diff --git a/CMakeLists.txt b/CMakeLists.txt --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ include(CMakePackageConfigHelpers) include(KDEInstallDirs) include(KDECompilerSettings NO_POLICY_SCOPE) +include(KDEClangFormat) include(KDECMakeSettings) include(FeatureSummary) include(GenerateExportHeader) @@ -55,4 +56,8 @@ install(FILES kgraphviewer.categories DESTINATION ${KDE_INSTALL_CONFDIR}) +# add clang-format target for all our real source files +file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES src/*.cpp src/*.h) +kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES}) + feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/KGraphEditorElementTreeWidget.h b/src/KGraphEditorElementTreeWidget.h --- a/src/KGraphEditorElementTreeWidget.h +++ b/src/KGraphEditorElementTreeWidget.h @@ -16,7 +16,6 @@ 02110-1301, USA */ - #ifndef _KGRAPHEDITORELEMENTTREEWIDGET_H_ #define _KGRAPHEDITORELEMENTTREEWIDGET_H_ @@ -30,36 +29,34 @@ */ class KGraphEditorElementTreeWidget : public QTreeWidget { - Q_OBJECT + Q_OBJECT public: - /** - * Default Constructor - */ - explicit KGraphEditorElementTreeWidget(QWidget* parent = nullptr); + /** + * Default Constructor + */ + explicit KGraphEditorElementTreeWidget(QWidget *parent = nullptr); - /** - * Default Destructor - */ - ~KGraphEditorElementTreeWidget() override; + /** + * Default Destructor + */ + ~KGraphEditorElementTreeWidget() override; protected: - - void contextMenuEvent(QContextMenuEvent* e) override; + void contextMenuEvent(QContextMenuEvent *e) override; protected Q_SLOTS: - void slotAddAttribute(); - void slotRemoveAttribute(); + void slotAddAttribute(); + void slotRemoveAttribute(); Q_SIGNALS: - void addAttribute(const QString&); - void removeAttribute(const QString&); + void addAttribute(const QString &); + void removeAttribute(const QString &); private: - void setupPopup(const QPoint& point); + void setupPopup(const QPoint &point); - QMenu* m_popup; - QTreeWidgetItem* m_item; + QMenu *m_popup; + QTreeWidgetItem *m_item; }; - #endif // _KGRAPHEDITORELEMENTTREEWIDGET_H_ diff --git a/src/KGraphEditorElementTreeWidget.cpp b/src/KGraphEditorElementTreeWidget.cpp --- a/src/KGraphEditorElementTreeWidget.cpp +++ b/src/KGraphEditorElementTreeWidget.cpp @@ -16,78 +16,72 @@ 02110-1301, USA */ - -#include "kgrapheditor_debug.h" #include "KGraphEditorElementTreeWidget.h" +#include "kgrapheditor_debug.h" -#include #include -#include #include +#include +#include #include -KGraphEditorElementTreeWidget::KGraphEditorElementTreeWidget(QWidget* parent) : - QTreeWidget(parent), - m_popup(nullptr), - m_item(nullptr) +KGraphEditorElementTreeWidget::KGraphEditorElementTreeWidget(QWidget *parent) + : QTreeWidget(parent) + , m_popup(nullptr) + , m_item(nullptr) { } KGraphEditorElementTreeWidget::~KGraphEditorElementTreeWidget() { } -void KGraphEditorElementTreeWidget::setupPopup(const QPoint& point) +void KGraphEditorElementTreeWidget::setupPopup(const QPoint &point) { - qCDebug(KGRAPHEDITOR_LOG) << point; - - if (m_popup) - { - delete m_popup; - } - m_popup = new QMenu(); - - m_item = itemAt(point); - QAction* aaa = new QAction(i18n("Add a new attribute"), this); - connect(aaa, &QAction::triggered, - this, &KGraphEditorElementTreeWidget::slotAddAttribute); - m_popup->addAction(aaa); - - if (m_item) // attribute item - { - QAction* raa = new QAction(i18n("Remove this attribute"), this); - connect(raa, &QAction::triggered, - this, &KGraphEditorElementTreeWidget::slotRemoveAttribute); - m_popup->addAction(raa); - } + qCDebug(KGRAPHEDITOR_LOG) << point; + + if (m_popup) { + delete m_popup; + } + m_popup = new QMenu(); + + m_item = itemAt(point); + QAction *aaa = new QAction(i18n("Add a new attribute"), this); + connect(aaa, &QAction::triggered, this, &KGraphEditorElementTreeWidget::slotAddAttribute); + m_popup->addAction(aaa); + + if (m_item) // attribute item + { + QAction *raa = new QAction(i18n("Remove this attribute"), this); + connect(raa, &QAction::triggered, this, &KGraphEditorElementTreeWidget::slotRemoveAttribute); + m_popup->addAction(raa); + } } void KGraphEditorElementTreeWidget::slotAddAttribute() { - QString nodeName = "NewAttribute"; - nodeName += QString::number(topLevelItemCount()); - emit addAttribute(nodeName); - QTreeWidgetItem* item = new QTreeWidgetItem(this, QStringList(nodeName)); - item->setFlags(item->flags() | Qt::ItemIsEditable); + QString nodeName = "NewAttribute"; + nodeName += QString::number(topLevelItemCount()); + emit addAttribute(nodeName); + QTreeWidgetItem *item = new QTreeWidgetItem(this, QStringList(nodeName)); + item->setFlags(item->flags() | Qt::ItemIsEditable); } void KGraphEditorElementTreeWidget::slotRemoveAttribute() { - qCDebug(KGRAPHEDITOR_LOG) << "Remove Attribute"; - if (m_item == nullptr) // should not happen - { - qCWarning(KGRAPHEDITOR_LOG) << "null item ; should not happen" << endl; - return; - } - emit removeAttribute(m_item->text(0)); - delete takeTopLevelItem (indexOfTopLevelItem(m_item)); - m_item = nullptr; + qCDebug(KGRAPHEDITOR_LOG) << "Remove Attribute"; + if (m_item == nullptr) // should not happen + { + qCWarning(KGRAPHEDITOR_LOG) << "null item ; should not happen" << endl; + return; + } + emit removeAttribute(m_item->text(0)); + delete takeTopLevelItem(indexOfTopLevelItem(m_item)); + m_item = nullptr; } - - -void KGraphEditorElementTreeWidget::contextMenuEvent ( QContextMenuEvent * e ) +void KGraphEditorElementTreeWidget::contextMenuEvent(QContextMenuEvent *e) { - setupPopup(e->pos()); - m_popup->exec(e->globalPos()); + setupPopup(e->pos()); + m_popup->exec(e->globalPos()); } diff --git a/src/KGraphEditorNodesTreeWidget.h b/src/KGraphEditorNodesTreeWidget.h --- a/src/KGraphEditorNodesTreeWidget.h +++ b/src/KGraphEditorNodesTreeWidget.h @@ -16,7 +16,6 @@ 02110-1301, USA */ - #ifndef _KGRAPHEDITORNODESTREEWIDGET_H_ #define _KGRAPHEDITORNODESTREEWIDGET_H_ @@ -30,40 +29,39 @@ */ class KGraphEditorNodesTreeWidget : public QTreeWidget { - Q_OBJECT + Q_OBJECT public: - /** - * Default Constructor - */ - explicit KGraphEditorNodesTreeWidget(QWidget* parent = nullptr); + /** + * Default Constructor + */ + explicit KGraphEditorNodesTreeWidget(QWidget *parent = nullptr); - /** - * Default Destructor - */ - ~KGraphEditorNodesTreeWidget() override; + /** + * Default Destructor + */ + ~KGraphEditorNodesTreeWidget() override; protected: - - void contextMenuEvent(QContextMenuEvent* e) override; + void contextMenuEvent(QContextMenuEvent *e) override; protected Q_SLOTS: - void slotRemoveNode(); - void slotAddAttribute(); - void slotRemoveAttribute(); + void slotRemoveNode(); + void slotAddAttribute(); + void slotRemoveAttribute(); public Q_SLOTS: - void slotRemoveElement(const QString& id); + void slotRemoveElement(const QString &id); Q_SIGNALS: - void removeNode(const QString&); - void addAttribute(const QString&); - void removeAttribute(const QString&,const QString&); + void removeNode(const QString &); + void addAttribute(const QString &); + void removeAttribute(const QString &, const QString &); private: - void setupPopup(const QPoint& point); + void setupPopup(const QPoint &point); - QMenu* m_popup; - QTreeWidgetItem* m_item; + QMenu *m_popup; + QTreeWidgetItem *m_item; }; #endif // _KGRAPHEDITORNODESTREEWIDGET_H_ diff --git a/src/KGraphEditorNodesTreeWidget.cpp b/src/KGraphEditorNodesTreeWidget.cpp --- a/src/KGraphEditorNodesTreeWidget.cpp +++ b/src/KGraphEditorNodesTreeWidget.cpp @@ -16,111 +16,99 @@ 02110-1301, USA */ - -#include "kgrapheditor_debug.h" #include "KGraphEditorNodesTreeWidget.h" +#include "kgrapheditor_debug.h" -#include #include +#include -#include #include +#include #include -KGraphEditorNodesTreeWidget::KGraphEditorNodesTreeWidget(QWidget* parent) : - QTreeWidget(parent), - m_popup(nullptr), - m_item(nullptr) +KGraphEditorNodesTreeWidget::KGraphEditorNodesTreeWidget(QWidget *parent) + : QTreeWidget(parent) + , m_popup(nullptr) + , m_item(nullptr) { } KGraphEditorNodesTreeWidget::~KGraphEditorNodesTreeWidget() { } -void KGraphEditorNodesTreeWidget::setupPopup(const QPoint& point) +void KGraphEditorNodesTreeWidget::setupPopup(const QPoint &point) { - qCDebug(KGRAPHEDITOR_LOG) << point; - - if (m_popup) - { - delete m_popup; - } - m_popup = new QMenu(); - - m_item = itemAt(point); - if (m_item == nullptr) - { - qCDebug(KGRAPHEDITOR_LOG) << "no item at" << point; - return; - } - QAction* aaa = new QAction(i18n("Add a new attribute"), this); - connect(aaa, &QAction::triggered, - this, &KGraphEditorNodesTreeWidget::slotAddAttribute); - m_popup->addAction(aaa); - - if (m_item->parent()) // attribute item - { - QAction* raa = new QAction(i18n("Remove this attribute"), this); - connect(raa, &QAction::triggered, - this, &KGraphEditorNodesTreeWidget::slotRemoveAttribute); - m_popup->addAction(raa); - } - m_popup->addSeparator(); - QAction* rna = new QAction(i18n("Remove this node"), this); - connect(rna, &QAction::triggered, - this, &KGraphEditorNodesTreeWidget::slotRemoveNode); - m_popup->addAction(rna); + qCDebug(KGRAPHEDITOR_LOG) << point; + + if (m_popup) { + delete m_popup; + } + m_popup = new QMenu(); + + m_item = itemAt(point); + if (m_item == nullptr) { + qCDebug(KGRAPHEDITOR_LOG) << "no item at" << point; + return; + } + QAction *aaa = new QAction(i18n("Add a new attribute"), this); + connect(aaa, &QAction::triggered, this, &KGraphEditorNodesTreeWidget::slotAddAttribute); + m_popup->addAction(aaa); + + if (m_item->parent()) // attribute item + { + QAction *raa = new QAction(i18n("Remove this attribute"), this); + connect(raa, &QAction::triggered, this, &KGraphEditorNodesTreeWidget::slotRemoveAttribute); + m_popup->addAction(raa); + } + m_popup->addSeparator(); + QAction *rna = new QAction(i18n("Remove this node"), this); + connect(rna, &QAction::triggered, this, &KGraphEditorNodesTreeWidget::slotRemoveNode); + m_popup->addAction(rna); } void KGraphEditorNodesTreeWidget::slotRemoveNode() { - emit removeNode(m_item->text(0)); - delete takeTopLevelItem (indexOfTopLevelItem(m_item)); - m_item = nullptr; + emit removeNode(m_item->text(0)); + delete takeTopLevelItem(indexOfTopLevelItem(m_item)); + m_item = nullptr; } -void KGraphEditorNodesTreeWidget::slotRemoveElement(const QString& id) +void KGraphEditorNodesTreeWidget::slotRemoveElement(const QString &id) { - qCDebug(KGRAPHEDITOR_LOG) << id; - QList items = findItems(id,Qt::MatchExactly,0); - foreach (QTreeWidgetItem* item, items) - { - delete takeTopLevelItem (indexOfTopLevelItem(item)); - } + qCDebug(KGRAPHEDITOR_LOG) << id; + QList items = findItems(id, Qt::MatchExactly, 0); + foreach (QTreeWidgetItem *item, items) { + delete takeTopLevelItem(indexOfTopLevelItem(item)); + } } void KGraphEditorNodesTreeWidget::slotAddAttribute() { - qCDebug(KGRAPHEDITOR_LOG) << "Add Attribute"; - QString nodeName = "NewAttribute"; - emit addAttribute(m_item->text(0)); - if (m_item->parent() == nullptr) - { - nodeName += QString::number(m_item->childCount()); - QTreeWidgetItem* item = new QTreeWidgetItem(m_item, QStringList(nodeName)); - item->setFlags(item->flags() | Qt::ItemIsEditable); - } - else - { - nodeName += QString::number(m_item->parent()->childCount()); - QTreeWidgetItem* item = new QTreeWidgetItem(m_item->parent(), QStringList(nodeName)); - item->setFlags(item->flags() | Qt::ItemIsEditable); - } - } + qCDebug(KGRAPHEDITOR_LOG) << "Add Attribute"; + QString nodeName = "NewAttribute"; + emit addAttribute(m_item->text(0)); + if (m_item->parent() == nullptr) { + nodeName += QString::number(m_item->childCount()); + QTreeWidgetItem *item = new QTreeWidgetItem(m_item, QStringList(nodeName)); + item->setFlags(item->flags() | Qt::ItemIsEditable); + } else { + nodeName += QString::number(m_item->parent()->childCount()); + QTreeWidgetItem *item = new QTreeWidgetItem(m_item->parent(), QStringList(nodeName)); + item->setFlags(item->flags() | Qt::ItemIsEditable); + } +} void KGraphEditorNodesTreeWidget::slotRemoveAttribute() { - qCDebug(KGRAPHEDITOR_LOG) << "Remove Attribute"; - emit removeAttribute(m_item->parent()->text(0), m_item->text(0)); - m_item->parent()->removeChild(m_item); - m_item = nullptr; + qCDebug(KGRAPHEDITOR_LOG) << "Remove Attribute"; + emit removeAttribute(m_item->parent()->text(0), m_item->text(0)); + m_item->parent()->removeChild(m_item); + m_item = nullptr; } - - -void KGraphEditorNodesTreeWidget::contextMenuEvent ( QContextMenuEvent * e ) +void KGraphEditorNodesTreeWidget::contextMenuEvent(QContextMenuEvent *e) { - setupPopup(e->pos()); - m_popup->exec(e->globalPos()); + setupPopup(e->pos()); + m_popup->exec(e->globalPos()); } diff --git a/src/Singleton.h b/src/Singleton.h --- a/src/Singleton.h +++ b/src/Singleton.h @@ -16,7 +16,6 @@ 02110-1301, USA */ - #ifndef KGRAPHVIEWER_SINGLETON_H #define KGRAPHVIEWER_SINGLETON_H @@ -26,48 +25,39 @@ * @short Singleton pattern implementation * @author Gaƫl de Chalendar */ -template -class Singleton +template class Singleton { public: + /** + * @brief const singleton accessor + */ + static const Object &single(); - /** - * @brief const singleton accessor - */ - static const Object& single(); - - /** - * @brief singleton accessor - */ - static Object& changeable(); - + /** + * @brief singleton accessor + */ + static Object &changeable(); private: - static Object* s_instance; - + static Object *s_instance; }; -template -Object* Singleton::s_instance(nullptr); +template Object *Singleton::s_instance(nullptr); -template -const Object& Singleton::single() +template const Object &Singleton::single() { - if (s_instance == nullptr) - { - s_instance=new Object(); - } - return *s_instance; + if (s_instance == nullptr) { + s_instance = new Object(); + } + return *s_instance; } -template -Object& Singleton::changeable() +template Object &Singleton::changeable() { - if (s_instance == nullptr) - { - s_instance=new Object(); - } - return *s_instance; + if (s_instance == nullptr) { + s_instance = new Object(); + } + return *s_instance; } #endif diff --git a/src/kgrapheditor.h b/src/kgrapheditor.h --- a/src/kgrapheditor.h +++ b/src/kgrapheditor.h @@ -16,15 +16,14 @@ 02110-1301, USA */ - #ifndef _KGRAPHEDITOR_H_ #define _KGRAPHEDITOR_H_ +#include +#include #include #include #include -#include -#include #include @@ -38,140 +37,141 @@ namespace KParts { - class ReadOnlyPart; +class ReadOnlyPart; } - /** +/** * This is the application "Shell". It has a menubar, toolbar, and * statusbar but relies on the "Part" to do all the real work. * * @short Application Shell * @author Gael de Chalendar */ class KGraphEditor : public KParts::MainWindow { - Q_OBJECT + Q_OBJECT public: - /** - * Default Constructor - */ - KGraphEditor(); + /** + * Default Constructor + */ + KGraphEditor(); - /** - * Default Destructor - */ - ~KGraphEditor() override; + /** + * Default Destructor + */ + ~KGraphEditor() override; - /** - * Use this method to load whatever file/URL you have - */ - void openUrl(const QUrl& url); + /** + * Use this method to load whatever file/URL you have + */ + void openUrl(const QUrl &url); - void reloadPreviousFiles(); + void reloadPreviousFiles(); protected: - void closeEvent(QCloseEvent *event) override; + void closeEvent(QCloseEvent *event) override; Q_SIGNALS: - void hide(KParts::Part* part); - void prepareAddNewElement(QMap attribs); - void prepareAddNewEdge(QMap attribs); - void setReadWrite(); - void saveTo(const QString& fileName); - - void selectNode(const QString&); - void removeNode(const QString&); - void removeElement(const QString&); - void addAttribute(const QString&); - void removeAttribute(const QString&,const QString&); - void setAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue); - void update(); - void saddNewEdge(QString src, QString tgt, QMap attribs); - void renameNode(const QString& oldName, const QString& newName); + void hide(KParts::Part *part); + void prepareAddNewElement(QMap attribs); + void prepareAddNewEdge(QMap attribs); + void setReadWrite(); + void saveTo(const QString &fileName); + + void selectNode(const QString &); + void removeNode(const QString &); + void removeElement(const QString &); + void addAttribute(const QString &); + void removeAttribute(const QString &, const QString &); + void setAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue); + void update(); + void saddNewEdge(QString src, QString tgt, QMap attribs); + void renameNode(const QString &oldName, const QString &newName); public Q_SLOTS: - /** - * Use this method to load whatever file/URL you have - */ - void openUrl(const QString& url) { - openUrl(QUrl::fromUserInput(url, QDir::currentPath(), QUrl::AssumeLocalFile)); - } - - void slotSetActiveGraph(KParts::ReadOnlyPart* part); - - void slotGraphLoaded(); - - void slotRemoveNode(const QString&); - void slotAddAttribute(const QString&); - void slotRemoveAttribute(const QString&,const QString&); - - void slotNewElementItemChanged(QTreeWidgetItem*,int); - void slotAddNewElementAttribute(const QString&); - void slotRemoveNewElementAttribute(const QString&); - - void slotNewNodeAdded(const QString& id); - void slotNewEdgeAdded(const QString& ids, const QString& idt); - /*public slots: - void reloadOnChangeMode_pressed(int value); - void openInExistingWindowMode_pressed(int value); - void reopenPreviouslyOpenedFilesMode_pressed(int value);*/ - void slotRemoveElement(const QString& id); - void slotSelectionIs(const QList&, const QPoint&p); - void slotNewEdgeFinished( const QString&, const QString&, const QMap&); + /** + * Use this method to load whatever file/URL you have + */ + void openUrl(const QString &url) + { + openUrl(QUrl::fromUserInput(url, QDir::currentPath(), QUrl::AssumeLocalFile)); + } + + void slotSetActiveGraph(KParts::ReadOnlyPart *part); + + void slotGraphLoaded(); + + void slotRemoveNode(const QString &); + void slotAddAttribute(const QString &); + void slotRemoveAttribute(const QString &, const QString &); + + void slotNewElementItemChanged(QTreeWidgetItem *, int); + void slotAddNewElementAttribute(const QString &); + void slotRemoveNewElementAttribute(const QString &); + + void slotNewNodeAdded(const QString &id); + void slotNewEdgeAdded(const QString &ids, const QString &idt); + /*public slots: + void reloadOnChangeMode_pressed(int value); + void openInExistingWindowMode_pressed(int value); + void reopenPreviouslyOpenedFilesMode_pressed(int value);*/ + void slotRemoveElement(const QString &id); + void slotSelectionIs(const QList &, const QPoint &p); + void slotNewEdgeFinished(const QString &, const QString &, const QMap &); private Q_SLOTS: - void fileNew(); - void fileOpen(); - void fileSave(); - void fileSaveAs(); - void close(int index); - void close(); - void slotURLSelected(const QUrl&); - void optionsShowToolbar(); - void optionsShowStatusbar(); - void optionsConfigureKeys(); - void optionsConfigureToolbars(); - void optionsConfigure(); - void newTabSelectedSlot(int index); - - void applyNewToolbarConfig(); - void slotItemChanged ( QTreeWidgetItem * item, int column ); - void slotItemClicked ( QTreeWidgetItem * item, int column ); - void slotEditNewVertex(); - void slotEditNewEdge(); - - void slotParsingModeExternalToggled(bool value); - void slotParsingModeInternalToggled(bool value); - - void slotHoverEnter(const QString&); - void slotHoverLeave(const QString&); - - KParts::ReadOnlyPart *slotNewGraph(); - + void fileNew(); + void fileOpen(); + void fileSave(); + void fileSaveAs(); + void close(int index); + void close(); + void slotURLSelected(const QUrl &); + void optionsShowToolbar(); + void optionsShowStatusbar(); + void optionsConfigureKeys(); + void optionsConfigureToolbars(); + void optionsConfigure(); + void newTabSelectedSlot(int index); + + void applyNewToolbarConfig(); + void slotItemChanged(QTreeWidgetItem *item, int column); + void slotItemClicked(QTreeWidgetItem *item, int column); + void slotEditNewVertex(); + void slotEditNewEdge(); + + void slotParsingModeExternalToggled(bool value); + void slotParsingModeInternalToggled(bool value); + + void slotHoverEnter(const QString &); + void slotHoverLeave(const QString &); + + KParts::ReadOnlyPart *slotNewGraph(); + private: - void setupAccel(); - void setupActions(); - + void setupAccel(); + void setupActions(); + private: - KGraphEditorNodesTreeWidget* m_treeWidget; - KGraphEditorElementTreeWidget* m_newElementAttributesWidget; - QTabWidget* m_widget; - KRecentFilesAction* m_rfa; - KParts::PartManager* m_manager; + KGraphEditorNodesTreeWidget *m_treeWidget; + KGraphEditorElementTreeWidget *m_newElementAttributesWidget; + QTabWidget *m_widget; + KRecentFilesAction *m_rfa; + KParts::PartManager *m_manager; + + KToggleAction *m_toolbarAction; + KToggleAction *m_statusbarAction; + QAction *m_closeAction; - KToggleAction *m_toolbarAction; - KToggleAction *m_statusbarAction; - QAction *m_closeAction; + QStringList m_openedFiles; - QStringList m_openedFiles; - - QMap m_tabsPartsMap; - QMap m_tabsFilesMap; - KParts::ReadOnlyPart* m_currentPart; + QMap m_tabsPartsMap; + QMap m_tabsFilesMap; + KParts::ReadOnlyPart *m_currentPart; - QMap m_newElementAttributes; + QMap m_newElementAttributes; - QString m_currentTreeWidgetItemText; + QString m_currentTreeWidgetItemText; }; #endif // _KGRAPHEDITOR_H_ diff --git a/src/kgrapheditor.cpp b/src/kgrapheditor.cpp --- a/src/kgrapheditor.cpp +++ b/src/kgrapheditor.cpp @@ -16,407 +16,379 @@ 02110-1301, USA */ - #include "kgrapheditor.h" +#include "KGraphEditorElementTreeWidget.h" +#include "KGraphEditorNodesTreeWidget.h" #include "kgrapheditorConfigDialog.h" -#include "kgrapheditorsettings.h" #include "kgrapheditor_debug.h" -#include "KGraphEditorNodesTreeWidget.h" -#include "KGraphEditorElementTreeWidget.h" -#include "ui_preferencesReload.h" -#include "ui_preferencesParsing.h" +#include "kgrapheditorsettings.h" +#include "part/kgraphviewer_part.h" #include "ui_preferencesOpenInExistingWindow.h" +#include "ui_preferencesParsing.h" +#include "ui_preferencesReload.h" #include "ui_preferencesReopenPreviouslyOpenedFiles.h" -#include "part/kgraphviewer_part.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include +#include +#include +#include #include +#include #include +#include +#include +#include +#include +#include #include -#include +#include +#include +#include #include +#include +#include +#include #include -#include -#include -#include -#include -#include #include using namespace KGraphViewer; -KGraphEditor::KGraphEditor() : - KParts::MainWindow(), - m_rfa(nullptr), - m_currentPart(nullptr) -{ - // set the shell's ui resource file - setXMLFile("kgrapheditorui.rc"); - - m_widget = new QTabWidget(this); - m_widget->setTabsClosable(true); - connect(m_widget, SIGNAL(tabCloseRequested(int)), this, SLOT(close(int))); - connect(m_widget, SIGNAL(currentChanged(int)), this, SLOT(newTabSelectedSlot(int))); - - setCentralWidget(m_widget); - - QDockWidget* topLeftDockWidget = new QDockWidget(this); - topLeftDockWidget->setObjectName(QStringLiteral("TopLeftDockWidget")); - m_treeWidget = new KGraphEditorNodesTreeWidget(topLeftDockWidget); - connect(m_treeWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this,SLOT(slotItemChanged(QTreeWidgetItem*,int))); - connect(m_treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)), - this,SLOT(slotItemClicked(QTreeWidgetItem*,int))); - connect(m_treeWidget, SIGNAL(removeNode(QString)), - this, SLOT(slotRemoveNode(QString))); - connect(m_treeWidget, SIGNAL(addAttribute(QString)), - this, SLOT(slotAddAttribute(QString))); - connect(m_treeWidget, SIGNAL(removeAttribute(QString,QString)), - this, SLOT(slotRemoveAttribute(QString,QString))); - -// m_treeWidget->setItemDelegate(new VariantDelegate(m_treeWidget)); - m_treeWidget->setColumnCount(2); - topLeftDockWidget->setWidget(m_treeWidget); - addDockWidget ( Qt::LeftDockWidgetArea, topLeftDockWidget ); - - QDockWidget* bottomLeftDockWidget = new QDockWidget(this); - bottomLeftDockWidget->setObjectName(QStringLiteral("BottomLeftDockWidget")); - m_newElementAttributesWidget = new KGraphEditorElementTreeWidget(bottomLeftDockWidget); - connect(m_newElementAttributesWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this,SLOT(slotNewElementItemChanged(QTreeWidgetItem*,int))); - connect(m_newElementAttributesWidget, SIGNAL(addAttribute(QString)), - this, SLOT(slotAddNewElementAttribute(QString))); - connect(m_newElementAttributesWidget, SIGNAL(removeAttribute(QString)), - this, SLOT(slotRemoveNewElementAttribute(QString))); - m_newElementAttributesWidget->setColumnCount(2); - bottomLeftDockWidget->setWidget(m_newElementAttributesWidget); - addDockWidget ( Qt::LeftDockWidgetArea, bottomLeftDockWidget ); - - - if (QDBusConnection::sessionBus().registerService( "org.kde.kgrapheditor" )) - { - qCDebug(KGRAPHEDITOR_LOG) << "Service Registered successfully"; - QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportAllSlots); - - } - else - { - qCDebug(KGRAPHEDITOR_LOG) << "Failed to register service..."; - } - - // Create a KParts part manager, to handle part activation/deactivation - m_manager = new KParts::PartManager( this ); - - // When the manager says the active part changes, the window updates (recreates) the GUI - connect( m_manager, SIGNAL(activePartChanged(KParts::Part*)), - this, SLOT(createGUI(KParts::Part*)) ); - - setupGUI(ToolBar | Keys | StatusBar | Save); - - // then, setup our actions - setupActions(); - - // this routine will find and load our Part. it finds the Part by - // name which is a bad idea usually.. but it's alright in this - // case since our Part is made for this Shell - - // Creates the GUI with a null part to make appear the main app menus and tools - createGUI(0); +KGraphEditor::KGraphEditor() + : KParts::MainWindow() + , m_rfa(nullptr) + , m_currentPart(nullptr) +{ + // set the shell's ui resource file + setXMLFile("kgrapheditorui.rc"); + + m_widget = new QTabWidget(this); + m_widget->setTabsClosable(true); + connect(m_widget, SIGNAL(tabCloseRequested(int)), this, SLOT(close(int))); + connect(m_widget, SIGNAL(currentChanged(int)), this, SLOT(newTabSelectedSlot(int))); + + setCentralWidget(m_widget); + + QDockWidget *topLeftDockWidget = new QDockWidget(this); + topLeftDockWidget->setObjectName(QStringLiteral("TopLeftDockWidget")); + m_treeWidget = new KGraphEditorNodesTreeWidget(topLeftDockWidget); + connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemChanged(QTreeWidgetItem *, int))); + connect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(slotItemClicked(QTreeWidgetItem *, int))); + connect(m_treeWidget, SIGNAL(removeNode(QString)), this, SLOT(slotRemoveNode(QString))); + connect(m_treeWidget, SIGNAL(addAttribute(QString)), this, SLOT(slotAddAttribute(QString))); + connect(m_treeWidget, SIGNAL(removeAttribute(QString, QString)), this, SLOT(slotRemoveAttribute(QString, QString))); + + // m_treeWidget->setItemDelegate(new VariantDelegate(m_treeWidget)); + m_treeWidget->setColumnCount(2); + topLeftDockWidget->setWidget(m_treeWidget); + addDockWidget(Qt::LeftDockWidgetArea, topLeftDockWidget); + + QDockWidget *bottomLeftDockWidget = new QDockWidget(this); + bottomLeftDockWidget->setObjectName(QStringLiteral("BottomLeftDockWidget")); + m_newElementAttributesWidget = new KGraphEditorElementTreeWidget(bottomLeftDockWidget); + connect(m_newElementAttributesWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotNewElementItemChanged(QTreeWidgetItem *, int))); + connect(m_newElementAttributesWidget, SIGNAL(addAttribute(QString)), this, SLOT(slotAddNewElementAttribute(QString))); + connect(m_newElementAttributesWidget, SIGNAL(removeAttribute(QString)), this, SLOT(slotRemoveNewElementAttribute(QString))); + m_newElementAttributesWidget->setColumnCount(2); + bottomLeftDockWidget->setWidget(m_newElementAttributesWidget); + addDockWidget(Qt::LeftDockWidgetArea, bottomLeftDockWidget); + + if (QDBusConnection::sessionBus().registerService("org.kde.kgrapheditor")) { + qCDebug(KGRAPHEDITOR_LOG) << "Service Registered successfully"; + QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportAllSlots); + + } else { + qCDebug(KGRAPHEDITOR_LOG) << "Failed to register service..."; + } + + // Create a KParts part manager, to handle part activation/deactivation + m_manager = new KParts::PartManager(this); + + // When the manager says the active part changes, the window updates (recreates) the GUI + connect(m_manager, SIGNAL(activePartChanged(KParts::Part *)), this, SLOT(createGUI(KParts::Part *))); + + setupGUI(ToolBar | Keys | StatusBar | Save); + + // then, setup our actions + setupActions(); + + // this routine will find and load our Part. it finds the Part by + // name which is a bad idea usually.. but it's alright in this + // case since our Part is made for this Shell + + // Creates the GUI with a null part to make appear the main app menus and tools + createGUI(0); } KGraphEditor::~KGraphEditor() { } void KGraphEditor::reloadPreviousFiles() { - QStringList previouslyOpenedFiles = KGraphEditorSettings::previouslyOpenedFiles(); - if ( (previouslyOpenedFiles.empty() == false) - && (QMessageBox::question(this, - i18n("Session Restore"), - i18n("Do you want to reload files from previous session?")) == QMessageBox::Yes) ) - { - QStringList::const_iterator it, it_end; - it = previouslyOpenedFiles.constBegin(); it_end = previouslyOpenedFiles.constEnd(); - for (; it != it_end; it++) - { - openUrl(*it); + QStringList previouslyOpenedFiles = KGraphEditorSettings::previouslyOpenedFiles(); + if ((previouslyOpenedFiles.empty() == false) && (QMessageBox::question(this, i18n("Session Restore"), i18n("Do you want to reload files from previous session?")) == QMessageBox::Yes)) { + QStringList::const_iterator it, it_end; + it = previouslyOpenedFiles.constBegin(); + it_end = previouslyOpenedFiles.constEnd(); + for (; it != it_end; it++) { + openUrl(*it); + } } - } } KParts::ReadOnlyPart *KGraphEditor::slotNewGraph() { - KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory(); - if (!factory) - { - // if we couldn't find our Part, we exit since the Shell by - // itself can't do anything useful - QMessageBox::critical(this, i18n("Unable to start"), i18n("Could not find the KGraphViewer part.")); - qApp->quit(); - // we return here, cause kapp->quit() only means "exit the - // next time we enter the event loop... - return nullptr; - } - KParts::ReadOnlyPart* part = factory->create(this); - KGraphViewerInterface *view = qobject_cast(part); - if (!view) - { - // This should not happen - qCWarning(KGRAPHEDITOR_LOG) << "Failed to get KPart" << endl; - return nullptr; - } - view->setReadWrite(); + KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory(); + if (!factory) { + // if we couldn't find our Part, we exit since the Shell by + // itself can't do anything useful + QMessageBox::critical(this, i18n("Unable to start"), i18n("Could not find the KGraphViewer part.")); + qApp->quit(); + // we return here, cause kapp->quit() only means "exit the + // next time we enter the event loop... + return nullptr; + } + KParts::ReadOnlyPart *part = factory->create(this); + KGraphViewerInterface *view = qobject_cast(part); + if (!view) { + // This should not happen + qCWarning(KGRAPHEDITOR_LOG) << "Failed to get KPart" << endl; + return nullptr; + } + view->setReadWrite(); QWidget *w = part->widget(); m_tabsPartsMap[w] = part; m_tabsFilesMap[w] = ""; - connect(this,SIGNAL(hide(KParts::Part*)),part,SLOT(slotHide(KParts::Part*))); + connect(this, SIGNAL(hide(KParts::Part *)), part, SLOT(slotHide(KParts::Part *))); m_manager->addPart(part, true); m_widget->addTab(w, QIcon::fromTheme("kgraphviewer"), ""); m_widget->setCurrentWidget(w); m_closeAction->setEnabled(true); - return part; + return part; } -void KGraphEditor::openUrl(const QUrl& url) +void KGraphEditor::openUrl(const QUrl &url) { - qCDebug(KGRAPHEDITOR_LOG) << url; - KParts::ReadOnlyPart *part = slotNewGraph(); + qCDebug(KGRAPHEDITOR_LOG) << url; + KParts::ReadOnlyPart *part = slotNewGraph(); -// (KGraphEditorSettings::parsingMode() == "external") -// ?kgv->setLayoutMethod(KGraphViewerInterface::ExternalProgram) -// :kgv->setLayoutMethod(KGraphViewerInterface::InternalLibrary); + // (KGraphEditorSettings::parsingMode() == "external") + // ?kgv->setLayoutMethod(KGraphViewerInterface::ExternalProgram) + // :kgv->setLayoutMethod(KGraphViewerInterface::InternalLibrary); - QString label = url.path().section('/',-1,-1); - // @TODO set label - m_widget->setTabText(m_widget->currentIndex(), label); - m_tabsFilesMap[m_widget->currentWidget()] = url.path(); - part->openUrl(url); + QString label = url.path().section('/', -1, -1); + // @TODO set label + m_widget->setTabText(m_widget->currentIndex(), label); + m_tabsFilesMap[m_widget->currentWidget()] = url.path(); + part->openUrl(url); - if (m_rfa) { - m_rfa->addUrl(url); - } + if (m_rfa) { + m_rfa->addUrl(url); + } - m_openedFiles.push_back(url.path()); + m_openedFiles.push_back(url.path()); } void KGraphEditor::fileOpen() { - // this slot is called whenever the File->Open menu is selected, - // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar - // button is clicked - QFileDialog fileDialog(this); - fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); - fileDialog.setAcceptMode(QFileDialog::AcceptOpen); - fileDialog.setFileMode(QFileDialog::ExistingFiles); - if (fileDialog.exec() != QFileDialog::Accepted) { - return; - } - - foreach (const QUrl& url, fileDialog.selectedUrls()) { - openUrl(url); - } -} + // this slot is called whenever the File->Open menu is selected, + // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar + // button is clicked + QFileDialog fileDialog(this); + fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); + fileDialog.setAcceptMode(QFileDialog::AcceptOpen); + fileDialog.setFileMode(QFileDialog::ExistingFiles); + if (fileDialog.exec() != QFileDialog::Accepted) { + return; + } + foreach (const QUrl &url, fileDialog.selectedUrls()) { + openUrl(url); + } +} void KGraphEditor::setupActions() { - // create our actions + // create our actions - actionCollection()->addAction( KStandardAction::New, "file_new", this, SLOT(fileNew()) ); - actionCollection()->addAction( KStandardAction::Open, "file_open", this, SLOT(fileOpen()) ); - m_rfa = (KRecentFilesAction*) actionCollection()->addAction(KStandardAction::OpenRecent, "file_open_recent", this, SLOT(slotURLSelected(QUrl)) ); - m_rfa->loadEntries(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); - actionCollection()->addAction( KStandardAction::Save, "file_save", this, SLOT(fileSave()) ); - actionCollection()->addAction( KStandardAction::SaveAs, "file_save_as", this, SLOT(fileSaveAs()) ); + actionCollection()->addAction(KStandardAction::New, "file_new", this, SLOT(fileNew())); + actionCollection()->addAction(KStandardAction::Open, "file_open", this, SLOT(fileOpen())); + m_rfa = (KRecentFilesAction *)actionCollection()->addAction(KStandardAction::OpenRecent, "file_open_recent", this, SLOT(slotURLSelected(QUrl))); + m_rfa->loadEntries(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); + actionCollection()->addAction(KStandardAction::Save, "file_save", this, SLOT(fileSave())); + actionCollection()->addAction(KStandardAction::SaveAs, "file_save_as", this, SLOT(fileSaveAs())); - m_closeAction = actionCollection()->addAction( KStandardAction::Close, "file_close", this, SLOT(close()) ); - m_closeAction->setWhatsThis(i18n("Closes the current file")); - m_closeAction->setEnabled(false); + m_closeAction = actionCollection()->addAction(KStandardAction::Close, "file_close", this, SLOT(close())); + m_closeAction->setWhatsThis(i18n("Closes the current file")); + m_closeAction->setEnabled(false); - actionCollection()->addAction( KStandardAction::Quit, "file_quit", qApp, SLOT(quit()) ); + actionCollection()->addAction(KStandardAction::Quit, "file_quit", qApp, SLOT(quit())); - m_statusbarAction = KStandardAction::showStatusbar(this, SLOT(optionsShowStatusbar()), this); + m_statusbarAction = KStandardAction::showStatusbar(this, SLOT(optionsShowStatusbar()), this); - actionCollection()->addAction( KStandardAction::KeyBindings, "options_configure_keybinding", this, SLOT(optionsConfigureKeys()) ); -// KStandardAction::keyBindings(this, SLOT(optionsConfigureKeys()), this); - actionCollection()->addAction( KStandardAction::ConfigureToolbars, "options_configure_toolbars", this, SLOT(optionsConfigureToolbars()) ); - actionCollection()->addAction( KStandardAction::Preferences, "options_configure", this, SLOT(optionsConfigure()) ); + actionCollection()->addAction(KStandardAction::KeyBindings, "options_configure_keybinding", this, SLOT(optionsConfigureKeys())); + // KStandardAction::keyBindings(this, SLOT(optionsConfigureKeys()), this); + actionCollection()->addAction(KStandardAction::ConfigureToolbars, "options_configure_toolbars", this, SLOT(optionsConfigureToolbars())); + actionCollection()->addAction(KStandardAction::Preferences, "options_configure", this, SLOT(optionsConfigure())); - QAction* edit_new_vertex = actionCollection()->addAction( "edit_new_vertex" ); - edit_new_vertex->setText(i18n("Create a New Vertex")); - edit_new_vertex->setIcon(QPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newnode.png"))); - connect( edit_new_vertex, SIGNAL(triggered(bool)), this, SLOT(slotEditNewVertex()) ); + QAction *edit_new_vertex = actionCollection()->addAction("edit_new_vertex"); + edit_new_vertex->setText(i18n("Create a New Vertex")); + edit_new_vertex->setIcon(QPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newnode.png"))); + connect(edit_new_vertex, SIGNAL(triggered(bool)), this, SLOT(slotEditNewVertex())); - QAction* edit_new_edge = actionCollection()->addAction( "edit_new_edge" ); - edit_new_edge->setText(i18n("Create a New Edge")); - edit_new_edge->setIcon(QPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newedge.png"))); - connect( edit_new_edge, SIGNAL(triggered(bool)), this, SLOT(slotEditNewEdge()) ); + QAction *edit_new_edge = actionCollection()->addAction("edit_new_edge"); + edit_new_edge->setText(i18n("Create a New Edge")); + edit_new_edge->setIcon(QPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newedge.png"))); + connect(edit_new_edge, SIGNAL(triggered(bool)), this, SLOT(slotEditNewEdge())); } void KGraphEditor::closeEvent(QCloseEvent *event) { - KGraphEditorSettings::setPreviouslyOpenedFiles(m_openedFiles); - m_rfa->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); + KGraphEditorSettings::setPreviouslyOpenedFiles(m_openedFiles); + m_rfa->saveEntries(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); - KGraphEditorSettings::self()->save(); - KXmlGuiWindow::closeEvent(event); + KGraphEditorSettings::self()->save(); + KXmlGuiWindow::closeEvent(event); } void KGraphEditor::fileNew() { - // this slot is called whenever the File->New menu is selected, - // the New shortcut is pressed (usually CTRL+N) or the New toolbar - // button is clicked + // this slot is called whenever the File->New menu is selected, + // the New shortcut is pressed (usually CTRL+N) or the New toolbar + // button is clicked - slotNewGraph(); + slotNewGraph(); } - void KGraphEditor::optionsShowToolbar() { - // this is all very cut and paste code for showing/hiding the - // toolbar - if (m_toolbarAction->isChecked()) - toolBar()->show(); - else - toolBar()->hide(); + // this is all very cut and paste code for showing/hiding the + // toolbar + if (m_toolbarAction->isChecked()) + toolBar()->show(); + else + toolBar()->hide(); } void KGraphEditor::optionsShowStatusbar() { - // this is all very cut and paste code for showing/hiding the - // statusbar - if (m_statusbarAction->isChecked()) - statusBar()->show(); - else - statusBar()->hide(); + // this is all very cut and paste code for showing/hiding the + // statusbar + if (m_statusbarAction->isChecked()) + statusBar()->show(); + else + statusBar()->hide(); } void KGraphEditor::optionsConfigureKeys() { - KShortcutsDialog::configure(actionCollection()); + KShortcutsDialog::configure(actionCollection()); } void KGraphEditor::optionsConfigureToolbars() { KConfigGroup conf(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); saveMainWindowSettings(conf); - // use the standard toolbar editor - KEditToolBar dlg(factory()); - connect(&dlg, SIGNAL(newToolbarConfig()), - this, SLOT(applyNewToolbarConfig())); - dlg.exec(); + // use the standard toolbar editor + KEditToolBar dlg(factory()); + connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(applyNewToolbarConfig())); + dlg.exec(); } void KGraphEditor::optionsConfigure() { - //An instance of your dialog could be already created and could be cached, - //in which case you want to display the cached dialog instead of creating - //another one - if ( KgeConfigurationDialog::showDialog( "settings" ) ) - return; - - //KConfigDialog didn't find an instance of this dialog, so lets create it : - KgeConfigurationDialog* dialog = new KgeConfigurationDialog(this, "settings", KGraphEditorSettings::self()); - - Ui::KGraphViewerPreferencesParsingWidget* parsingWidget = dialog->m_parsingWidget; - qCDebug(KGRAPHEDITOR_LOG) << KGraphEditorSettings::parsingMode(); - if (KGraphEditorSettings::parsingMode() == "external") - { - parsingWidget->external->setChecked(true); - } - else if (KGraphEditorSettings::parsingMode() == "internal") - { - parsingWidget->internal->setChecked(true); - } - connect((QObject*)parsingWidget->external, SIGNAL(toggled(bool)), this, SLOT(slotParsingModeExternalToggled(bool)) ); - connect((QObject*)parsingWidget->internal, SIGNAL(toggled(bool)), this, SLOT(slotParsingModeInternalToggled(bool)) ); - - -/* KGraphViewerPreferencesReloadWidget* reloadWidget = - new KGraphViewerPreferencesReloadWidget( 0, "KGraphViewer Settings" ); - if (KGraphEditorSettings::reloadOnChangeMode() == "yes") - { - reloadWidget->reloadOnChangeMode->setButton(0); - } - else if (KGraphEditorSettings::reloadOnChangeMode() == "no") - { - reloadWidget->reloadOnChangeMode->setButton(1); - } - else if (KGraphEditorSettings::reloadOnChangeMode() == "ask") - { - reloadWidget->reloadOnChangeMode->setButton(2); - } - - connect((QObject*)reloadWidget->reloadOnChangeMode, SIGNAL(clicked(int)), this, SLOT(reloadOnChangeMode_pressed(int)) ); - - dialog->addPage( reloadWidget, i18n("Reloading"), "kgraphreloadoptions", i18n("Reloading"), true); - - KGraphViewerPreferencesOpenInExistingWindowWidget* openingWidget = - new KGraphViewerPreferencesOpenInExistingWindowWidget( 0, "KGraphViewer Settings" ); - if (KGraphEditorSettings::openInExistingWindowMode() == "yes") - { - openingWidget->openInExistingWindowMode->setButton(0); - } - else if (KGraphEditorSettings::openInExistingWindowMode() == "no") - { - openingWidget->openInExistingWindowMode->setButton(1); - } - else if (KGraphEditorSettings::openInExistingWindowMode() == "ask") - { - openingWidget->openInExistingWindowMode->setButton(2); - } - - connect((QObject*)openingWidget->openInExistingWindowMode, SIGNAL(clicked(int)), this, SLOT(openInExistingWindowMode_pressed(int)) ); - - dialog->addPage( openingWidget, i18n("Opening"), "kgraphopeningoptions", i18n("Opening"), true); - - KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget* reopeningWidget = - new KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget( 0, "KGraphViewer Settings" ); - if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "yes") - { - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); - } - else if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "no") - { - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); - } - else if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "ask") - { - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2); - } - - connect((QObject*)reopeningWidget->reopenPreviouslyOpenedFilesMode, SIGNAL(clicked(int)), this, SLOT(reopenPreviouslyOpenedFilesMode_pressed(int)) ); - - dialog->addPage( reopeningWidget, i18n("Session Management"), "kgraphreopeningoptions", i18n("Session Management"), true); - */ -// connect(dialog, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); - - dialog->show(); + // An instance of your dialog could be already created and could be cached, + // in which case you want to display the cached dialog instead of creating + // another one + if (KgeConfigurationDialog::showDialog("settings")) + return; + + // KConfigDialog didn't find an instance of this dialog, so lets create it : + KgeConfigurationDialog *dialog = new KgeConfigurationDialog(this, "settings", KGraphEditorSettings::self()); + + Ui::KGraphViewerPreferencesParsingWidget *parsingWidget = dialog->m_parsingWidget; + qCDebug(KGRAPHEDITOR_LOG) << KGraphEditorSettings::parsingMode(); + if (KGraphEditorSettings::parsingMode() == "external") { + parsingWidget->external->setChecked(true); + } else if (KGraphEditorSettings::parsingMode() == "internal") { + parsingWidget->internal->setChecked(true); + } + connect((QObject *)parsingWidget->external, SIGNAL(toggled(bool)), this, SLOT(slotParsingModeExternalToggled(bool))); + connect((QObject *)parsingWidget->internal, SIGNAL(toggled(bool)), this, SLOT(slotParsingModeInternalToggled(bool))); + + /* KGraphViewerPreferencesReloadWidget* reloadWidget = + new KGraphViewerPreferencesReloadWidget( 0, "KGraphViewer Settings" ); + if (KGraphEditorSettings::reloadOnChangeMode() == "yes") + { + reloadWidget->reloadOnChangeMode->setButton(0); + } + else if (KGraphEditorSettings::reloadOnChangeMode() == "no") + { + reloadWidget->reloadOnChangeMode->setButton(1); + } + else if (KGraphEditorSettings::reloadOnChangeMode() == "ask") + { + reloadWidget->reloadOnChangeMode->setButton(2); + } + + connect((QObject*)reloadWidget->reloadOnChangeMode, SIGNAL(clicked(int)), this, SLOT(reloadOnChangeMode_pressed(int)) ); + + dialog->addPage( reloadWidget, i18n("Reloading"), "kgraphreloadoptions", i18n("Reloading"), true); + + KGraphViewerPreferencesOpenInExistingWindowWidget* openingWidget = + new KGraphViewerPreferencesOpenInExistingWindowWidget( 0, "KGraphViewer Settings" ); + if (KGraphEditorSettings::openInExistingWindowMode() == "yes") + { + openingWidget->openInExistingWindowMode->setButton(0); + } + else if (KGraphEditorSettings::openInExistingWindowMode() == "no") + { + openingWidget->openInExistingWindowMode->setButton(1); + } + else if (KGraphEditorSettings::openInExistingWindowMode() == "ask") + { + openingWidget->openInExistingWindowMode->setButton(2); + } + + connect((QObject*)openingWidget->openInExistingWindowMode, SIGNAL(clicked(int)), this, SLOT(openInExistingWindowMode_pressed(int)) ); + + dialog->addPage( openingWidget, i18n("Opening"), "kgraphopeningoptions", i18n("Opening"), true); + + KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget* reopeningWidget = + new KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget( 0, "KGraphViewer Settings" ); + if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "yes") + { + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); + } + else if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "no") + { + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); + } + else if (KGraphEditorSettings::reopenPreviouslyOpenedFilesMode() == "ask") + { + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2); + } + + connect((QObject*)reopeningWidget->reopenPreviouslyOpenedFilesMode, SIGNAL(clicked(int)), this, SLOT(reopenPreviouslyOpenedFilesMode_pressed(int)) ); + + dialog->addPage( reopeningWidget, i18n("Session Management"), "kgraphreopeningoptions", i18n("Session Management"), true); + */ + // connect(dialog, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); + + dialog->show(); } void KGraphEditor::applyNewToolbarConfig() { - applyMainWindowSettings(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); + applyMainWindowSettings(KConfigGroup(KSharedConfig::openConfig(), "kgrapheditor")); } // void KGraphViewer::reloadOnChangeMode_pressed(int value) @@ -490,399 +462,350 @@ // KGraphEditorSettings::save(); // } - -void KGraphEditor::slotURLSelected(const QUrl& url) +void KGraphEditor::slotURLSelected(const QUrl &url) { - openUrl(url); + openUrl(url); } void KGraphEditor::close(int index) { - QWidget *tab = m_widget->widget(index); - m_openedFiles.removeAll(m_tabsFilesMap[tab]); - m_widget->removeTab(index); - tab->hide(); - KParts::ReadOnlyPart *part = m_tabsPartsMap[tab]; - m_manager->removePart(part); - m_tabsPartsMap.remove(tab); - m_tabsFilesMap.remove(tab); - delete part; part = nullptr; -/* delete tab; - tab = nullptr;*/ - m_closeAction->setEnabled(m_widget->count() > 0); + QWidget *tab = m_widget->widget(index); + m_openedFiles.removeAll(m_tabsFilesMap[tab]); + m_widget->removeTab(index); + tab->hide(); + KParts::ReadOnlyPart *part = m_tabsPartsMap[tab]; + m_manager->removePart(part); + m_tabsPartsMap.remove(tab); + m_tabsFilesMap.remove(tab); + delete part; + part = nullptr; + /* delete tab; + tab = nullptr;*/ + m_closeAction->setEnabled(m_widget->count() > 0); } void KGraphEditor::close() { - int currentPage = m_widget->currentIndex(); - if (currentPage != -1) - { - close(currentPage); - } + int currentPage = m_widget->currentIndex(); + if (currentPage != -1) { + close(currentPage); + } } void KGraphEditor::fileSave() { - QWidget* currentPage = m_widget->currentWidget(); - if (currentPage) - { - emit(saveTo(QUrl(m_tabsFilesMap[currentPage]).path())); - } + QWidget *currentPage = m_widget->currentWidget(); + if (currentPage) { + emit(saveTo(QUrl(m_tabsFilesMap[currentPage]).path())); + } } void KGraphEditor::fileSaveAs() { - QWidget* currentPage = m_widget->currentWidget(); - if (currentPage) - { - QFileDialog fileDialog(currentPage, i18n("Save current graph")); - fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - if (fileDialog.exec() != QFileDialog::Accepted) { - return; + QWidget *currentPage = m_widget->currentWidget(); + if (currentPage) { + QFileDialog fileDialog(currentPage, i18n("Save current graph")); + fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + if (fileDialog.exec() != QFileDialog::Accepted) { + return; + } + const QString fileName = fileDialog.selectedFiles().at(0); + if (fileName.isEmpty()) { + return; + } + + m_tabsFilesMap[currentPage] = fileName; + emit(saveTo(fileName)); } - const QString fileName = fileDialog.selectedFiles().at(0); - if (fileName.isEmpty()) { - return; - } - - m_tabsFilesMap[currentPage] = fileName; - emit(saveTo(fileName)); - } } void KGraphEditor::newTabSelectedSlot(int index) { -// qCDebug(KGRAPHEDITOR_LOG) << tab; - emit(hide((KParts::Part*)(m_manager->activePart()))); - QWidget *tab = m_widget->widget(index); - if (tab) { - slotSetActiveGraph(m_tabsPartsMap[tab]); - m_manager->setActivePart(m_tabsPartsMap[tab]); - } + // qCDebug(KGRAPHEDITOR_LOG) << tab; + emit(hide((KParts::Part *)(m_manager->activePart()))); + QWidget *tab = m_widget->widget(index); + if (tab) { + slotSetActiveGraph(m_tabsPartsMap[tab]); + m_manager->setActivePart(m_tabsPartsMap[tab]); + } } void KGraphEditor::slotSetActiveGraph(KParts::ReadOnlyPart *part) { - if (m_currentPart) - { - disconnect(this,SIGNAL(prepareAddNewElement(QMap)),m_currentPart,SLOT(prepareAddNewElement(QMap))); - disconnect(this,SIGNAL(prepareAddNewEdge(QMap)),m_currentPart,SLOT(prepareAddNewEdge(QMap))); - disconnect(this,SIGNAL(saveTo(QString)),m_currentPart,SLOT(saveTo(QString))); - disconnect(this,SIGNAL(removeNode(QString)),m_currentPart,SLOT(slotRemoveNode(QString))); - disconnect(this,SIGNAL(addAttribute(QString)),m_currentPart,SLOT(slotAddAttribute(QString))); - disconnect(this,SIGNAL(removeAttribute(QString,QString)),m_currentPart,SLOT(slotRemoveAttribute(QString,QString))); - disconnect(this,SIGNAL(update()),m_currentPart,SLOT(slotUpdate())); - disconnect(this,SIGNAL(selectNode(QString)),m_currentPart,SLOT(slotSelectNode(QString))); - disconnect(this,SIGNAL(saddNewEdge(QString,QString,QMap)), - m_currentPart,SLOT(slotAddNewEdge(QString,QString,QMap))); - disconnect(this,SIGNAL(renameNode(QString,QString)), - m_currentPart,SLOT(slotRenameNode(QString,QString))); - disconnect(this,SIGNAL(setAttribute(QString,QString,QString)),m_currentPart,SLOT(slotSetAttribute(QString,QString,QString))); - } - m_currentPart = part; - m_treeWidget->clear(); - if (m_currentPart == nullptr) - { - return; - } - connect(this,SIGNAL(prepareAddNewElement(QMap)),part,SLOT(prepareAddNewElement(QMap))); - connect(this,SIGNAL(prepareAddNewEdge(QMap)),part,SLOT(prepareAddNewEdge(QMap))); - connect(this,SIGNAL(saveTo(QString)),part,SLOT(saveTo(QString))); - connect(this,SIGNAL(removeNode(QString)),part,SLOT(slotRemoveNode(QString))); - connect(this,SIGNAL(addAttribute(QString)),part,SLOT(slotAddAttribute(QString))); - connect(this,SIGNAL(removeAttribute(QString,QString)),part,SLOT(slotRemoveAttribute(QString,QString))); - connect(this,SIGNAL(update()),part,SLOT(slotUpdate())); - connect(this,SIGNAL(selectNode(QString)),part,SLOT(slotSelectNode(QString))); - connect( this,SIGNAL(removeElement(QString)),m_currentPart,SLOT(slotRemoveElement(QString))); - connect(this,SIGNAL(saddNewEdge(QString,QString,QMap)),m_currentPart,SLOT(slotAddNewEdge(QString,QString,QMap))); - connect(this,SIGNAL(renameNode(QString,QString)),m_currentPart,SLOT(slotRenameNode(QString,QString))); - connect(this,SIGNAL(setAttribute(QString,QString,QString)),m_currentPart,SLOT(slotSetAttribute(QString,QString,QString))); - - QList nodesIds;//TODO = m_currentPart->nodesIds(); - QList items; - foreach (const QString& nodeId, nodesIds) - { - qCDebug(KGRAPHEDITOR_LOG)<< "new item " << nodeId; - QTreeWidgetItem* item = new QTreeWidgetItem((QTreeWidget*)nullptr, QStringList(nodeId)); - item->setFlags(item->flags() | Qt::ItemIsEditable); - QMap attributes;//TODO = m_currentPart->nodeAtributes(nodeId); - foreach (const QString& attrib, attributes.keys()) - { - if (attrib != "_draw_" && attrib != "_ldraw_") - { - QStringList list(attrib); - list << attributes[attrib]; - QTreeWidgetItem* child = new QTreeWidgetItem((QTreeWidget*)nullptr, list); - child->setFlags(child->flags() | Qt::ItemIsEditable); - item->addChild(child); - } + if (m_currentPart) { + disconnect(this, SIGNAL(prepareAddNewElement(QMap)), m_currentPart, SLOT(prepareAddNewElement(QMap))); + disconnect(this, SIGNAL(prepareAddNewEdge(QMap)), m_currentPart, SLOT(prepareAddNewEdge(QMap))); + disconnect(this, SIGNAL(saveTo(QString)), m_currentPart, SLOT(saveTo(QString))); + disconnect(this, SIGNAL(removeNode(QString)), m_currentPart, SLOT(slotRemoveNode(QString))); + disconnect(this, SIGNAL(addAttribute(QString)), m_currentPart, SLOT(slotAddAttribute(QString))); + disconnect(this, SIGNAL(removeAttribute(QString, QString)), m_currentPart, SLOT(slotRemoveAttribute(QString, QString))); + disconnect(this, SIGNAL(update()), m_currentPart, SLOT(slotUpdate())); + disconnect(this, SIGNAL(selectNode(QString)), m_currentPart, SLOT(slotSelectNode(QString))); + disconnect(this, SIGNAL(saddNewEdge(QString, QString, QMap)), m_currentPart, SLOT(slotAddNewEdge(QString, QString, QMap))); + disconnect(this, SIGNAL(renameNode(QString, QString)), m_currentPart, SLOT(slotRenameNode(QString, QString))); + disconnect(this, SIGNAL(setAttribute(QString, QString, QString)), m_currentPart, SLOT(slotSetAttribute(QString, QString, QString))); } - items.append(item); - } - qCDebug(KGRAPHEDITOR_LOG) << "inserting"; - m_treeWidget->insertTopLevelItems(0, items); - + m_currentPart = part; + m_treeWidget->clear(); + if (m_currentPart == nullptr) { + return; + } + connect(this, SIGNAL(prepareAddNewElement(QMap)), part, SLOT(prepareAddNewElement(QMap))); + connect(this, SIGNAL(prepareAddNewEdge(QMap)), part, SLOT(prepareAddNewEdge(QMap))); + connect(this, SIGNAL(saveTo(QString)), part, SLOT(saveTo(QString))); + connect(this, SIGNAL(removeNode(QString)), part, SLOT(slotRemoveNode(QString))); + connect(this, SIGNAL(addAttribute(QString)), part, SLOT(slotAddAttribute(QString))); + connect(this, SIGNAL(removeAttribute(QString, QString)), part, SLOT(slotRemoveAttribute(QString, QString))); + connect(this, SIGNAL(update()), part, SLOT(slotUpdate())); + connect(this, SIGNAL(selectNode(QString)), part, SLOT(slotSelectNode(QString))); + connect(this, SIGNAL(removeElement(QString)), m_currentPart, SLOT(slotRemoveElement(QString))); + connect(this, SIGNAL(saddNewEdge(QString, QString, QMap)), m_currentPart, SLOT(slotAddNewEdge(QString, QString, QMap))); + connect(this, SIGNAL(renameNode(QString, QString)), m_currentPart, SLOT(slotRenameNode(QString, QString))); + connect(this, SIGNAL(setAttribute(QString, QString, QString)), m_currentPart, SLOT(slotSetAttribute(QString, QString, QString))); + + QList nodesIds; // TODO = m_currentPart->nodesIds(); + QList items; + foreach (const QString &nodeId, nodesIds) { + qCDebug(KGRAPHEDITOR_LOG) << "new item " << nodeId; + QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget *)nullptr, QStringList(nodeId)); + item->setFlags(item->flags() | Qt::ItemIsEditable); + QMap attributes; // TODO = m_currentPart->nodeAtributes(nodeId); + foreach (const QString &attrib, attributes.keys()) { + if (attrib != "_draw_" && attrib != "_ldraw_") { + QStringList list(attrib); + list << attributes[attrib]; + QTreeWidgetItem *child = new QTreeWidgetItem((QTreeWidget *)nullptr, list); + child->setFlags(child->flags() | Qt::ItemIsEditable); + item->addChild(child); + } + } + items.append(item); + } + qCDebug(KGRAPHEDITOR_LOG) << "inserting"; + m_treeWidget->insertTopLevelItems(0, items); - connect( m_currentPart, SIGNAL(graphLoaded()), - this, SLOT(slotGraphLoaded()) ); + connect(m_currentPart, SIGNAL(graphLoaded()), this, SLOT(slotGraphLoaded())); - connect( m_currentPart, SIGNAL(newNodeAdded(QString)), - this, SLOT(slotNewNodeAdded(QString)) ); + connect(m_currentPart, SIGNAL(newNodeAdded(QString)), this, SLOT(slotNewNodeAdded(QString))); - connect( m_currentPart, SIGNAL(newEdgeAdded(QString,QString)), - this, SLOT(slotNewEdgeAdded(QString,QString)) ); + connect(m_currentPart, SIGNAL(newEdgeAdded(QString, QString)), this, SLOT(slotNewEdgeAdded(QString, QString))); - connect( m_currentPart, SIGNAL(removeElement(QString)), - this, SLOT(slotRemoveElement(QString)) ); + connect(m_currentPart, SIGNAL(removeElement(QString)), this, SLOT(slotRemoveElement(QString))); - connect( m_currentPart, SIGNAL(selectionIs(QList,QPoint)), - this, SLOT(slotSelectionIs(QList,QPoint)) ); + connect(m_currentPart, SIGNAL(selectionIs(QList, QPoint)), this, SLOT(slotSelectionIs(QList, QPoint))); - connect( m_currentPart, SIGNAL(newEdgeFinished(QString,QString,QMap)), - this, SLOT(slotNewEdgeFinished(QString,QString,QMap)) ); + connect(m_currentPart, SIGNAL(newEdgeFinished(QString, QString, QMap)), this, SLOT(slotNewEdgeFinished(QString, QString, QMap))); - connect( m_currentPart, SIGNAL(hoverEnter(QString)), - this, SLOT(slotHoverEnter(QString)) ); + connect(m_currentPart, SIGNAL(hoverEnter(QString)), this, SLOT(slotHoverEnter(QString))); - connect( m_currentPart, SIGNAL(hoverLeave(QString)), - this, SLOT(slotHoverLeave(QString)) ); + connect(m_currentPart, SIGNAL(hoverLeave(QString)), this, SLOT(slotHoverLeave(QString))); } -void KGraphEditor::slotNewNodeAdded(const QString& id) +void KGraphEditor::slotNewNodeAdded(const QString &id) { - qCDebug(KGRAPHEDITOR_LOG) << id; - update(); + qCDebug(KGRAPHEDITOR_LOG) << id; + update(); } -void KGraphEditor::slotNewEdgeAdded(const QString& ids, const QString& idt) +void KGraphEditor::slotNewEdgeAdded(const QString &ids, const QString &idt) { - qCDebug(KGRAPHEDITOR_LOG) << ids << idt; - update(); + qCDebug(KGRAPHEDITOR_LOG) << ids << idt; + update(); } -void KGraphEditor::slotNewEdgeFinished( const QString& srcId, const QString& tgtId, const QMap&attribs) +void KGraphEditor::slotNewEdgeFinished(const QString &srcId, const QString &tgtId, const QMap &attribs) { - qCDebug(KGRAPHEDITOR_LOG) << srcId << tgtId << attribs; - emit saddNewEdge(srcId,tgtId,attribs); - update(); + qCDebug(KGRAPHEDITOR_LOG) << srcId << tgtId << attribs; + emit saddNewEdge(srcId, tgtId, attribs); + update(); } void KGraphEditor::slotGraphLoaded() { - qCDebug(KGRAPHEDITOR_LOG); - disconnect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this,SLOT(slotItemChanged(QTreeWidgetItem*,int))); - disconnect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), - this,SLOT(slotItemClicked(QTreeWidgetItem*,int))); - - QList nodesIds;//TODO = m_currentPart->nodesIds(); - QList items; - foreach (const QString& nodeId, nodesIds) - { - qCDebug(KGRAPHEDITOR_LOG)<< "item " << nodeId; - QTreeWidgetItem* item; - QList existingItems = m_treeWidget->findItems(nodeId,Qt::MatchRecursive|Qt::MatchExactly); - if (existingItems.isEmpty()) - { - item = new QTreeWidgetItem((QTreeWidget*)nullptr, QStringList(nodeId)); - items.append(item); + qCDebug(KGRAPHEDITOR_LOG); + disconnect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemChanged(QTreeWidgetItem *, int))); + disconnect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(slotItemClicked(QTreeWidgetItem *, int))); + + QList nodesIds; // TODO = m_currentPart->nodesIds(); + QList items; + foreach (const QString &nodeId, nodesIds) { + qCDebug(KGRAPHEDITOR_LOG) << "item " << nodeId; + QTreeWidgetItem *item; + QList existingItems = m_treeWidget->findItems(nodeId, Qt::MatchRecursive | Qt::MatchExactly); + if (existingItems.isEmpty()) { + item = new QTreeWidgetItem((QTreeWidget *)nullptr, QStringList(nodeId)); + items.append(item); + } else { + item = existingItems[0]; + } + item->setFlags(item->flags() | Qt::ItemIsEditable); + QMap attributes; // TODO = m_currentPart->nodeAtributes(nodeId); + QList keys = attributes.keys(); + for (int i = 0; i < item->childCount(); i++) { + if (keys.contains(item->child(i)->text(0))) { + item->child(i)->setText(1, attributes[item->child(i)->text(0)]); + keys.removeAll(item->child(i)->text(0)); + } + } + foreach (const QString &attrib, keys) { + if (attrib != "_draw_" && attrib != "_ldraw_") { + QStringList list(attrib); + list << attributes[attrib]; + QTreeWidgetItem *child = new QTreeWidgetItem((QTreeWidget *)nullptr, list); + child->setFlags(child->flags() | Qt::ItemIsEditable); + item->addChild(child); + } + } } - else - { - item = existingItems[0]; - } - item->setFlags(item->flags() | Qt::ItemIsEditable); - QMap attributes; //TODO = m_currentPart->nodeAtributes(nodeId); - QList keys = attributes.keys(); - for (int i=0; i < item->childCount();i++) - { - if (keys.contains(item->child(i)->text(0))) - { - item->child(i)->setText(1,attributes[item->child(i)->text(0)]); - keys.removeAll(item->child(i)->text(0)); - } - } - foreach (const QString &attrib, keys) - { - if (attrib != "_draw_" && attrib != "_ldraw_") - { - QStringList list(attrib); - list << attributes[attrib]; - QTreeWidgetItem* child = new QTreeWidgetItem((QTreeWidget*)nullptr, list); - child->setFlags(child->flags() | Qt::ItemIsEditable); - item->addChild(child); - } + qCDebug(KGRAPHEDITOR_LOG) << "inserting"; + m_treeWidget->insertTopLevelItems(0, items); + connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemChanged(QTreeWidgetItem *, int))); + connect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(slotItemClicked(QTreeWidgetItem *, int))); +} + +void KGraphEditor::slotItemChanged(QTreeWidgetItem *item, int column) +{ + qCDebug(KGRAPHEDITOR_LOG); + /* values column */ + if (column == 0) { + QString oldNodeName = m_currentTreeWidgetItemText; + QString newNodeName = item->text(0); + emit(renameNode(oldNodeName, newNodeName)); + } else if (column == 1) { + /* there is a parent ; it is an attribute line */ + if (item->parent()) { + QString nodeLabel = item->parent()->text(0); + QString attributeName = item->text(0); + QString attributeValue = item->text(1); + emit(setAttribute(nodeLabel, attributeName, attributeValue)); + } } -} - qCDebug(KGRAPHEDITOR_LOG) << "inserting"; - m_treeWidget->insertTopLevelItems(0, items); - connect(m_treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this,SLOT(slotItemChanged(QTreeWidgetItem*,int))); - connect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), - this,SLOT(slotItemClicked(QTreeWidgetItem*,int))); -} - -void KGraphEditor::slotItemChanged ( QTreeWidgetItem * item, int column ) -{ - qCDebug(KGRAPHEDITOR_LOG) ; - /* values column */ - if (column == 0) - { - QString oldNodeName = m_currentTreeWidgetItemText; - QString newNodeName = item->text(0); - emit(renameNode(oldNodeName,newNodeName)); - } - else if (column == 1) - { - /* there is a parent ; it is an attribute line */ - if (item->parent()) - { - QString nodeLabel = item->parent()->text(0); - QString attributeName = item->text(0); - QString attributeValue = item->text(1); - emit (setAttribute(nodeLabel,attributeName,attributeValue)); - } - } - emit update(); + emit update(); } -void KGraphEditor::slotItemClicked ( QTreeWidgetItem * item, int column ) +void KGraphEditor::slotItemClicked(QTreeWidgetItem *item, int column) { - qCDebug(KGRAPHEDITOR_LOG) << column; - m_currentTreeWidgetItemText = item->text(0); + qCDebug(KGRAPHEDITOR_LOG) << column; + m_currentTreeWidgetItemText = item->text(0); - QString nodeName = item->parent() ? - item->parent()->text(0) : - item->text(0); - emit selectNode(nodeName); + QString nodeName = item->parent() ? item->parent()->text(0) : item->text(0); + emit selectNode(nodeName); } void KGraphEditor::slotEditNewVertex() { - if (m_currentPart == nullptr) - { - qCDebug(KGRAPHEDITOR_LOG) << "new vertex: no part selected"; - return; - } - qCDebug(KGRAPHEDITOR_LOG) << "new vertex"; - emit(prepareAddNewElement(m_newElementAttributes)); + if (m_currentPart == nullptr) { + qCDebug(KGRAPHEDITOR_LOG) << "new vertex: no part selected"; + return; + } + qCDebug(KGRAPHEDITOR_LOG) << "new vertex"; + emit(prepareAddNewElement(m_newElementAttributes)); } void KGraphEditor::slotEditNewEdge() { - if (m_currentPart == nullptr) - { - qCDebug(KGRAPHEDITOR_LOG) << "new edge: no part selected"; - return; - } - qCDebug(KGRAPHEDITOR_LOG) << "new edge"; - emit(prepareAddNewEdge(m_newElementAttributes)); + if (m_currentPart == nullptr) { + qCDebug(KGRAPHEDITOR_LOG) << "new edge: no part selected"; + return; + } + qCDebug(KGRAPHEDITOR_LOG) << "new edge"; + emit(prepareAddNewEdge(m_newElementAttributes)); } -void KGraphEditor::slotRemoveNode(const QString& nodeName) +void KGraphEditor::slotRemoveNode(const QString &nodeName) { - emit removeNode(nodeName); - emit update(); + emit removeNode(nodeName); + emit update(); } -void KGraphEditor::slotAddAttribute(const QString& attribName) +void KGraphEditor::slotAddAttribute(const QString &attribName) { - emit addAttribute(attribName); - emit update(); + emit addAttribute(attribName); + emit update(); } -void KGraphEditor::slotRemoveAttribute(const QString& nodeName, const QString& attribName) +void KGraphEditor::slotRemoveAttribute(const QString &nodeName, const QString &attribName) { - emit removeAttribute(nodeName,attribName); - emit update(); + emit removeAttribute(nodeName, attribName); + emit update(); } -void KGraphEditor::slotNewElementItemChanged(QTreeWidgetItem* item ,int column) +void KGraphEditor::slotNewElementItemChanged(QTreeWidgetItem *item, int column) { - qCDebug(KGRAPHEDITOR_LOG); - if (column == 0) - { - qCWarning(KGRAPHEDITOR_LOG) << "Item id change not handled"; - return; - } - else if (column == 1) - { - m_newElementAttributes[item->text(0)] = item->text(1); - } - else - { - qCWarning(KGRAPHEDITOR_LOG) << "Unknown column" << column; - return; - } + qCDebug(KGRAPHEDITOR_LOG); + if (column == 0) { + qCWarning(KGRAPHEDITOR_LOG) << "Item id change not handled"; + return; + } else if (column == 1) { + m_newElementAttributes[item->text(0)] = item->text(1); + } else { + qCWarning(KGRAPHEDITOR_LOG) << "Unknown column" << column; + return; + } } -void KGraphEditor::slotAddNewElementAttribute(const QString& attrib) +void KGraphEditor::slotAddNewElementAttribute(const QString &attrib) { - m_newElementAttributes[attrib] = QString(); + m_newElementAttributes[attrib] = QString(); } -void KGraphEditor::slotRemoveNewElementAttribute(const QString& attrib) +void KGraphEditor::slotRemoveNewElementAttribute(const QString &attrib) { - m_newElementAttributes.remove(attrib); + m_newElementAttributes.remove(attrib); } -void KGraphEditor::slotRemoveElement(const QString& id) +void KGraphEditor::slotRemoveElement(const QString &id) { - qCDebug(KGRAPHEDITOR_LOG) << id; - m_treeWidget->slotRemoveElement(id); - emit(removeElement(id)); + qCDebug(KGRAPHEDITOR_LOG) << id; + m_treeWidget->slotRemoveElement(id); + emit(removeElement(id)); } -void KGraphEditor::slotSelectionIs(const QList& elements , const QPoint& p) +void KGraphEditor::slotSelectionIs(const QList &elements, const QPoint &p) { - qCDebug(KGRAPHEDITOR_LOG); - Q_UNUSED(p); - QList items = m_treeWidget->selectedItems(); - foreach (QTreeWidgetItem* item, items) - { - item->setSelected(false); - } - foreach (const QString &elementName, elements) - { - QList items = m_treeWidget->findItems(elementName,Qt::MatchExactly,0); - foreach (QTreeWidgetItem* item, items) - { - item->setSelected(true); + qCDebug(KGRAPHEDITOR_LOG); + Q_UNUSED(p); + QList items = m_treeWidget->selectedItems(); + foreach (QTreeWidgetItem *item, items) { + item->setSelected(false); + } + foreach (const QString &elementName, elements) { + QList items = m_treeWidget->findItems(elementName, Qt::MatchExactly, 0); + foreach (QTreeWidgetItem *item, items) { + item->setSelected(true); + } } - } } void KGraphEditor::slotParsingModeExternalToggled(bool value) { - if (value) - { - KGraphEditorSettings::setParsingMode("external"); - } - // qCDebug(KGRAPHEDITOR_LOG) << "emiting"; - // emit(settingsChanged()); - KGraphEditorSettings::self()->save(); + if (value) { + KGraphEditorSettings::setParsingMode("external"); + } + // qCDebug(KGRAPHEDITOR_LOG) << "emiting"; + // emit(settingsChanged()); + KGraphEditorSettings::self()->save(); } void KGraphEditor::slotParsingModeInternalToggled(bool value) { - if (value) - { - KGraphEditorSettings::setParsingMode("internal"); - } - // qCDebug(KGRAPHEDITOR_LOG) << "emiting"; - // emit(settingsChanged()); - KGraphEditorSettings::self()->save(); + if (value) { + KGraphEditorSettings::setParsingMode("internal"); + } + // qCDebug(KGRAPHEDITOR_LOG) << "emiting"; + // emit(settingsChanged()); + KGraphEditorSettings::self()->save(); } -void KGraphEditor::slotHoverEnter(const QString& id) +void KGraphEditor::slotHoverEnter(const QString &id) { - qCDebug(KGRAPHEDITOR_LOG) << id; - statusBar()->showMessage(id); + qCDebug(KGRAPHEDITOR_LOG) << id; + statusBar()->showMessage(id); } -void KGraphEditor::slotHoverLeave(const QString& id) +void KGraphEditor::slotHoverLeave(const QString &id) { - qCDebug(KGRAPHEDITOR_LOG) << id; - statusBar()->showMessage(""); + qCDebug(KGRAPHEDITOR_LOG) << id; + statusBar()->showMessage(""); } diff --git a/src/kgrapheditorConfigDialog.h b/src/kgrapheditorConfigDialog.h --- a/src/kgrapheditorConfigDialog.h +++ b/src/kgrapheditorConfigDialog.h @@ -16,14 +16,14 @@ 02110-1301, USA */ - #ifndef KGRAPHEDITORCONFIGDIALOG_H #define KGRAPHEDITORCONFIGDIALOG_H -#include #include +#include -namespace Ui { +namespace Ui +{ class KGraphViewerPreferencesParsingWidget; class KGraphViewerPreferencesReloadWidget; class KGraphViewerPreferencesOpenInExistingWindowWidget; @@ -39,29 +39,29 @@ */ class KgeConfigurationDialog : public KConfigDialog { - Q_OBJECT + Q_OBJECT public: - KgeConfigurationDialog (QWidget *parent, const QString& name, KConfigSkeleton *config); + KgeConfigurationDialog(QWidget *parent, const QString &name, KConfigSkeleton *config); - ~KgeConfigurationDialog() override; + ~KgeConfigurationDialog() override; protected Q_SLOTS: - void updateSettings() override; - void updateWidgets() override; + void updateSettings() override; + void updateWidgets() override; - void settingChanged(int); + void settingChanged(int); protected: - bool hasChanged() override; + bool hasChanged() override; - bool m_changed; + bool m_changed; public: - Ui::KGraphViewerPreferencesParsingWidget* m_parsingWidget; - Ui::KGraphViewerPreferencesReloadWidget* m_reloadWidget; - Ui::KGraphViewerPreferencesOpenInExistingWindowWidget* m_openingWidget; - Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget* m_reopeningWidget; - Ui::KGraphViewerPreferencesAppearanceWidget* m_appearanceWidget; + Ui::KGraphViewerPreferencesParsingWidget *m_parsingWidget; + Ui::KGraphViewerPreferencesReloadWidget *m_reloadWidget; + Ui::KGraphViewerPreferencesOpenInExistingWindowWidget *m_openingWidget; + Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget *m_reopeningWidget; + Ui::KGraphViewerPreferencesAppearanceWidget *m_appearanceWidget; }; #endif diff --git a/src/kgrapheditorConfigDialog.cpp b/src/kgrapheditorConfigDialog.cpp --- a/src/kgrapheditorConfigDialog.cpp +++ b/src/kgrapheditorConfigDialog.cpp @@ -16,154 +16,148 @@ 02110-1301, USA */ - #include "kgrapheditorConfigDialog.h" #include "kgrapheditorsettings.h" -#include "ui_preferencesReload.h" -#include "ui_preferencesParsing.h" #include "ui_preferencesOpenInExistingWindow.h" +#include "ui_preferencesParsing.h" +#include "ui_preferencesReload.h" #include "ui_preferencesReopenPreviouslyOpenedFiles.h" +#include #include -#include -#include #include -#include +#include +#include #include -#include +#include -#include #include -#include +#include #include #include #include +#include //#include //#include #include -KgeConfigurationDialog::KgeConfigurationDialog (QWidget *parent, const QString& name, KConfigSkeleton *config) : - KConfigDialog(parent, name, config), - m_changed(false), - m_parsingWidget(new Ui::KGraphViewerPreferencesParsingWidget()), - m_reloadWidget(new Ui::KGraphViewerPreferencesReloadWidget()), - m_openingWidget(new Ui::KGraphViewerPreferencesOpenInExistingWindowWidget()), - m_reopeningWidget(new Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget()) +KgeConfigurationDialog::KgeConfigurationDialog(QWidget *parent, const QString &name, KConfigSkeleton *config) + : KConfigDialog(parent, name, config) + , m_changed(false) + , m_parsingWidget(new Ui::KGraphViewerPreferencesParsingWidget()) + , m_reloadWidget(new Ui::KGraphViewerPreferencesReloadWidget()) + , m_openingWidget(new Ui::KGraphViewerPreferencesOpenInExistingWindowWidget()) + , m_reopeningWidget(new Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget()) { - QWidget* page0 = new QWidget(); - m_parsingWidget->setupUi(page0); - QWidget* page1 = new QWidget(); - m_reloadWidget->setupUi(page1); - QWidget* page2 = new QWidget(); - m_openingWidget->setupUi(page2); - QWidget* page3 = new QWidget(); - m_reopeningWidget->setupUi(page3); - addPage( page0, i18n("Parsing"), "preferences-other", i18n("Parsing"), false); - addPage( page1, i18n("Reloading"), "view-refresh", i18n("Reloading"), false); - addPage( page2, i18n("Opening"), "document-open", i18n("Opening"), false); - addPage( page3, i18n("Session Management"), "preferences-other", i18n("Session Management"), false); - connect(m_parsingWidget->parsingMode, &QGroupBox::clicked, - this, &KgeConfigurationDialog::settingChanged); - connect(m_reloadWidget->reloadOnChangeMode, &QGroupBox::clicked, - this, &KgeConfigurationDialog::settingChanged); - connect(m_openingWidget->openInExistingWindowMode, &QGroupBox::clicked, - this, &KgeConfigurationDialog::settingChanged); - connect(m_reopeningWidget->reopenPreviouslyOpenedFilesMode, &QGroupBox::clicked, - this, &KgeConfigurationDialog::settingChanged); + QWidget *page0 = new QWidget(); + m_parsingWidget->setupUi(page0); + QWidget *page1 = new QWidget(); + m_reloadWidget->setupUi(page1); + QWidget *page2 = new QWidget(); + m_openingWidget->setupUi(page2); + QWidget *page3 = new QWidget(); + m_reopeningWidget->setupUi(page3); + addPage(page0, i18n("Parsing"), "preferences-other", i18n("Parsing"), false); + addPage(page1, i18n("Reloading"), "view-refresh", i18n("Reloading"), false); + addPage(page2, i18n("Opening"), "document-open", i18n("Opening"), false); + addPage(page3, i18n("Session Management"), "preferences-other", i18n("Session Management"), false); + connect(m_parsingWidget->parsingMode, &QGroupBox::clicked, this, &KgeConfigurationDialog::settingChanged); + connect(m_reloadWidget->reloadOnChangeMode, &QGroupBox::clicked, this, &KgeConfigurationDialog::settingChanged); + connect(m_openingWidget->openInExistingWindowMode, &QGroupBox::clicked, this, &KgeConfigurationDialog::settingChanged); + connect(m_reopeningWidget->reopenPreviouslyOpenedFilesMode, &QGroupBox::clicked, this, &KgeConfigurationDialog::settingChanged); } -KgeConfigurationDialog::~KgeConfigurationDialog () +KgeConfigurationDialog::~KgeConfigurationDialog() { } void KgeConfigurationDialog::settingChanged(int) { -// std::cerr << "KgeConfigurationDialog::settingChanged" << std::endl; - m_changed = true; + // std::cerr << "KgeConfigurationDialog::settingChanged" << std::endl; + m_changed = true; } bool KgeConfigurationDialog::hasChanged() { -// std::cerr << "KgeConfigurationDialog::hasChanged" << std::endl; - return m_changed; + // std::cerr << "KgeConfigurationDialog::hasChanged" << std::endl; + return m_changed; } void KgeConfigurationDialog::updateSettings() { -// std::cerr << "KgeConfigurationDialog::updateSettings" << std::endl; - m_changed = false; -/* switch (m_openingWidget->openInExistingWindowMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setOpenInExistingWindowMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setOpenInExistingWindowMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setOpenInExistingWindowMode("ask"); - break; - default: ; - } - switch (m_reloadWidget->reloadOnChangeMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setReloadOnChangeMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setReloadOnChangeMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setReloadOnChangeMode("ask"); - break; - default: ; - } - switch (m_reopeningWidget->reopenPreviouslyOpenedFilesMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); - break; - default: ; - }*/ - //@TODO to port - //KGraphViewerSettings::writeConfig(); + // std::cerr << "KgeConfigurationDialog::updateSettings" << std::endl; + m_changed = false; + /* switch (m_openingWidget->openInExistingWindowMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setOpenInExistingWindowMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setOpenInExistingWindowMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setOpenInExistingWindowMode("ask"); + break; + default: ; + } + switch (m_reloadWidget->reloadOnChangeMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setReloadOnChangeMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setReloadOnChangeMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setReloadOnChangeMode("ask"); + break; + default: ; + } + switch (m_reopeningWidget->reopenPreviouslyOpenedFilesMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); + break; + default: ; + }*/ + //@TODO to port + // KGraphViewerSettings::writeConfig(); } void KgeConfigurationDialog::updateWidgets() { -// std::cerr << "KgeConfigurationDialog::updateWidgets" << std::endl; - - m_changed = false; -// std::cerr << " openInExistingWindowMode: " << KGraphViewerSettings::openInExistingWindowMode() << std::endl; -// if (KGraphViewerSettings::openInExistingWindowMode() == "no") -// m_openingWidget->openInExistingWindowMode->setButton(0); -// else if (KGraphViewerSettings::openInExistingWindowMode() == "yes") -// m_openingWidget->openInExistingWindowMode->setButton(1); -// else if (KGraphViewerSettings::openInExistingWindowMode() == "ask") -// m_openingWidget->openInExistingWindowMode->setButton(2); - - -// std::cerr << " reloadOnChangeMode: " << KGraphViewerSettings::reloadOnChangeMode() << std::endl; -// if (KGraphViewerSettings::reloadOnChangeMode() == "no") -// m_reloadWidget->reloadOnChangeMode->setButton(0); -// else if (KGraphViewerSettings::reloadOnChangeMode() == "yes") -// m_reloadWidget->reloadOnChangeMode->setButton(1); -// else if (KGraphViewerSettings::reloadOnChangeMode() == "ask") -// m_reloadWidget->reloadOnChangeMode->setButton(2); - -// std::cerr << " reopenPreviouslyOpenedFilesMode: " << KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() << std::endl; -/* if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "no") - m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); - else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "yes") - m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); - else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") - m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2);*/ + // std::cerr << "KgeConfigurationDialog::updateWidgets" << std::endl; + + m_changed = false; + // std::cerr << " openInExistingWindowMode: " << KGraphViewerSettings::openInExistingWindowMode() << std::endl; + // if (KGraphViewerSettings::openInExistingWindowMode() == "no") + // m_openingWidget->openInExistingWindowMode->setButton(0); + // else if (KGraphViewerSettings::openInExistingWindowMode() == "yes") + // m_openingWidget->openInExistingWindowMode->setButton(1); + // else if (KGraphViewerSettings::openInExistingWindowMode() == "ask") + // m_openingWidget->openInExistingWindowMode->setButton(2); + + // std::cerr << " reloadOnChangeMode: " << KGraphViewerSettings::reloadOnChangeMode() << std::endl; + // if (KGraphViewerSettings::reloadOnChangeMode() == "no") + // m_reloadWidget->reloadOnChangeMode->setButton(0); + // else if (KGraphViewerSettings::reloadOnChangeMode() == "yes") + // m_reloadWidget->reloadOnChangeMode->setButton(1); + // else if (KGraphViewerSettings::reloadOnChangeMode() == "ask") + // m_reloadWidget->reloadOnChangeMode->setButton(2); + + // std::cerr << " reopenPreviouslyOpenedFilesMode: " << KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() << std::endl; + /* if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "no") + m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); + else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "yes") + m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); + else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") + m_reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2);*/ } diff --git a/src/kgrapheditormain.cpp b/src/kgrapheditormain.cpp --- a/src/kgrapheditormain.cpp +++ b/src/kgrapheditormain.cpp @@ -16,124 +16,101 @@ 02110-1301, USA */ - #include "kgrapheditor.h" #include "kgrapheditor_debug.h" #include -#include -#include -#include -#include -#include -#include #include -#include +#include #include #include +#include #include +#include +#include +#include +#include +#include -#include -#include -#include "kgrapheditoradaptor.h" #include "config-kgraphviewer.h" +#include "kgrapheditoradaptor.h" +#include +#include int main(int argc, char **argv) { - QApplication app(argc, argv); - - KLocalizedString::setApplicationDomain("kgraphviewer"); - - KAboutData about(QStringLiteral("kgrapheditor"), - i18n("KGraphEditor"), - KGRAPHVIEWER_VERSION_STRING, - i18n("A Graphviz DOT graph editor by KDE"), - KAboutLicense::GPL, - i18n("(C) 2005-2010 Gaƫl de Chalendar")); - - app.setOrganizationDomain(QStringLiteral("kde.org")); - app.setOrganizationName(QStringLiteral("KDE")); - - KAboutData::setApplicationData(about); - - app.setWindowIcon(QIcon::fromTheme("kgraphviewer", app.windowIcon())); - - QCommandLineParser options; - options.addHelpOption(); - options.addVersionOption(); - options.addPositionalArgument(QStringLiteral("url"), i18n("Path or URL to scan"), i18n("[url]")); - about.setupCommandLine(&options); - options.process(app); - about.processCommandLine(&options); - -// see if we are starting with session management - if (app.isSessionRestored()) - { - RESTORE(KGraphEditor); - } - else - { - // no session.. just start up normally - QStringList args = options.positionalArguments(); - - KGraphEditor *widget = nullptr; - if ( args.count() == 0 ) - { - widget = new KGraphEditor; - new KgrapheditorAdaptor(widget); - QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget); - widget->show(); - } - else - { - QDBusReply reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kgrapheditor" ); - - bool instanceExists = reply.value(); - - for (int i = 0; i < args.count(); i++ ) - { - if (instanceExists - && (QMessageBox::question(nullptr, - i18n("A KGraphEditor window is already open, do you want to open the file in it?"), - i18n("Opening in new window confirmation"), - "openInNewWindowMode" ) == QMessageBox::Yes) ) - { - QByteArray tosenddata; - QDataStream arg(&tosenddata, QIODevice::WriteOnly); - QString strarg = args[i]; - QUrl url = QUrl::fromUserInput(strarg, QDir::currentPath(), QUrl::AssumeLocalFile); - arg << url; - QDBusInterface iface("org.kde.kgrapheditor", "/KGraphEditor", "", QDBusConnection::sessionBus()); - if (iface.isValid()) - { - QDBusReply reply = iface.call("openUrl", url.url(QUrl::PreferLocalFile)); - if (reply.isValid()) - { - qCDebug(KGRAPHEDITOR_LOG) << "Reply was valid" << endl; - return 0; - } - - qCWarning(KGRAPHEDITOR_LOG) << "Call failed: " << reply.error().message() << endl; - return 1; - } - qCWarning(KGRAPHEDITOR_LOG) << "Invalid interface" << endl; - exit(0); - } - else - { + QApplication app(argc, argv); + + KLocalizedString::setApplicationDomain("kgraphviewer"); + + KAboutData about(QStringLiteral("kgrapheditor"), i18n("KGraphEditor"), KGRAPHVIEWER_VERSION_STRING, i18n("A Graphviz DOT graph editor by KDE"), KAboutLicense::GPL, i18n("(C) 2005-2010 Gaƫl de Chalendar")); + + app.setOrganizationDomain(QStringLiteral("kde.org")); + app.setOrganizationName(QStringLiteral("KDE")); + + KAboutData::setApplicationData(about); + + app.setWindowIcon(QIcon::fromTheme("kgraphviewer", app.windowIcon())); + + QCommandLineParser options; + options.addHelpOption(); + options.addVersionOption(); + options.addPositionalArgument(QStringLiteral("url"), i18n("Path or URL to scan"), i18n("[url]")); + about.setupCommandLine(&options); + options.process(app); + about.processCommandLine(&options); + + // see if we are starting with session management + if (app.isSessionRestored()) { + RESTORE(KGraphEditor); + } else { + // no session.. just start up normally + QStringList args = options.positionalArguments(); + + KGraphEditor *widget = nullptr; + if (args.count() == 0) { widget = new KGraphEditor; new KgrapheditorAdaptor(widget); QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget); widget->show(); - widget->openUrl(QUrl::fromUserInput(args[0], QDir::currentPath(), QUrl::AssumeLocalFile)); - } + } else { + QDBusReply reply = QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kgrapheditor"); + + bool instanceExists = reply.value(); + + for (int i = 0; i < args.count(); i++) { + if (instanceExists && + (QMessageBox::question(nullptr, i18n("A KGraphEditor window is already open, do you want to open the file in it?"), i18n("Opening in new window confirmation"), "openInNewWindowMode") == QMessageBox::Yes)) { + QByteArray tosenddata; + QDataStream arg(&tosenddata, QIODevice::WriteOnly); + QString strarg = args[i]; + QUrl url = QUrl::fromUserInput(strarg, QDir::currentPath(), QUrl::AssumeLocalFile); + arg << url; + QDBusInterface iface("org.kde.kgrapheditor", "/KGraphEditor", "", QDBusConnection::sessionBus()); + if (iface.isValid()) { + QDBusReply reply = iface.call("openUrl", url.url(QUrl::PreferLocalFile)); + if (reply.isValid()) { + qCDebug(KGRAPHEDITOR_LOG) << "Reply was valid" << endl; + return 0; + } + + qCWarning(KGRAPHEDITOR_LOG) << "Call failed: " << reply.error().message() << endl; + return 1; + } + qCWarning(KGRAPHEDITOR_LOG) << "Invalid interface" << endl; + exit(0); + } else { + widget = new KGraphEditor; + new KgrapheditorAdaptor(widget); + QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget); + widget->show(); + widget->openUrl(QUrl::fromUserInput(args[0], QDir::currentPath(), QUrl::AssumeLocalFile)); + } + } + } + if (widget) { + widget->reloadPreviousFiles(); } - } - if (widget) - { - widget->reloadPreviousFiles(); } - - } - return app.exec(); + return app.exec(); } diff --git a/src/kgraphviewer.h b/src/kgraphviewer.h --- a/src/kgraphviewer.h +++ b/src/kgraphviewer.h @@ -16,17 +16,16 @@ 02110-1301, USA */ - #ifndef _KGRAPHVIEWER_H_ #define _KGRAPHVIEWER_H_ //#include +#include +#include #include #include #include -#include -#include #include @@ -41,89 +40,89 @@ */ class KGraphViewerWindow : public KParts::MainWindow { - Q_OBJECT + Q_OBJECT public: - /** - * Default Constructor - */ - KGraphViewerWindow(); + /** + * Default Constructor + */ + KGraphViewerWindow(); - /** - * Default Destructor - */ - ~KGraphViewerWindow() override; + /** + * Default Destructor + */ + ~KGraphViewerWindow() override; - /** - * Use this method to load whatever file/URL you have - */ - void openUrl(const QUrl& url); + /** + * Use this method to load whatever file/URL you have + */ + void openUrl(const QUrl &url); - void reloadPreviousFiles(); + void reloadPreviousFiles(); protected: - - void closeEvent(QCloseEvent *event) override; + void closeEvent(QCloseEvent *event) override; Q_SIGNALS: - void hide(KParts::Part* part); + void hide(KParts::Part *part); public Q_SLOTS: - /** - * Use this method to load whatever file/URL you have - */ - void openUrl(const QString& url) { - openUrl(QUrl::fromUserInput(url, QDir::currentPath(), QUrl::AssumeLocalFile)); - } - - void close(); - - void slotReloadOnChangeModeYesToggled(bool value); - void slotReloadOnChangeModeNoToggled(bool value); - void slotReloadOnChangeModeAskToggled(bool value); - void slotOpenInExistingWindowModeYesToggled(bool value); - void slotOpenInExistingWindowModeNoToggled(bool value); - void slotOpenInExistingWindowModeAskToggled(bool value); - void slotReopenPreviouslyOpenedFilesModeYesToggled(bool value); - void slotReopenPreviouslyOpenedFilesModeNoToggled(bool value); - void slotReopenPreviouslyOpenedFilesModeAskToggled(bool value); - void slotParsingModeExternalToggled(bool value); - void slotParsingModeInternalToggled(bool value); + /** + * Use this method to load whatever file/URL you have + */ + void openUrl(const QString &url) + { + openUrl(QUrl::fromUserInput(url, QDir::currentPath(), QUrl::AssumeLocalFile)); + } + + void close(); + + void slotReloadOnChangeModeYesToggled(bool value); + void slotReloadOnChangeModeNoToggled(bool value); + void slotReloadOnChangeModeAskToggled(bool value); + void slotOpenInExistingWindowModeYesToggled(bool value); + void slotOpenInExistingWindowModeNoToggled(bool value); + void slotOpenInExistingWindowModeAskToggled(bool value); + void slotReopenPreviouslyOpenedFilesModeYesToggled(bool value); + void slotReopenPreviouslyOpenedFilesModeNoToggled(bool value); + void slotReopenPreviouslyOpenedFilesModeAskToggled(bool value); + void slotParsingModeExternalToggled(bool value); + void slotParsingModeInternalToggled(bool value); private Q_SLOTS: - void fileNew(); - void fileOpen(); - void close(int index); - void slotURLSelected(const QUrl&); - void optionsShowToolbar(); - void optionsShowStatusbar(); - void optionsConfigureKeys(); - void optionsConfigureToolbars(); - void optionsConfigure(); - void newTabSelectedSlot(int index); - - void applyNewToolbarConfig(); - - void slotHoverEnter(const QString&); - void slotHoverLeave(const QString&); - void slotBackgroundColorChanged(const QColor&); + void fileNew(); + void fileOpen(); + void close(int index); + void slotURLSelected(const QUrl &); + void optionsShowToolbar(); + void optionsShowStatusbar(); + void optionsConfigureKeys(); + void optionsConfigureToolbars(); + void optionsConfigure(); + void newTabSelectedSlot(int index); + + void applyNewToolbarConfig(); + + void slotHoverEnter(const QString &); + void slotHoverLeave(const QString &); + void slotBackgroundColorChanged(const QColor &); private: - void setupAccel(); - void setupActions(); + void setupAccel(); + void setupActions(); private: - QTabWidget* m_widget; - KRecentFilesAction* m_rfa; - KParts::PartManager* m_manager; + QTabWidget *m_widget; + KRecentFilesAction *m_rfa; + KParts::PartManager *m_manager; - KToggleAction *m_toolbarAction; - KToggleAction *m_statusbarAction; - QAction *m_closeAction; + KToggleAction *m_toolbarAction; + KToggleAction *m_statusbarAction; + QAction *m_closeAction; - QStringList m_openedFiles; + QStringList m_openedFiles; - QMap m_tabsPartsMap; - QMap m_tabsFilesMap; + QMap m_tabsPartsMap; + QMap m_tabsFilesMap; }; #endif // _KGRAPHVIEWER_H_ diff --git a/src/kgraphviewer.cpp b/src/kgraphviewer.cpp --- a/src/kgraphviewer.cpp +++ b/src/kgraphviewer.cpp @@ -16,577 +16,511 @@ 02110-1301, USA */ - #include "kgraphviewer.h" -#include "kgraphviewer_debug.h" -#include "part/kgraphviewer_interface.h" #include "kgraphviewerConfigDialog.h" +#include "kgraphviewer_debug.h" #include "kgraphviewersettings.h" +#include "part/kgraphviewer_interface.h" +#include "ui_preferencesOpenInExistingWindow.h" #include "ui_preferencesParsing.h" #include "ui_preferencesReload.h" -#include "ui_preferencesOpenInExistingWindow.h" #include "ui_preferencesReopenPreviouslyOpenedFiles.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include +#include +#include #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include #include -#include +#include +#include +#include +#include #include +#include +#include +#include #include -#include -#include -#include -#include -#include #include #include -#include KGraphViewerWindow::KGraphViewerWindow() - : KParts::MainWindow(), - m_rfa(nullptr) -{ - // set the shell's ui resource file - setXMLFile("kgraphviewerui.rc"); - -// std::cerr << "Creating tab widget" << std::endl; - m_widget = new QTabWidget(this); - m_widget->setTabsClosable(true); - connect(m_widget, &QTabWidget::tabCloseRequested, - this, static_cast(&KGraphViewerWindow::close)); - connect(m_widget, &QTabWidget::currentChanged, - this, &KGraphViewerWindow::newTabSelectedSlot); - - setCentralWidget(m_widget); - - if (QDBusConnection::sessionBus().registerService( "org.kde.kgraphviewer" )) - { - qCDebug(KGRAPHVIEWER_LOG) << "Service Registered successfully"; - QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportAllSlots); - - } - else - { - qCDebug(KGRAPHVIEWER_LOG) << "Failed to register service..."; - } - - // this routine will find and load our Part. it finds the Part by - // name which is a bad idea usually.. but it's alright in this - // case since our Part is made for this Shell - - // Create a KParts part manager, to handle part activation/deactivation - m_manager = new KParts::PartManager( this ); - - // When the manager says the active part changes, the window updates (recreates) the GUI - connect(m_manager, &KParts::PartManager::activePartChanged, - this, &KGraphViewerWindow::createGUI); - - setupGUI(ToolBar | Keys | StatusBar | Save); - - // then, setup our actions - setupActions(); - - // Creates the GUI with a null part to make appear the main app menus and tools - createGUI(nullptr); + : KParts::MainWindow() + , m_rfa(nullptr) +{ + // set the shell's ui resource file + setXMLFile("kgraphviewerui.rc"); + + // std::cerr << "Creating tab widget" << std::endl; + m_widget = new QTabWidget(this); + m_widget->setTabsClosable(true); + connect(m_widget, &QTabWidget::tabCloseRequested, this, static_cast(&KGraphViewerWindow::close)); + connect(m_widget, &QTabWidget::currentChanged, this, &KGraphViewerWindow::newTabSelectedSlot); + + setCentralWidget(m_widget); + + if (QDBusConnection::sessionBus().registerService("org.kde.kgraphviewer")) { + qCDebug(KGRAPHVIEWER_LOG) << "Service Registered successfully"; + QDBusConnection::sessionBus().registerObject("/", this, QDBusConnection::ExportAllSlots); + + } else { + qCDebug(KGRAPHVIEWER_LOG) << "Failed to register service..."; + } + + // this routine will find and load our Part. it finds the Part by + // name which is a bad idea usually.. but it's alright in this + // case since our Part is made for this Shell + + // Create a KParts part manager, to handle part activation/deactivation + m_manager = new KParts::PartManager(this); + + // When the manager says the active part changes, the window updates (recreates) the GUI + connect(m_manager, &KParts::PartManager::activePartChanged, this, &KGraphViewerWindow::createGUI); + + setupGUI(ToolBar | Keys | StatusBar | Save); + + // then, setup our actions + setupActions(); + + // Creates the GUI with a null part to make appear the main app menus and tools + createGUI(nullptr); } KGraphViewerWindow::~KGraphViewerWindow() { - KSharedConfig::Ptr config = KSharedConfig::openConfig(); - if (m_rfa) - m_rfa->saveEntries(KConfigGroup(config, "kgraphviewer recent files")); + KSharedConfig::Ptr config = KSharedConfig::openConfig(); + if (m_rfa) + m_rfa->saveEntries(KConfigGroup(config, "kgraphviewer recent files")); - // delete partsmanager explicitly, to avoid activePartChanged being emitted from here - delete m_manager; + // delete partsmanager explicitly, to avoid activePartChanged being emitted from here + delete m_manager; } void KGraphViewerWindow::reloadPreviousFiles() { - QStringList previouslyOpenedFiles = KGraphViewerSettings::previouslyOpenedFiles(); - if ( (previouslyOpenedFiles.empty() == false) - && (KMessageBox::questionYesNo(this, - i18n("Do you want to reload files from the previous session?"), - i18n("Session Restore"), - KStandardGuiItem::yes(), - KStandardGuiItem::no(), - "reopenPreviouslyOpenedFilesMode" ) == KMessageBox::Yes) ) - { - QStringList::const_iterator it, it_end; - it = previouslyOpenedFiles.constBegin(); it_end = previouslyOpenedFiles.constEnd(); - for (; it != it_end; it++) - { - openUrl(*it); + QStringList previouslyOpenedFiles = KGraphViewerSettings::previouslyOpenedFiles(); + if ((previouslyOpenedFiles.empty() == false) && + (KMessageBox::questionYesNo(this, i18n("Do you want to reload files from the previous session?"), i18n("Session Restore"), KStandardGuiItem::yes(), KStandardGuiItem::no(), "reopenPreviouslyOpenedFilesMode") == KMessageBox::Yes)) { + QStringList::const_iterator it, it_end; + it = previouslyOpenedFiles.constBegin(); + it_end = previouslyOpenedFiles.constEnd(); + for (; it != it_end; it++) { + openUrl(*it); + } + KGraphViewerSettings::self()->save(); } - KGraphViewerSettings::self()->save(); - } - -} - -void KGraphViewerWindow::openUrl(const QUrl& url) -{ - qCDebug(KGRAPHVIEWER_LOG) << url; - KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory(); - if (!factory) - { - // if we couldn't find our Part, we exit since the Shell by - // itself can't do anything useful - KMessageBox::error(this, i18n("Could not find the KGraphViewer part.")); - qApp->quit(); - // we return here, cause kapp->quit() only means "exit the - // next time we enter the event loop... - return; - } - KParts::ReadOnlyPart* part = factory->create(this); - KGraphViewer::KGraphViewerInterface* kgv = qobject_cast( part ); - if( ! kgv ) - { - // This should not happen - qCWarning(KGRAPHVIEWER_LOG) << "Failed to get KPart" << endl; - return; +} + +void KGraphViewerWindow::openUrl(const QUrl &url) +{ + qCDebug(KGRAPHVIEWER_LOG) << url; + KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory(); + if (!factory) { + // if we couldn't find our Part, we exit since the Shell by + // itself can't do anything useful + KMessageBox::error(this, i18n("Could not find the KGraphViewer part.")); + qApp->quit(); + // we return here, cause kapp->quit() only means "exit the + // next time we enter the event loop... + return; + } + KParts::ReadOnlyPart *part = factory->create(this); + KGraphViewer::KGraphViewerInterface *kgv = qobject_cast(part); + if (!kgv) { + // This should not happen + qCWarning(KGRAPHVIEWER_LOG) << "Failed to get KPart" << endl; + return; } kgv->setBackgroundColor(KGraphViewerSettings::backgroundColor()); - (KGraphViewerSettings::parsingMode() == "external") - ?kgv->setLayoutMethod(KGraphViewer::KGraphViewerInterface::ExternalProgram) - :kgv->setLayoutMethod(KGraphViewer::KGraphViewerInterface::InternalLibrary); + (KGraphViewerSettings::parsingMode() == "external") ? kgv->setLayoutMethod(KGraphViewer::KGraphViewerInterface::ExternalProgram) : kgv->setLayoutMethod(KGraphViewer::KGraphViewerInterface::InternalLibrary); - if (part) - { - QString fileName = url.url(); - QWidget *w = part->widget(); - - part->openUrl( url ); - - if (m_rfa) - { - m_rfa->addUrl(url); - KSharedConfig::Ptr config = KSharedConfig::openConfig(); - m_rfa->saveEntries(KConfigGroup(config, "kgraphviewer recent files")); - } - - m_openedFiles.push_back(fileName); - m_tabsPartsMap[w] = part; - m_tabsFilesMap[w] = fileName; - connect(this,SIGNAL(hide(KParts::Part*)),part,SLOT(slotHide(KParts::Part*))); - - connect(part, SIGNAL(hoverEnter(QString)), - this, SLOT(slotHoverEnter(QString))); - connect(part, SIGNAL(hoverLeave(QString)), - this, SLOT(slotHoverLeave(QString))); - - m_manager->addPart( part, true ); - const QString label = fileName.section('/', -1, -1); - m_widget->addTab(w, QIcon::fromTheme("kgraphviewer"), label); - m_widget->setCurrentWidget(w); - m_closeAction->setEnabled(true); + if (part) { + QString fileName = url.url(); + QWidget *w = part->widget(); + + part->openUrl(url); + + if (m_rfa) { + m_rfa->addUrl(url); + KSharedConfig::Ptr config = KSharedConfig::openConfig(); + m_rfa->saveEntries(KConfigGroup(config, "kgraphviewer recent files")); + } + + m_openedFiles.push_back(fileName); + m_tabsPartsMap[w] = part; + m_tabsFilesMap[w] = fileName; + connect(this, SIGNAL(hide(KParts::Part *)), part, SLOT(slotHide(KParts::Part *))); + + connect(part, SIGNAL(hoverEnter(QString)), this, SLOT(slotHoverEnter(QString))); + connect(part, SIGNAL(hoverLeave(QString)), this, SLOT(slotHoverLeave(QString))); + + m_manager->addPart(part, true); + const QString label = fileName.section('/', -1, -1); + m_widget->addTab(w, QIcon::fromTheme("kgraphviewer"), label); + m_widget->setCurrentWidget(w); + m_closeAction->setEnabled(true); } } void KGraphViewerWindow::fileOpen() { - qCDebug(KGRAPHVIEWER_LOG) ; - // this slot is called whenever the File->Open menu is selected, - // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar - // button is clicked - QFileDialog fileDialog(this); - fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); - fileDialog.setAcceptMode(QFileDialog::AcceptOpen); - fileDialog.setFileMode(QFileDialog::ExistingFiles); - if (fileDialog.exec() != QFileDialog::Accepted) { - return; - } - - foreach (const QUrl& url, fileDialog.selectedUrls()) { - openUrl(url); - } + qCDebug(KGRAPHVIEWER_LOG); + // this slot is called whenever the File->Open menu is selected, + // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar + // button is clicked + QFileDialog fileDialog(this); + fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("text/vnd.graphviz"))); + fileDialog.setAcceptMode(QFileDialog::AcceptOpen); + fileDialog.setFileMode(QFileDialog::ExistingFiles); + if (fileDialog.exec() != QFileDialog::Accepted) { + return; + } + + foreach (const QUrl &url, fileDialog.selectedUrls()) { + openUrl(url); + } } void KGraphViewerWindow::setupActions() { - // create our actions - QAction* newAction = actionCollection()->addAction( KStandardAction::New, "file_new", this, SLOT(fileNew()) ); - newAction->setWhatsThis(i18n("Opens a new empty KGraphViewer window.")); - - QAction* openAction = actionCollection()->addAction( KStandardAction::Open, "file_open", this, SLOT(fileOpen()) ); - openAction->setWhatsThis(i18n("Shows the file open dialog to choose a Graphviz DOT file to open.")); - - m_rfa = KStandardAction::openRecent(this, SLOT(slotURLSelected(QUrl)), this); - actionCollection()->addAction(m_rfa->objectName(),m_rfa); - m_rfa->setWhatsThis(i18n("This lists files which you have opened recently, and allows you to easily open them again.")); - - KSharedConfig::Ptr config = KSharedConfig::openConfig(); - m_rfa->loadEntries(KConfigGroup(config, "kgraphviewer recent files")); - - m_closeAction = actionCollection()->addAction( KStandardAction::Close, "file_close", this, SLOT(close()) ); - m_closeAction->setWhatsThis(i18n("Closes the current file")); - m_closeAction->setEnabled(false); - - QAction* quitAction = actionCollection()->addAction( KStandardAction::Quit, "file_quit", qApp, SLOT(quit()) ); - quitAction->setWhatsThis(i18n("Quits KGraphViewer.")); - - m_statusbarAction = KStandardAction::showStatusbar(this, SLOT(optionsShowStatusbar()), this); - m_statusbarAction->setWhatsThis(i18n("Shows or hides the status bar.")); - - QAction* kbAction = actionCollection()->addAction( KStandardAction::KeyBindings, "options_configure_keybinding", this, SLOT(optionsConfigureKeys()) ); - kbAction->setWhatsThis(i18n("Configure the bindings between keys and actions.")); - - QAction* ctAction = actionCollection()->addAction( KStandardAction::ConfigureToolbars, "options_configure_toolbars", this, SLOT(optionsConfigureToolbars()) ); - ctAction->setWhatsThis(i18n("Toolbar configuration.")); - - QAction* configureAction = actionCollection()->addAction( KStandardAction::Preferences, "options_configure", this, SLOT(optionsConfigure()) ); - configureAction->setWhatsThis(i18n("Main KGraphViewer configuration options.")); -} - -void KGraphViewerWindow::closeEvent(QCloseEvent* event) -{ - KGraphViewerSettings::setPreviouslyOpenedFiles(m_openedFiles); - KGraphViewerSettings::self()->save(); - KParts::MainWindow::closeEvent(event); + // create our actions + QAction *newAction = actionCollection()->addAction(KStandardAction::New, "file_new", this, SLOT(fileNew())); + newAction->setWhatsThis(i18n("Opens a new empty KGraphViewer window.")); + + QAction *openAction = actionCollection()->addAction(KStandardAction::Open, "file_open", this, SLOT(fileOpen())); + openAction->setWhatsThis(i18n("Shows the file open dialog to choose a Graphviz DOT file to open.")); + + m_rfa = KStandardAction::openRecent(this, SLOT(slotURLSelected(QUrl)), this); + actionCollection()->addAction(m_rfa->objectName(), m_rfa); + m_rfa->setWhatsThis(i18n("This lists files which you have opened recently, and allows you to easily open them again.")); + + KSharedConfig::Ptr config = KSharedConfig::openConfig(); + m_rfa->loadEntries(KConfigGroup(config, "kgraphviewer recent files")); + + m_closeAction = actionCollection()->addAction(KStandardAction::Close, "file_close", this, SLOT(close())); + m_closeAction->setWhatsThis(i18n("Closes the current file")); + m_closeAction->setEnabled(false); + + QAction *quitAction = actionCollection()->addAction(KStandardAction::Quit, "file_quit", qApp, SLOT(quit())); + quitAction->setWhatsThis(i18n("Quits KGraphViewer.")); + + m_statusbarAction = KStandardAction::showStatusbar(this, SLOT(optionsShowStatusbar()), this); + m_statusbarAction->setWhatsThis(i18n("Shows or hides the status bar.")); + + QAction *kbAction = actionCollection()->addAction(KStandardAction::KeyBindings, "options_configure_keybinding", this, SLOT(optionsConfigureKeys())); + kbAction->setWhatsThis(i18n("Configure the bindings between keys and actions.")); + + QAction *ctAction = actionCollection()->addAction(KStandardAction::ConfigureToolbars, "options_configure_toolbars", this, SLOT(optionsConfigureToolbars())); + ctAction->setWhatsThis(i18n("Toolbar configuration.")); + + QAction *configureAction = actionCollection()->addAction(KStandardAction::Preferences, "options_configure", this, SLOT(optionsConfigure())); + configureAction->setWhatsThis(i18n("Main KGraphViewer configuration options.")); +} + +void KGraphViewerWindow::closeEvent(QCloseEvent *event) +{ + KGraphViewerSettings::setPreviouslyOpenedFiles(m_openedFiles); + KGraphViewerSettings::self()->save(); + KParts::MainWindow::closeEvent(event); } void KGraphViewerWindow::fileNew() { - // this slot is called whenever the File->New menu is selected, - // the New shortcut is pressed (usually CTRL+N) or the New toolbar - // button is clicked + // this slot is called whenever the File->New menu is selected, + // the New shortcut is pressed (usually CTRL+N) or the New toolbar + // button is clicked - (new KGraphViewerWindow())->show(); + (new KGraphViewerWindow())->show(); } - void KGraphViewerWindow::optionsShowToolbar() { - // this is all very cut and paste code for showing/hiding the - // toolbar - if (m_toolbarAction->isChecked()) - toolBar()->show(); - else - toolBar()->hide(); + // this is all very cut and paste code for showing/hiding the + // toolbar + if (m_toolbarAction->isChecked()) + toolBar()->show(); + else + toolBar()->hide(); } void KGraphViewerWindow::optionsShowStatusbar() { - // this is all very cut and paste code for showing/hiding the - // statusbar - if (m_statusbarAction->isChecked()) - statusBar()->show(); - else - statusBar()->hide(); + // this is all very cut and paste code for showing/hiding the + // statusbar + if (m_statusbarAction->isChecked()) + statusBar()->show(); + else + statusBar()->hide(); } void KGraphViewerWindow::optionsConfigureKeys() { - KShortcutsDialog::configure(actionCollection()); + KShortcutsDialog::configure(actionCollection()); } void KGraphViewerWindow::optionsConfigureToolbars() { - KConfigGroup group(KConfigGroup(KSharedConfig::openConfig(), "kgraphviewer")); - KMainWindow::saveMainWindowSettings(group); + KConfigGroup group(KConfigGroup(KSharedConfig::openConfig(), "kgraphviewer")); + KMainWindow::saveMainWindowSettings(group); - // use the standard toolbar editor - KEditToolBar dlg(factory()); - connect(&dlg, &KEditToolBar::newToolbarConfig, - this, &KGraphViewerWindow::applyNewToolbarConfig); - dlg.exec(); + // use the standard toolbar editor + KEditToolBar dlg(factory()); + connect(&dlg, &KEditToolBar::newToolbarConfig, this, &KGraphViewerWindow::applyNewToolbarConfig); + dlg.exec(); } void KGraphViewerWindow::optionsConfigure() { - //An instance of your dialog could be already created and could be cached, - //in which case you want to display the cached dialog instead of creating - //another one - if ( KgvConfigurationDialog::showDialog( "settings" ) ) - return; - - //KConfigDialog didn't find an instance of this dialog, so lets create it : - KgvConfigurationDialog* dialog = new KgvConfigurationDialog( this, "settings", KGraphViewerSettings::self()); - connect(dialog, &KgvConfigurationDialog::backgroundColorChanged, - this, &KGraphViewerWindow::slotBackgroundColorChanged); - Ui::KGraphViewerPreferencesParsingWidget* parsingWidget = dialog->parsingWidget; - qCDebug(KGRAPHVIEWER_LOG) << KGraphViewerSettings::parsingMode(); - if (KGraphViewerSettings::parsingMode() == "external") - { - parsingWidget->external->setChecked(true); - } - else if (KGraphViewerSettings::parsingMode() == "internal") - { - parsingWidget->internal->setChecked(true); - } - connect(parsingWidget->external, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotParsingModeExternalToggled); - connect(parsingWidget->internal, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotParsingModeInternalToggled); - - Ui::KGraphViewerPreferencesReloadWidget* reloadWidget = dialog->reloadWidget; - qCDebug(KGRAPHVIEWER_LOG) << KGraphViewerSettings::reloadOnChangeMode(); - if (KGraphViewerSettings::reloadOnChangeMode() == "true") - { - reloadWidget->yes->setChecked(true); - } - else if (KGraphViewerSettings::reloadOnChangeMode() == "false") - { - reloadWidget->no->setChecked(true); - } - else // if (KGraphViewerSettings::reloadOnChangeMode() == "ask") - { - reloadWidget->ask->setChecked(true); - } - - connect(reloadWidget->yes, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReloadOnChangeModeYesToggled); - connect(reloadWidget->no, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReloadOnChangeModeNoToggled); - connect(reloadWidget->ask, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReloadOnChangeModeAskToggled); - - Ui::KGraphViewerPreferencesOpenInExistingWindowWidget* openingWidget = dialog->openingWidget; - if (KGraphViewerSettings::openInExistingWindowMode() == "true") - { - openingWidget->yes->setChecked(true); - } - else if (KGraphViewerSettings::openInExistingWindowMode() == "false") - { - openingWidget->no->setChecked(true); - } - else // if (KGraphViewerSettings::openInExistingWindowMode() == "ask") - { - openingWidget->ask->setChecked(true); - } - - connect(openingWidget->yes, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotOpenInExistingWindowModeYesToggled); - connect(openingWidget->no, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotOpenInExistingWindowModeNoToggled); - connect(openingWidget->ask, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotOpenInExistingWindowModeAskToggled); - - Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget* reopeningWidget = dialog->reopeningWidget; - if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "true") - { - reopeningWidget->yes->setChecked(true); - } - else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "false") - { - reopeningWidget->no->setChecked(true); - } - else // if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") - { - reopeningWidget->ask->setChecked(true); - } - - connect(reopeningWidget->yes, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeYesToggled); - connect(reopeningWidget->no, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeNoToggled); - connect(reopeningWidget->ask, &QRadioButton::toggled, - this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeAskToggled); - - dialog->show(); + // An instance of your dialog could be already created and could be cached, + // in which case you want to display the cached dialog instead of creating + // another one + if (KgvConfigurationDialog::showDialog("settings")) + return; + + // KConfigDialog didn't find an instance of this dialog, so lets create it : + KgvConfigurationDialog *dialog = new KgvConfigurationDialog(this, "settings", KGraphViewerSettings::self()); + connect(dialog, &KgvConfigurationDialog::backgroundColorChanged, this, &KGraphViewerWindow::slotBackgroundColorChanged); + Ui::KGraphViewerPreferencesParsingWidget *parsingWidget = dialog->parsingWidget; + qCDebug(KGRAPHVIEWER_LOG) << KGraphViewerSettings::parsingMode(); + if (KGraphViewerSettings::parsingMode() == "external") { + parsingWidget->external->setChecked(true); + } else if (KGraphViewerSettings::parsingMode() == "internal") { + parsingWidget->internal->setChecked(true); + } + connect(parsingWidget->external, &QRadioButton::toggled, this, &KGraphViewerWindow::slotParsingModeExternalToggled); + connect(parsingWidget->internal, &QRadioButton::toggled, this, &KGraphViewerWindow::slotParsingModeInternalToggled); + + Ui::KGraphViewerPreferencesReloadWidget *reloadWidget = dialog->reloadWidget; + qCDebug(KGRAPHVIEWER_LOG) << KGraphViewerSettings::reloadOnChangeMode(); + if (KGraphViewerSettings::reloadOnChangeMode() == "true") { + reloadWidget->yes->setChecked(true); + } else if (KGraphViewerSettings::reloadOnChangeMode() == "false") { + reloadWidget->no->setChecked(true); + } else // if (KGraphViewerSettings::reloadOnChangeMode() == "ask") + { + reloadWidget->ask->setChecked(true); + } + + connect(reloadWidget->yes, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReloadOnChangeModeYesToggled); + connect(reloadWidget->no, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReloadOnChangeModeNoToggled); + connect(reloadWidget->ask, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReloadOnChangeModeAskToggled); + + Ui::KGraphViewerPreferencesOpenInExistingWindowWidget *openingWidget = dialog->openingWidget; + if (KGraphViewerSettings::openInExistingWindowMode() == "true") { + openingWidget->yes->setChecked(true); + } else if (KGraphViewerSettings::openInExistingWindowMode() == "false") { + openingWidget->no->setChecked(true); + } else // if (KGraphViewerSettings::openInExistingWindowMode() == "ask") + { + openingWidget->ask->setChecked(true); + } + + connect(openingWidget->yes, &QRadioButton::toggled, this, &KGraphViewerWindow::slotOpenInExistingWindowModeYesToggled); + connect(openingWidget->no, &QRadioButton::toggled, this, &KGraphViewerWindow::slotOpenInExistingWindowModeNoToggled); + connect(openingWidget->ask, &QRadioButton::toggled, this, &KGraphViewerWindow::slotOpenInExistingWindowModeAskToggled); + + Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget *reopeningWidget = dialog->reopeningWidget; + if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "true") { + reopeningWidget->yes->setChecked(true); + } else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "false") { + reopeningWidget->no->setChecked(true); + } else // if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") + { + reopeningWidget->ask->setChecked(true); + } + + connect(reopeningWidget->yes, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeYesToggled); + connect(reopeningWidget->no, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeNoToggled); + connect(reopeningWidget->ask, &QRadioButton::toggled, this, &KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeAskToggled); + + dialog->show(); } void KGraphViewerWindow::applyNewToolbarConfig() { - applyMainWindowSettings(KSharedConfig::openConfig()->group("kgraphviewer")); + applyMainWindowSettings(KSharedConfig::openConfig()->group("kgraphviewer")); } void KGraphViewerWindow::slotReloadOnChangeModeYesToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG); - if (value) - { - KGraphViewerSettings::setReloadOnChangeMode("true"); - } - // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; - // emit(settingsChanged()); - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG); + if (value) { + KGraphViewerSettings::setReloadOnChangeMode("true"); + } + // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; + // emit(settingsChanged()); + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotReloadOnChangeModeNoToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG); - if (value) - { - KGraphViewerSettings::setReloadOnChangeMode("false"); - } - // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; - // emit(settingsChanged()); - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG); + if (value) { + KGraphViewerSettings::setReloadOnChangeMode("false"); + } + // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; + // emit(settingsChanged()); + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotReloadOnChangeModeAskToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG); - if (value) - { - KGraphViewerSettings::setReloadOnChangeMode("ask"); - } - // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; - // emit(settingsChanged()); - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG); + if (value) { + KGraphViewerSettings::setReloadOnChangeMode("ask"); + } + // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; + // emit(settingsChanged()); + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotOpenInExistingWindowModeYesToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setOpenInExistingWindowMode("true"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setOpenInExistingWindowMode("true"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotOpenInExistingWindowModeNoToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setOpenInExistingWindowMode("false"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setOpenInExistingWindowMode("false"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotOpenInExistingWindowModeAskToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setOpenInExistingWindowMode("ask"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setOpenInExistingWindowMode("ask"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeYesToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("true"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("true"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeNoToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("false"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("false"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotReopenPreviouslyOpenedFilesModeAskToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG) << value; - if (value) - { - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); - } - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG) << value; + if (value) { + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); + } + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotParsingModeExternalToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG); - if (value) - { - KGraphViewerSettings::setParsingMode("external"); - } - // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; - // emit(settingsChanged()); - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG); + if (value) { + KGraphViewerSettings::setParsingMode("external"); + } + // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; + // emit(settingsChanged()); + KGraphViewerSettings::self()->save(); } void KGraphViewerWindow::slotParsingModeInternalToggled(bool value) { - qCDebug(KGRAPHVIEWER_LOG); - if (value) - { - KGraphViewerSettings::setParsingMode("internal"); - } - // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; - // emit(settingsChanged()); - KGraphViewerSettings::self()->save(); + qCDebug(KGRAPHVIEWER_LOG); + if (value) { + KGraphViewerSettings::setParsingMode("internal"); + } + // qCDebug(KGRAPHVIEWER_LOG) << "emitting"; + // emit(settingsChanged()); + KGraphViewerSettings::self()->save(); } - - -void KGraphViewerWindow::slotURLSelected(const QUrl& url) +void KGraphViewerWindow::slotURLSelected(const QUrl &url) { - openUrl(url); + openUrl(url); } void KGraphViewerWindow::close(int index) { - QWidget *tab = m_widget->widget(index); - m_openedFiles.removeAll(m_tabsFilesMap[tab]); - m_widget->removeTab(index); - tab->hide(); - KParts::Part* part = m_tabsPartsMap[tab]; - m_manager->removePart(part); - m_tabsPartsMap.remove(tab); - m_tabsFilesMap.remove(tab); - delete part; part = nullptr; -/* delete tab; - tab = nullptr;*/ - m_closeAction->setEnabled(m_widget->count() > 0); + QWidget *tab = m_widget->widget(index); + m_openedFiles.removeAll(m_tabsFilesMap[tab]); + m_widget->removeTab(index); + tab->hide(); + KParts::Part *part = m_tabsPartsMap[tab]; + m_manager->removePart(part); + m_tabsPartsMap.remove(tab); + m_tabsFilesMap.remove(tab); + delete part; + part = nullptr; + /* delete tab; + tab = nullptr;*/ + m_closeAction->setEnabled(m_widget->count() > 0); } void KGraphViewerWindow::close() { - int currentPage = m_widget->currentIndex(); - if (currentPage != -1) - { - close(currentPage); - } + int currentPage = m_widget->currentIndex(); + if (currentPage != -1) { + close(currentPage); + } } void KGraphViewerWindow::newTabSelectedSlot(int index) { - emit(hide((KParts::Part*)(m_manager->activePart()))); + emit(hide((KParts::Part *)(m_manager->activePart()))); - QWidget *tab = m_widget->widget(index); - if (tab) { - m_manager->setActivePart(m_tabsPartsMap[tab]); - } + QWidget *tab = m_widget->widget(index); + if (tab) { + m_manager->setActivePart(m_tabsPartsMap[tab]); + } } -void KGraphViewerWindow::slotHoverEnter(const QString& id) +void KGraphViewerWindow::slotHoverEnter(const QString &id) { - qCDebug(KGRAPHVIEWER_LOG) << id; - statusBar()->showMessage(id); + qCDebug(KGRAPHVIEWER_LOG) << id; + statusBar()->showMessage(id); } -void KGraphViewerWindow::slotHoverLeave(const QString& id) +void KGraphViewerWindow::slotHoverLeave(const QString &id) { - qCDebug(KGRAPHVIEWER_LOG) << id; - statusBar()->showMessage(""); + qCDebug(KGRAPHVIEWER_LOG) << id; + statusBar()->showMessage(""); } -void KGraphViewerWindow::slotBackgroundColorChanged(const QColor&) +void KGraphViewerWindow::slotBackgroundColorChanged(const QColor &) { - qCDebug(KGRAPHVIEWER_LOG); - foreach(KParts::Part* part, m_tabsPartsMap) - { - KGraphViewer::KGraphViewerInterface* kgv = qobject_cast( part ); - if( ! kgv ) - { - // This should not happen - return; + qCDebug(KGRAPHVIEWER_LOG); + foreach (KParts::Part *part, m_tabsPartsMap) { + KGraphViewer::KGraphViewerInterface *kgv = qobject_cast(part); + if (!kgv) { + // This should not happen + return; + } + kgv->setBackgroundColor(KGraphViewerSettings::backgroundColor()); } - kgv->setBackgroundColor(KGraphViewerSettings::backgroundColor()); - } } diff --git a/src/kgraphviewerConfigDialog.h b/src/kgraphviewerConfigDialog.h --- a/src/kgraphviewerConfigDialog.h +++ b/src/kgraphviewerConfigDialog.h @@ -16,21 +16,21 @@ 02110-1301, USA */ - #ifndef KGRAPHVIEWERCONFIGDIALOG_H #define KGRAPHVIEWERCONFIGDIALOG_H #include -#include #include +#include -namespace Ui { - class KGraphViewerPreferencesParsingWidget; - class KGraphViewerPreferencesReloadWidget; - class KGraphViewerPreferencesOpenInExistingWindowWidget; - class KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget; - class KGraphViewerPreferencesAppearanceWidget; +namespace Ui +{ +class KGraphViewerPreferencesParsingWidget; +class KGraphViewerPreferencesReloadWidget; +class KGraphViewerPreferencesOpenInExistingWindowWidget; +class KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget; +class KGraphViewerPreferencesAppearanceWidget; } /** @@ -41,33 +41,33 @@ */ class KgvConfigurationDialog : public KConfigDialog { - Q_OBJECT + Q_OBJECT public: - KgvConfigurationDialog (QWidget *parent, const QString& name, KConfigSkeleton *config); + KgvConfigurationDialog(QWidget *parent, const QString &name, KConfigSkeleton *config); - ~KgvConfigurationDialog() override; + ~KgvConfigurationDialog() override; Q_SIGNALS: - void backgroundColorChanged(const QColor& color); - + void backgroundColorChanged(const QColor &color); + protected Q_SLOTS: - void updateSettings() override; - void updateWidgets() override; + void updateSettings() override; + void updateWidgets() override; - void settingChanged(int); - void slotBackgroundColorChanged(const QColor& color); + void settingChanged(int); + void slotBackgroundColorChanged(const QColor &color); protected: - bool hasChanged() override; + bool hasChanged() override; - bool m_changed; + bool m_changed; public: - Ui::KGraphViewerPreferencesParsingWidget* parsingWidget; - Ui::KGraphViewerPreferencesReloadWidget* reloadWidget; - Ui::KGraphViewerPreferencesOpenInExistingWindowWidget* openingWidget; - Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget* reopeningWidget; - Ui::KGraphViewerPreferencesAppearanceWidget* appearanceWidget; + Ui::KGraphViewerPreferencesParsingWidget *parsingWidget; + Ui::KGraphViewerPreferencesReloadWidget *reloadWidget; + Ui::KGraphViewerPreferencesOpenInExistingWindowWidget *openingWidget; + Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget *reopeningWidget; + Ui::KGraphViewerPreferencesAppearanceWidget *appearanceWidget; }; #endif diff --git a/src/kgraphviewerConfigDialog.cpp b/src/kgraphviewerConfigDialog.cpp --- a/src/kgraphviewerConfigDialog.cpp +++ b/src/kgraphviewerConfigDialog.cpp @@ -16,170 +16,163 @@ 02110-1301, USA */ - -#include "kgraphviewer_debug.h" #include "kgraphviewerConfigDialog.h" +#include "kgraphviewer_debug.h" #include "kgraphviewersettings.h" -#include "ui_preferencesReload.h" -#include "ui_preferencesParsing.h" +#include "ui_preferencesAppearance.h" #include "ui_preferencesOpenInExistingWindow.h" +#include "ui_preferencesParsing.h" +#include "ui_preferencesReload.h" #include "ui_preferencesReopenPreviouslyOpenedFiles.h" -#include "ui_preferencesAppearance.h" +#include #include -#include -#include #include -#include +#include +#include #include -#include +#include -#include #include +#include #include #include #include #include //#include //#include -#include #include +#include -KgvConfigurationDialog::KgvConfigurationDialog (QWidget *parent, const QString& name, KConfigSkeleton *config) : - KConfigDialog(parent, name, config), - m_changed(false), - parsingWidget(new Ui::KGraphViewerPreferencesParsingWidget()), - reloadWidget(new Ui::KGraphViewerPreferencesReloadWidget()), - openingWidget(new Ui::KGraphViewerPreferencesOpenInExistingWindowWidget()), - reopeningWidget(new Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget()), - appearanceWidget(new Ui::KGraphViewerPreferencesAppearanceWidget()) +KgvConfigurationDialog::KgvConfigurationDialog(QWidget *parent, const QString &name, KConfigSkeleton *config) + : KConfigDialog(parent, name, config) + , m_changed(false) + , parsingWidget(new Ui::KGraphViewerPreferencesParsingWidget()) + , reloadWidget(new Ui::KGraphViewerPreferencesReloadWidget()) + , openingWidget(new Ui::KGraphViewerPreferencesOpenInExistingWindowWidget()) + , reopeningWidget(new Ui::KGraphViewerPreferencesReopenPreviouslyOpenedFilesWidget()) + , appearanceWidget(new Ui::KGraphViewerPreferencesAppearanceWidget()) { - QWidget* page4 = new QWidget(); - appearanceWidget->setupUi(page4); - QWidget* page0 = new QWidget(); - parsingWidget->setupUi(page0); - QWidget* page1 = new QWidget(); - reloadWidget->setupUi(page1); - QWidget* page2 = new QWidget(); - openingWidget->setupUi(page2); - QWidget* page3 = new QWidget(); - reopeningWidget->setupUi(page3); - - appearanceWidget->kcolorbutton->setColor(KGraphViewerSettings::backgroundColor()); - appearanceWidget->kcolorbutton->setDefaultColor(KGraphViewerSettings::backgroundColor()); - addPage( page4, i18n("Appearance"), "preferences-other", i18n("Appearance"), false); - addPage( page0, i18n("Parsing"), "preferences-other", i18n("Parsing"), false); - addPage( page1, i18n("Reloading"), "view-refresh", i18n("Reloading"), false); - addPage( page2, i18n("Opening"), "document-open", i18n("Opening"), false); - addPage( page3, i18n("Session Management"), "preferences-other", i18n("Session Management"), false); - connect(parsingWidget->parsingMode, &QGroupBox::clicked, - this, &KgvConfigurationDialog::settingChanged); - connect(reloadWidget->reloadOnChangeMode, &QGroupBox::clicked, - this, &KgvConfigurationDialog::settingChanged); - connect(openingWidget->openInExistingWindowMode, &QGroupBox::clicked, - this, &KgvConfigurationDialog::settingChanged); - connect(reopeningWidget->reopenPreviouslyOpenedFilesMode, &QGroupBox::clicked, - this, &KgvConfigurationDialog::settingChanged); - connect(appearanceWidget->kcolorbutton, &KColorButton::changed, - this, &KgvConfigurationDialog::slotBackgroundColorChanged); + QWidget *page4 = new QWidget(); + appearanceWidget->setupUi(page4); + QWidget *page0 = new QWidget(); + parsingWidget->setupUi(page0); + QWidget *page1 = new QWidget(); + reloadWidget->setupUi(page1); + QWidget *page2 = new QWidget(); + openingWidget->setupUi(page2); + QWidget *page3 = new QWidget(); + reopeningWidget->setupUi(page3); + + appearanceWidget->kcolorbutton->setColor(KGraphViewerSettings::backgroundColor()); + appearanceWidget->kcolorbutton->setDefaultColor(KGraphViewerSettings::backgroundColor()); + addPage(page4, i18n("Appearance"), "preferences-other", i18n("Appearance"), false); + addPage(page0, i18n("Parsing"), "preferences-other", i18n("Parsing"), false); + addPage(page1, i18n("Reloading"), "view-refresh", i18n("Reloading"), false); + addPage(page2, i18n("Opening"), "document-open", i18n("Opening"), false); + addPage(page3, i18n("Session Management"), "preferences-other", i18n("Session Management"), false); + connect(parsingWidget->parsingMode, &QGroupBox::clicked, this, &KgvConfigurationDialog::settingChanged); + connect(reloadWidget->reloadOnChangeMode, &QGroupBox::clicked, this, &KgvConfigurationDialog::settingChanged); + connect(openingWidget->openInExistingWindowMode, &QGroupBox::clicked, this, &KgvConfigurationDialog::settingChanged); + connect(reopeningWidget->reopenPreviouslyOpenedFilesMode, &QGroupBox::clicked, this, &KgvConfigurationDialog::settingChanged); + connect(appearanceWidget->kcolorbutton, &KColorButton::changed, this, &KgvConfigurationDialog::slotBackgroundColorChanged); } -KgvConfigurationDialog::~KgvConfigurationDialog () +KgvConfigurationDialog::~KgvConfigurationDialog() { } void KgvConfigurationDialog::settingChanged(int) { -// std::cerr << "KgvConfigurationDialog::settingChanged" << std::endl; - m_changed = true; + // std::cerr << "KgvConfigurationDialog::settingChanged" << std::endl; + m_changed = true; } bool KgvConfigurationDialog::hasChanged() { -// std::cerr << "KgvConfigurationDialog::hasChanged" << std::endl; - return m_changed; + // std::cerr << "KgvConfigurationDialog::hasChanged" << std::endl; + return m_changed; } void KgvConfigurationDialog::updateSettings() { -// std::cerr << "KgvConfigurationDialog::updateSettings" << std::endl; - m_changed = false; -/* switch (openingWidget->openInExistingWindowMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setOpenInExistingWindowMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setOpenInExistingWindowMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setOpenInExistingWindowMode("ask"); - break; - default: ; - } - switch (reloadWidget->reloadOnChangeMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setReloadOnChangeMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setReloadOnChangeMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setReloadOnChangeMode("ask"); - break; - default: ; - } - switch (reopeningWidget->reopenPreviouslyOpenedFilesMode->selectedId()) - { - case 0: // no - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("no"); - break; - case 1: // yes - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("yes"); - break; - case 2: // ask - KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); - break; - default: ; - }*/ - //@TODO to port - //KGraphViewerSettings::writeConfig(); + // std::cerr << "KgvConfigurationDialog::updateSettings" << std::endl; + m_changed = false; + /* switch (openingWidget->openInExistingWindowMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setOpenInExistingWindowMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setOpenInExistingWindowMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setOpenInExistingWindowMode("ask"); + break; + default: ; + } + switch (reloadWidget->reloadOnChangeMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setReloadOnChangeMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setReloadOnChangeMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setReloadOnChangeMode("ask"); + break; + default: ; + } + switch (reopeningWidget->reopenPreviouslyOpenedFilesMode->selectedId()) + { + case 0: // no + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("no"); + break; + case 1: // yes + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("yes"); + break; + case 2: // ask + KGraphViewerSettings::setReopenPreviouslyOpenedFilesMode("ask"); + break; + default: ; + }*/ + //@TODO to port + // KGraphViewerSettings::writeConfig(); } void KgvConfigurationDialog::updateWidgets() { - m_changed = false; - qCDebug(KGRAPHVIEWER_LOG) << " openInExistingWindowMode: " << KGraphViewerSettings::openInExistingWindowMode(); -// if (KGraphViewerSettings::openInExistingWindowMode() == "no") -// openingWidget->openInExistingWindowMode->setButton(0); -// else if (KGraphViewerSettings::openInExistingWindowMode() == "yes") -// openingWidget->openInExistingWindowMode->setButton(1); -// else if (KGraphViewerSettings::openInExistingWindowMode() == "ask") -// openingWidget->openInExistingWindowMode->setButton(2); - - -// std::cerr << " reloadOnChangeMode: " << KGraphViewerSettings::reloadOnChangeMode() << std::endl; -// if (KGraphViewerSettings::reloadOnChangeMode() == "no") -// reloadWidget->reloadOnChangeMode->setButton(0); -// else if (KGraphViewerSettings::reloadOnChangeMode() == "yes") -// reloadWidget->reloadOnChangeMode->setButton(1); -// else if (KGraphViewerSettings::reloadOnChangeMode() == "ask") -// reloadWidget->reloadOnChangeMode->setButton(2); - -// std::cerr << " reopenPreviouslyOpenedFilesMode: " << KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() << std::endl; -/* if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "no") - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); - else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "yes") - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); - else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") - reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2);*/ + m_changed = false; + qCDebug(KGRAPHVIEWER_LOG) << " openInExistingWindowMode: " << KGraphViewerSettings::openInExistingWindowMode(); + // if (KGraphViewerSettings::openInExistingWindowMode() == "no") + // openingWidget->openInExistingWindowMode->setButton(0); + // else if (KGraphViewerSettings::openInExistingWindowMode() == "yes") + // openingWidget->openInExistingWindowMode->setButton(1); + // else if (KGraphViewerSettings::openInExistingWindowMode() == "ask") + // openingWidget->openInExistingWindowMode->setButton(2); + + // std::cerr << " reloadOnChangeMode: " << KGraphViewerSettings::reloadOnChangeMode() << std::endl; + // if (KGraphViewerSettings::reloadOnChangeMode() == "no") + // reloadWidget->reloadOnChangeMode->setButton(0); + // else if (KGraphViewerSettings::reloadOnChangeMode() == "yes") + // reloadWidget->reloadOnChangeMode->setButton(1); + // else if (KGraphViewerSettings::reloadOnChangeMode() == "ask") + // reloadWidget->reloadOnChangeMode->setButton(2); + + // std::cerr << " reopenPreviouslyOpenedFilesMode: " << KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() << std::endl; + /* if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "no") + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(0); + else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "yes") + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(1); + else if (KGraphViewerSettings::reopenPreviouslyOpenedFilesMode() == "ask") + reopeningWidget->reopenPreviouslyOpenedFilesMode->setButton(2);*/ } -void KgvConfigurationDialog::slotBackgroundColorChanged(const QColor& color) +void KgvConfigurationDialog::slotBackgroundColorChanged(const QColor &color) { - KGraphViewerSettings::setBackgroundColor(color); - emit backgroundColorChanged(color); + KGraphViewerSettings::setBackgroundColor(color); + emit backgroundColorChanged(color); } diff --git a/src/main.cpp b/src/main.cpp --- a/src/main.cpp +++ b/src/main.cpp @@ -16,134 +16,117 @@ 02110-1301, USA */ - #include "kgraphviewer.h" #include "kgraphviewer_debug.h" +#include "config-kgraphviewer.h" +#include "kgraphvieweradaptor.h" +#include #include -#include -#include -#include -#include -#include -#include #include -#include +#include #include #include +#include #include +#include +#include +#include +#include +#include #include -#include -#include "kgraphvieweradaptor.h" -#include "config-kgraphviewer.h" int main(int argc, char **argv) { - QApplication app(argc, argv); - - KLocalizedString::setApplicationDomain("kgraphviewer"); - - KAboutData about(QStringLiteral("kgraphviewer"), - i18n("KGraphViewer"), - KGRAPHVIEWER_VERSION_STRING, - i18n("A Graphviz DOT graph viewer"), - KAboutLicense::GPL, - i18n("(C) 2005-2010 Gaƫl de Chalendar"), - QString(), - QStringLiteral("https://www.kde.org/applications/graphics/kgraphviewer")); - about.addAuthor( i18n("Gaƫl de Chalendar"), i18n("Original Author and current maintainer"), "kleag@free.fr" ); - about.addAuthor( i18n("Reimar Dƶffinger"), i18n("Contributor"), "kde@reimardoeffinger.de" ); - about.addAuthor( i18n("Matthias Peinhardt"), i18n("Contributor"), "matthias.peinhardt@googlemail.com" ); - about.addAuthor( i18n("Sandro Andrade"), i18n("Contributor"), "sandro.andrade@gmail.com" ); - about.addAuthor( i18n("Milian Wolff"), i18n("Contributor"), "mail@milianw.de" ); - about.addAuthor( i18n("Martin Sandsmark"), i18n("Port to KF5"), "martin.sandsmark@kde.org" ); - - app.setOrganizationDomain(QStringLiteral("kde.org")); - app.setOrganizationName(QStringLiteral("KDE")); - - KAboutData::setApplicationData(about); - - app.setWindowIcon(QIcon::fromTheme("kgraphviewer", app.windowIcon())); - - QCommandLineParser options; - options.addHelpOption(); - options.addVersionOption(); - options.addPositionalArgument(QStringLiteral("url"), i18n("Path or URL to scan"), i18n("[url]")); - about.setupCommandLine(&options); - options.process(app); - about.processCommandLine(&options); - -// see if we are starting with session management - if (app.isSessionRestored()) - { - RESTORE(KGraphViewerWindow); - } - else - { - // no session.. just start up normally - QStringList args = options.positionalArguments(); - - KGraphViewerWindow *widget = nullptr; - if ( args.count() == 0 ) - { - widget = new KGraphViewerWindow; - new KgraphviewerAdaptor(widget); - QDBusConnection::sessionBus().registerObject("/KGraphViewer", widget); - widget->show(); - } - else - { - QDBusReply reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kgraphviewer" ); - - bool instanceExists = reply.value(); - - for (int i = 0; i < args.count(); i++ ) - { - if (instanceExists - && (QMessageBox::question(nullptr, - i18n("Opening in new window confirmation"), - i18n("A KGraphViewer window is already open, where do you want to open this file in the existing window?")) - == QMessageBox::Yes)) - { - QByteArray tosenddata; - QDataStream arg(&tosenddata, QIODevice::WriteOnly); - QString strarg = args[i]; - QUrl url; - if (strarg.left(1) == "/") - url = QUrl::fromUserInput(strarg); - else url = QUrl::fromLocalFile(QDir::currentPath() + '/' + strarg); - arg << url; - QDBusInterface iface("org.kde.kgraphviewer", "/KGraphViewer", "", QDBusConnection::sessionBus()); - if (iface.isValid()) - { - QDBusReply reply = iface.call("openUrl", url.url(QUrl::PreferLocalFile)); - if (reply.isValid()) - { - qCWarning(KGRAPHVIEWER_LOG) << "Reply was valid"; - return 0; - } - - qCWarning(KGRAPHVIEWER_LOG) << "Call failed: " << reply.error().message() << endl; - return 1; - } - qCWarning(KGRAPHVIEWER_LOG) << "Invalid interface" << endl; - exit(0); - } - else - { + QApplication app(argc, argv); + + KLocalizedString::setApplicationDomain("kgraphviewer"); + + KAboutData about(QStringLiteral("kgraphviewer"), + i18n("KGraphViewer"), + KGRAPHVIEWER_VERSION_STRING, + i18n("A Graphviz DOT graph viewer"), + KAboutLicense::GPL, + i18n("(C) 2005-2010 Gaƫl de Chalendar"), + QString(), + QStringLiteral("https://www.kde.org/applications/graphics/kgraphviewer")); + about.addAuthor(i18n("Gaƫl de Chalendar"), i18n("Original Author and current maintainer"), "kleag@free.fr"); + about.addAuthor(i18n("Reimar Dƶffinger"), i18n("Contributor"), "kde@reimardoeffinger.de"); + about.addAuthor(i18n("Matthias Peinhardt"), i18n("Contributor"), "matthias.peinhardt@googlemail.com"); + about.addAuthor(i18n("Sandro Andrade"), i18n("Contributor"), "sandro.andrade@gmail.com"); + about.addAuthor(i18n("Milian Wolff"), i18n("Contributor"), "mail@milianw.de"); + about.addAuthor(i18n("Martin Sandsmark"), i18n("Port to KF5"), "martin.sandsmark@kde.org"); + + app.setOrganizationDomain(QStringLiteral("kde.org")); + app.setOrganizationName(QStringLiteral("KDE")); + + KAboutData::setApplicationData(about); + + app.setWindowIcon(QIcon::fromTheme("kgraphviewer", app.windowIcon())); + + QCommandLineParser options; + options.addHelpOption(); + options.addVersionOption(); + options.addPositionalArgument(QStringLiteral("url"), i18n("Path or URL to scan"), i18n("[url]")); + about.setupCommandLine(&options); + options.process(app); + about.processCommandLine(&options); + + // see if we are starting with session management + if (app.isSessionRestored()) { + RESTORE(KGraphViewerWindow); + } else { + // no session.. just start up normally + QStringList args = options.positionalArguments(); + + KGraphViewerWindow *widget = nullptr; + if (args.count() == 0) { widget = new KGraphViewerWindow; new KgraphviewerAdaptor(widget); QDBusConnection::sessionBus().registerObject("/KGraphViewer", widget); widget->show(); - widget->openUrl( QUrl::fromUserInput(args[i])); - } + } else { + QDBusReply reply = QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kgraphviewer"); + + bool instanceExists = reply.value(); + + for (int i = 0; i < args.count(); i++) { + if (instanceExists && + (QMessageBox::question(nullptr, i18n("Opening in new window confirmation"), i18n("A KGraphViewer window is already open, where do you want to open this file in the existing window?")) == QMessageBox::Yes)) { + QByteArray tosenddata; + QDataStream arg(&tosenddata, QIODevice::WriteOnly); + QString strarg = args[i]; + QUrl url; + if (strarg.left(1) == "/") + url = QUrl::fromUserInput(strarg); + else + url = QUrl::fromLocalFile(QDir::currentPath() + '/' + strarg); + arg << url; + QDBusInterface iface("org.kde.kgraphviewer", "/KGraphViewer", "", QDBusConnection::sessionBus()); + if (iface.isValid()) { + QDBusReply reply = iface.call("openUrl", url.url(QUrl::PreferLocalFile)); + if (reply.isValid()) { + qCWarning(KGRAPHVIEWER_LOG) << "Reply was valid"; + return 0; + } + + qCWarning(KGRAPHVIEWER_LOG) << "Call failed: " << reply.error().message() << endl; + return 1; + } + qCWarning(KGRAPHVIEWER_LOG) << "Invalid interface" << endl; + exit(0); + } else { + widget = new KGraphViewerWindow; + new KgraphviewerAdaptor(widget); + QDBusConnection::sessionBus().registerObject("/KGraphViewer", widget); + widget->show(); + widget->openUrl(QUrl::fromUserInput(args[i])); + } + } + } + if (widget) { + widget->reloadPreviousFiles(); } - } - if (widget) - { - widget->reloadPreviousFiles(); } - - } - return app.exec(); + return app.exec(); } diff --git a/src/part/DotGraphParsingHelper.h b/src/part/DotGraphParsingHelper.h --- a/src/part/DotGraphParsingHelper.h +++ b/src/part/DotGraphParsingHelper.h @@ -19,8 +19,8 @@ #ifndef DOT_GRAPHPARSINGHELPER_H #define DOT_GRAPHPARSINGHELPER_H -#include #include +#include #include namespace KGraphViewer @@ -31,54 +31,53 @@ class GraphEdge; class GraphElement; -struct DotGraphParsingHelper -{ - typedef std::map< std::string, std::string > AttributesMap; - - DotGraphParsingHelper(); - - void createnode(const std::string& nodeid); - void createsubgraph(); - void setgraphattributes(); - void setsubgraphattributes(); - void setnodeattributes(); - void setedgeattributes(); - void setattributedlist(); - void createedges(); - void edgebound(const std::string& bound) {edgebounds.push_back(bound);} - void finalactions(); - void setgraphelementattributes(GraphElement* ge, const AttributesMap& attributes); - - std::string attrid; - std::string valid; - std::string attributed; - std::string subgraphid; - - unsigned int uniq; - - AttributesMap attributes; - AttributesMap graphAttributes; - AttributesMap nodesAttributes; - AttributesMap edgesAttributes; - std::list< AttributesMap > graphAttributesStack; - std::list< AttributesMap > nodesAttributesStack; - std::list< AttributesMap > edgesAttributesStack; - - std::list< std::string > edgebounds; - - unsigned int z; - unsigned int maxZ; - - DotGraph* graph; - - GraphSubgraph* gs; - GraphNode* gn; - GraphEdge* ge; -}; +struct DotGraphParsingHelper { + typedef std::map AttributesMap; -} + DotGraphParsingHelper(); -#endif + void createnode(const std::string &nodeid); + void createsubgraph(); + void setgraphattributes(); + void setsubgraphattributes(); + void setnodeattributes(); + void setedgeattributes(); + void setattributedlist(); + void createedges(); + void edgebound(const std::string &bound) + { + edgebounds.push_back(bound); + } + void finalactions(); + void setgraphelementattributes(GraphElement *ge, const AttributesMap &attributes); + + std::string attrid; + std::string valid; + std::string attributed; + std::string subgraphid; + + unsigned int uniq; + AttributesMap attributes; + AttributesMap graphAttributes; + AttributesMap nodesAttributes; + AttributesMap edgesAttributes; + std::list graphAttributesStack; + std::list nodesAttributesStack; + std::list edgesAttributesStack; + std::list edgebounds; + unsigned int z; + unsigned int maxZ; + + DotGraph *graph; + + GraphSubgraph *gs; + GraphNode *gn; + GraphEdge *ge; +}; + +} + +#endif diff --git a/src/part/DotGraphParsingHelper.cpp b/src/part/DotGraphParsingHelper.cpp --- a/src/part/DotGraphParsingHelper.cpp +++ b/src/part/DotGraphParsingHelper.cpp @@ -16,334 +16,300 @@ 02110-1301, USA */ - #include "DotGraphParsingHelper.h" -#include "dotgraph.h" -#include "dotgrammar.h" #include "dotdefaults.h" +#include "dotgrammar.h" +#include "dotgraph.h" //#include "graphsubgraph.h" -#include "graphnode.h" #include "graphedge.h" +#include "graphnode.h" #include "kgraphviewerlib_debug.h" -#include +#include #include #include #include -#include - +#include #include #include - + #include -#include +#include using namespace std; -extern KGraphViewer::DotGraphParsingHelper* phelper; +extern KGraphViewer::DotGraphParsingHelper *phelper; namespace KGraphViewer { #define KGV_MAX_ITEMS_TO_LOAD std::numeric_limits::max() -DotGraphParsingHelper::DotGraphParsingHelper(): - attrid(), - valid(), - attributed(), - subgraphid(), - uniq(0), - attributes(), - graphAttributes(), - nodesAttributes(), - edgesAttributes(), - graphAttributesStack(), - nodesAttributesStack(), - edgesAttributesStack(), - edgebounds(), - z(0), - maxZ(0), - graph(nullptr), - gs(nullptr), - gn(nullptr), - ge(nullptr) +DotGraphParsingHelper::DotGraphParsingHelper() + : attrid() + , valid() + , attributed() + , subgraphid() + , uniq(0) + , attributes() + , graphAttributes() + , nodesAttributes() + , edgesAttributes() + , graphAttributesStack() + , nodesAttributesStack() + , edgesAttributesStack() + , edgebounds() + , z(0) + , maxZ(0) + , graph(nullptr) + , gs(nullptr) + , gn(nullptr) + , ge(nullptr) { } -void DotGraphParsingHelper::setgraphelementattributes(GraphElement* ge, const AttributesMap& attributes) +void DotGraphParsingHelper::setgraphelementattributes(GraphElement *ge, const AttributesMap &attributes) { - AttributesMap::const_iterator it, it_end; - it = attributes.begin(); it_end = attributes.end(); - for (; it != it_end; it++) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << "\t=\t'" << QString::fromStdString((*it).second) <<"'"; - if ((*it).first=="label") - { - QString label = QString::fromUtf8((*it).second.c_str()); - label.replace("\\n","\n"); - (*ge).attributes()["label"] = label; + AttributesMap::const_iterator it, it_end; + it = attributes.begin(); + it_end = attributes.end(); + for (; it != it_end; it++) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << "\t=\t'" << QString::fromStdString((*it).second) <<"'"; + if ((*it).first == "label") { + QString label = QString::fromUtf8((*it).second.c_str()); + label.replace("\\n", "\n"); + (*ge).attributes()["label"] = label; + } else { + (*ge).attributes()[QString::fromStdString((*it).first)] = QString::fromStdString((*it).second); + } + } + + DotRenderOpVec ops = ge->renderOperations(); + if (attributes.find("_draw_") != attributes.end()) { + parse_renderop((attributes.find("_draw_"))->second, ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); } - else - { - (*ge).attributes()[QString::fromStdString((*it).first)] = - QString::fromStdString((*it).second); + if (attributes.find("_ldraw_") != attributes.end()) { + parse_renderop(attributes.find("_ldraw_")->second, ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); } - } - - DotRenderOpVec ops = ge->renderOperations(); - if (attributes.find("_draw_") != attributes.end()) - { - parse_renderop((attributes.find("_draw_"))->second, ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); - } - if (attributes.find("_ldraw_") != attributes.end()) - { - parse_renderop(attributes.find("_ldraw_")->second, ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); - } - if (attributes.find("_hldraw_") != attributes.end()) - { - parse_renderop(attributes.find("_hldraw_")->second, ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); - } - if (attributes.find("_tldraw_") != attributes.end()) - { - parse_renderop(attributes.find("_tldraw_")->second, ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); - } - ge->setRenderOperations(ops); + if (attributes.find("_hldraw_") != attributes.end()) { + parse_renderop(attributes.find("_hldraw_")->second, ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); + } + if (attributes.find("_tldraw_") != attributes.end()) { + parse_renderop(attributes.find("_tldraw_")->second, ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ge->renderOperations().size(); + } + ge->setRenderOperations(ops); } void DotGraphParsingHelper::setgraphattributes() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for graph are : "; - setgraphelementattributes(graph, graphAttributes); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for graph are : "; + setgraphelementattributes(graph, graphAttributes); } void DotGraphParsingHelper::setsubgraphattributes() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for subgraph are : "; - gs->setZ(z); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); - setgraphelementattributes(gs, graphAttributes); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for subgraph are : "; + gs->setZ(z); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); + setgraphelementattributes(gs, graphAttributes); } void DotGraphParsingHelper::setnodeattributes() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setnodeattributes with z = " << z; - - if (gn == nullptr) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "gn is null"; - return; - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for node " << gn->id() << " are : "; - gn->setZ(z+1); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); - setgraphelementattributes(gn, nodesAttributes); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setnodeattributes with z = " << z; + + if (gn == nullptr) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "gn is null"; + return; + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for node " << gn->id() << " are : "; + gn->setZ(z + 1); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); + setgraphelementattributes(gn, nodesAttributes); } void DotGraphParsingHelper::setedgeattributes() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setedgeattributeswith z = " << z; - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for edge " << ge->fromNode()->id() << "->" << ge->toNode()->id() << " are : "; - ge->setZ(z+1); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); - setgraphelementattributes(ge, edgesAttributes); - - DotRenderOpVec ops = ge->renderOperations(); - if (edgesAttributes.find("_tdraw_") != edgesAttributes.end()) - { - parse_renderop(edgesAttributes["_tdraw_"], ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "edge renderOperations size is now " << ge->renderOperations().size(); - DotRenderOpVec::const_iterator it, it_end; - it = ops.constBegin(); it_end = ops.constEnd(); - for (; it != it_end; it++) - ge->arrowheads().push_back(*it); - } - if (edgesAttributes.find("_hdraw_") != edgesAttributes.end()) - { - parse_renderop(edgesAttributes["_hdraw_"], ops); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "edge renderOperations size is now " << ge->renderOperations().size(); - DotRenderOpVec::const_iterator it, it_end; - it = ops.constBegin(); it_end = ops.constEnd(); - for (; it != it_end; it++) - ge->arrowheads().push_back(*it); - } - ge->setRenderOperations(ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setedgeattributeswith z = " << z; + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Attributes for edge " << ge->fromNode()->id() << "->" << ge->toNode()->id() << " are : "; + ge->setZ(z + 1); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "z="<z(); + setgraphelementattributes(ge, edgesAttributes); + + DotRenderOpVec ops = ge->renderOperations(); + if (edgesAttributes.find("_tdraw_") != edgesAttributes.end()) { + parse_renderop(edgesAttributes["_tdraw_"], ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "edge renderOperations size is now " << ge->renderOperations().size(); + DotRenderOpVec::const_iterator it, it_end; + it = ops.constBegin(); + it_end = ops.constEnd(); + for (; it != it_end; it++) + ge->arrowheads().push_back(*it); + } + if (edgesAttributes.find("_hdraw_") != edgesAttributes.end()) { + parse_renderop(edgesAttributes["_hdraw_"], ops); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "edge renderOperations size is now " << ge->renderOperations().size(); + DotRenderOpVec::const_iterator it, it_end; + it = ops.constBegin(); + it_end = ops.constEnd(); + for (; it != it_end; it++) + ge->arrowheads().push_back(*it); + } + ge->setRenderOperations(ops); } void DotGraphParsingHelper::setattributedlist() { -// // qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting attributes list for " << QString::fromStdString(attributed); - if (attributed == "graph") - { - if (attributes.find("bb") != attributes.end()) - { - std::vector< int > v; - parse_integers(attributes["bb"].c_str(), v); - if (v.size()>=4) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setting width and height to " << v[2] << v[3]; - graph->width(v[2]); - graph->height(v[3]); - } - } - AttributesMap::const_iterator it, it_end; - it = attributes.begin(); it_end = attributes.end(); - for (; it != it_end; it++) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); - graphAttributes[(*it).first] = (*it).second; + // // qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting attributes list for " << QString::fromStdString(attributed); + if (attributed == "graph") { + if (attributes.find("bb") != attributes.end()) { + std::vector v; + parse_integers(attributes["bb"].c_str(), v); + if (v.size() >= 4) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setting width and height to " << v[2] << v[3]; + graph->width(v[2]); + graph->height(v[3]); + } + } + AttributesMap::const_iterator it, it_end; + it = attributes.begin(); + it_end = attributes.end(); + for (; it != it_end; it++) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); + graphAttributes[(*it).first] = (*it).second; + } + } else if (attributed == "node") { + AttributesMap::const_iterator it, it_end; + it = attributes.begin(); + it_end = attributes.end(); + for (; it != it_end; it++) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); + nodesAttributes[(*it).first] = (*it).second; + } + } else if (attributed == "edge") { + AttributesMap::const_iterator it, it_end; + it = attributes.begin(); + it_end = attributes.end(); + for (; it != it_end; it++) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); + edgesAttributes[(*it).first] = (*it).second; + } } - } - else if (attributed == "node") - { - AttributesMap::const_iterator it, it_end; - it = attributes.begin(); it_end = attributes.end(); - for (; it != it_end; it++) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); - nodesAttributes[(*it).first] = (*it).second; - } - } - else if (attributed == "edge") - { - AttributesMap::const_iterator it, it_end; - it = attributes.begin(); it_end = attributes.end(); - for (; it != it_end; it++) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << " " << QString::fromStdString((*it).first) << " = " << QString::fromStdString((*it).second); - edgesAttributes[(*it).first] = (*it).second; - } - } - attributes.clear(); + attributes.clear(); } -void DotGraphParsingHelper::createnode(const std::string& nodeid) +void DotGraphParsingHelper::createnode(const std::string &nodeid) { - QString id = QString::fromStdString(nodeid); -// qCDebug(KGRAPHVIEWERLIB_LOG) << id; - gn = dynamic_cast(graph->elementNamed(id)); - if (gn==nullptr && graph->nodes().size() < KGV_MAX_ITEMS_TO_LOAD) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating a new node" << z << (void*)gs; - gn = new GraphNode(); - gn->setId(id); -// gn->label(QString::fromStdString(nodeid)); - if (z>0 && gs) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding node" << id << "in subgraph" << gs->id(); - gs->content().push_back(gn); - } - else - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding node" << id; - graph->nodes()[id] = gn; + QString id = QString::fromStdString(nodeid); + // qCDebug(KGRAPHVIEWERLIB_LOG) << id; + gn = dynamic_cast(graph->elementNamed(id)); + if (gn == nullptr && graph->nodes().size() < KGV_MAX_ITEMS_TO_LOAD) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating a new node" << z << (void*)gs; + gn = new GraphNode(); + gn->setId(id); + // gn->label(QString::fromStdString(nodeid)); + if (z > 0 && gs) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding node" << id << "in subgraph" << gs->id(); + gs->content().push_back(gn); + } else { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding node" << id; + graph->nodes()[id] = gn; + } } - } - edgebounds.clear(); + edgebounds.clear(); } void DotGraphParsingHelper::createsubgraph() { -// qCDebug(KGRAPHVIEWERLIB_LOG) ; - if (phelper) - { - std::string str = phelper->subgraphid; - if (str.empty()) - { - std::ostringstream oss; - oss << "kgv_id_" << phelper->uniq++; - str = oss.str(); + // qCDebug(KGRAPHVIEWERLIB_LOG) ; + if (phelper) { + std::string str = phelper->subgraphid; + if (str.empty()) { + std::ostringstream oss; + oss << "kgv_id_" << phelper->uniq++; + str = oss.str(); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(str); + if (graph->subgraphs().find(QString::fromStdString(str)) == graph->subgraphs().end()) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating a new subgraph"; + gs = new GraphSubgraph(); + gs->setId(QString::fromStdString(str)); + // gs->label(QString::fromStdString(str)); + graph->subgraphs().insert(QString::fromStdString(str), gs); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "there is now"<subgraphs().size()<<"subgraphs in" << graph; + } else { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Found existing subgraph"; + gs = *(graph->subgraphs().find(QString::fromStdString(str))); + } + phelper->subgraphid = ""; } -// qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(str); - if (graph->subgraphs().find(QString::fromStdString(str)) == graph->subgraphs().end()) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating a new subgraph"; - gs = new GraphSubgraph(); - gs->setId(QString::fromStdString(str)); -// gs->label(QString::fromStdString(str)); - graph->subgraphs().insert(QString::fromStdString(str), gs); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "there is now"<subgraphs().size()<<"subgraphs in" << graph; - } - else - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Found existing subgraph"; - gs = *(graph->subgraphs().find(QString::fromStdString(str))); - } - phelper->subgraphid = ""; - } } void DotGraphParsingHelper::createedges() { -// qCDebug(KGRAPHVIEWERLIB_LOG); - std::string node1Name, node2Name; - node1Name = edgebounds.front(); - edgebounds.pop_front(); - while (!edgebounds.empty()) - { - node2Name = edgebounds.front(); + // qCDebug(KGRAPHVIEWERLIB_LOG); + std::string node1Name, node2Name; + node1Name = edgebounds.front(); edgebounds.pop_front(); + while (!edgebounds.empty()) { + node2Name = edgebounds.front(); + edgebounds.pop_front(); - if (graph->nodes().size() >= KGV_MAX_ITEMS_TO_LOAD || graph->edges().size() >= KGV_MAX_ITEMS_TO_LOAD) - { - return; - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(node1Name) << ", " << QString::fromStdString(node2Name); - ge = new GraphEdge(); - GraphElement* gn1 = graph->elementNamed(QString::fromStdString(node1Name)); - if (gn1 == nullptr) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "new node 1"; - gn1 = new GraphNode(); - gn1->setId(QString::fromStdString(node1Name)); - graph->nodes()[QString::fromStdString(node1Name)] = dynamic_cast(gn1); - } - GraphElement* gn2 = graph->elementNamed(QString::fromStdString(node2Name)); - if (gn2 == nullptr) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "new node 2"; - gn2 = new GraphNode(); - gn2->setId(QString::fromStdString(node2Name)); - graph->nodes()[QString::fromStdString(node2Name)] = dynamic_cast(gn2); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Found gn1="< " << ge->toNode()->id(); - setedgeattributes(); -// qCDebug(KGRAPHVIEWERLIB_LOG) << ge->id(); - if (ge->id().isEmpty()) - { - ge->setId(QString::fromStdString(node1Name)+QString::fromStdString(node2Name)+QUuid::createUuid().toString().remove('{').remove('}').remove('-')); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << ge->id(); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "num before=" << graph->edges().size(); - graph->edges().insert(ge->id(), ge); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "num after=" << graph->edges().size(); - + if (graph->nodes().size() >= KGV_MAX_ITEMS_TO_LOAD || graph->edges().size() >= KGV_MAX_ITEMS_TO_LOAD) { + return; + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(node1Name) << ", " << QString::fromStdString(node2Name); + ge = new GraphEdge(); + GraphElement *gn1 = graph->elementNamed(QString::fromStdString(node1Name)); + if (gn1 == nullptr) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new node 1"; + gn1 = new GraphNode(); + gn1->setId(QString::fromStdString(node1Name)); + graph->nodes()[QString::fromStdString(node1Name)] = dynamic_cast(gn1); + } + GraphElement *gn2 = graph->elementNamed(QString::fromStdString(node2Name)); + if (gn2 == nullptr) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new node 2"; + gn2 = new GraphNode(); + gn2->setId(QString::fromStdString(node2Name)); + graph->nodes()[QString::fromStdString(node2Name)] = dynamic_cast(gn2); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Found gn1="< " << ge->toNode()->id(); + setedgeattributes(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << ge->id(); + if (ge->id().isEmpty()) { + ge->setId(QString::fromStdString(node1Name) + QString::fromStdString(node2Name) + QUuid::createUuid().toString().remove('{').remove('}').remove('-')); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << ge->id(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "num before=" << graph->edges().size(); + graph->edges().insert(ge->id(), ge); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "num after=" << graph->edges().size(); - node1Name = node2Name; - } - edgebounds.clear(); + node1Name = node2Name; + } + edgebounds.clear(); } void DotGraphParsingHelper::finalactions() { - GraphEdgeMap::iterator it, it_end; - it = graph->edges().begin(); it_end = graph->edges().end(); - for (; it != it_end; it++) - { - (*it)->setZ(maxZ+1); - } + GraphEdgeMap::iterator it, it_end; + it = graph->edges().begin(); + it_end = graph->edges().end(); + for (; it != it_end; it++) { + (*it)->setZ(maxZ + 1); + } } } diff --git a/src/part/FontsCache.h b/src/part/FontsCache.h --- a/src/part/FontsCache.h +++ b/src/part/FontsCache.h @@ -16,7 +16,6 @@ 02110-1301, USA */ - #ifndef KGRAPHVIEWER_FONTSCACHE_H #define KGRAPHVIEWER_FONTSCACHE_H @@ -32,22 +31,22 @@ * @short A fonts map * @author Gaƫl de Chalendar */ -class FontsCache : - public Singleton, - public QMap +class FontsCache : public Singleton, public QMap { -friend class Singleton; + friend class Singleton; public: - ~FontsCache(); + ~FontsCache(); - QFont* cachedFont(const QFont& font); - QFont* fromName(const QString& font); + QFont *cachedFont(const QFont &font); + QFont *fromName(const QString &font); private: - FontsCache() {} + FontsCache() + { + } - QMap m_namesToFonts; + QMap m_namesToFonts; }; #endif diff --git a/src/part/FontsCache.cpp b/src/part/FontsCache.cpp --- a/src/part/FontsCache.cpp +++ b/src/part/FontsCache.cpp @@ -16,36 +16,33 @@ 02110-1301, USA */ - #include "FontsCache.h" #include "dot2qtconsts.h" FontsCache::~FontsCache() { - FontsCache::iterator it, it_end; - it = begin(); it_end = end(); - for (; it != it_end; it++) - { - delete (*it); - } + FontsCache::iterator it, it_end; + it = begin(); + it_end = end(); + for (; it != it_end; it++) { + delete (*it); + } } -QFont* FontsCache::cachedFont(const QFont& font) +QFont *FontsCache::cachedFont(const QFont &font) { - if (find(font.key()) == end()) - { - (*this)[font.key()] = new QFont(font); - } - return (*this)[font.key()]; + if (find(font.key()) == end()) { + (*this)[font.key()] = new QFont(font); + } + return (*this)[font.key()]; } -QFont* FontsCache::fromName(const QString& fontName) +QFont *FontsCache::fromName(const QString &fontName) { - if (m_namesToFonts.find(fontName) == m_namesToFonts.end()) - { - QFont font(Dot2QtConsts::componentData().qtFont(fontName)); - m_namesToFonts[fontName] = cachedFont(font); - } - return m_namesToFonts[fontName]; + if (m_namesToFonts.find(fontName) == m_namesToFonts.end()) { + QFont font(Dot2QtConsts::componentData().qtFont(fontName)); + m_namesToFonts[fontName] = cachedFont(font); + } + return m_namesToFonts[fontName]; } diff --git a/src/part/KgvGlobal.h b/src/part/KgvGlobal.h --- a/src/part/KgvGlobal.h +++ b/src/part/KgvGlobal.h @@ -28,28 +28,30 @@ #ifndef kgvGlobal_h #define kgvGlobal_h -#include +#include #include #include #include -#include +#include class KConfig; class KgvGlobal { public: /// For KgvApplication - static void initialize() { + static void initialize() + { (void)self(); // I don't want to make KGlobal instances public, so self() is private } /** * Return the default font for KOffice programs. * This is (currently) the same as the KDE-global default font, * except that it is guaranteed to have a point size set, * never a pixel size (see @ref QFont). */ - static QFont defaultFont() { + static QFont defaultFont() + { return self()->_defaultFont(); } @@ -59,52 +61,55 @@ * so this is the centralization of the KConfig object so that the file is * parsed only once */ - static KConfig* kofficeConfig() { + static KConfig *kofficeConfig() + { return self()->_kofficeConfig(); } - static int dpiX() { + static int dpiX() + { return qApp->primaryScreen()->physicalDotsPerInchX(); } - static int dpiY() { + static int dpiY() + { return qApp->primaryScreen()->physicalDotsPerInchY(); } /// Return the list of available languages, in their displayable form /// (translated names) -// static QStringList listOfLanguages() { -// return self()->_listOfLanguages(); -// } + // static QStringList listOfLanguages() { + // return self()->_listOfLanguages(); + // } /// Return the list of available languages, in their internal form /// e.g. "fr" or "en_US", here called "tag" -// static QStringList listTagOfLanguages() { // TODO rename to listOfLanguageTags -// return self()->_listOfLanguageTags(); -// } + // static QStringList listTagOfLanguages() { // TODO rename to listOfLanguageTags + // return self()->_listOfLanguageTags(); + // } /// For a given language display name, return its tag - static QString tagOfLanguage( const QString & _lang ); + static QString tagOfLanguage(const QString &_lang); /// For a given language tag, return its display name - static QString languageFromTag( const QString &_lang ); + static QString languageFromTag(const QString &_lang); ~KgvGlobal(); private: - static KgvGlobal* self(); + static KgvGlobal *self(); KgvGlobal(); QFont _defaultFont(); -// QStringList _listOfLanguages(); -// QStringList _listOfLanguageTags(); - KConfig* _kofficeConfig(); -// void createListOfLanguages(); + // QStringList _listOfLanguages(); + // QStringList _listOfLanguageTags(); + KConfig *_kofficeConfig(); + // void createListOfLanguages(); int m_pointSize; typedef QMap LanguageMap; LanguageMap m_langMap; // display-name -> language tag - KConfig* m_kofficeConfig; + KConfig *m_kofficeConfig; // No BC problem here, constructor is private, feel free to add members // Singleton pattern. Maybe this should even be refcounted, so // that it gets cleaned up when closing all koffice parts in e.g. konqueror? - static KgvGlobal* s_global; + static KgvGlobal *s_global; friend class this_is_a_singleton; // work around gcc warning }; diff --git a/src/part/KgvGlobal.cpp b/src/part/KgvGlobal.cpp --- a/src/part/KgvGlobal.cpp +++ b/src/part/KgvGlobal.cpp @@ -26,39 +26,39 @@ */ #include "kgraphviewerlib_debug.h" +#include #include +#include #include #include -#include -#include #include -#include -#include #include +#include +#include // #include -#include #include +#include - -KgvGlobal* KgvGlobal::s_global = nullptr; +KgvGlobal *KgvGlobal::s_global = nullptr; // static K3StaticDeleter sdg; -KgvGlobal* KgvGlobal::self() +KgvGlobal *KgvGlobal::self() { - if ( !s_global ) - s_global = new KgvGlobal ; -// sdg.setObject( s_global, new KgvGlobal ); + if (!s_global) + s_global = new KgvGlobal; + // sdg.setObject( s_global, new KgvGlobal ); return s_global; } KgvGlobal::KgvGlobal() - : m_pointSize( -1 ), m_kofficeConfig(nullptr) + : m_pointSize(-1) + , m_kofficeConfig(nullptr) { // Install the libkoffice* translations -// KGlobal::locale()->insertCatalogue("koffice"); + // KGlobal::locale()->insertCatalogue("koffice"); // Tell the iconloader about share/apps/koffice/icons -// KGlobal::iconLoader()->addAppDir("koffice"); + // KGlobal::iconLoader()->addAppDir("koffice"); // Another way to get the DPI of the display would be QPaintDeviceMetrics, // but we have no widget here (and moving this to KgvView wouldn't allow @@ -74,16 +74,15 @@ { QFont font = qApp->font(); // we have to use QFontInfo, in case the font was specified with a pixel size - if ( font.pointSize() == -1 ) - { + if (font.pointSize() == -1) { // cache size into m_pointSize, since QFontInfo loads the font -> slow - if ( m_pointSize == -1 ) + if (m_pointSize == -1) m_pointSize = QFontInfo(font).pointSize(); - Q_ASSERT( m_pointSize != -1 ); - font.setPointSize( m_pointSize ); + Q_ASSERT(m_pointSize != -1); + font.setPointSize(m_pointSize); } - //qCDebug(KGRAPHVIEWERLIB_LOG)<<"QFontInfo(font).pointSize() :"< seenLanguages; // const QStringList langlist = config.groupList(); // for ( QStringList::ConstIterator itall = langlist.begin(); @@ -116,18 +115,18 @@ // config.setGroup( tag ); // const QString name = config.readEntry("Name", tag); // // e.g. name is "French" and tag is "fr" -// +// // // The QMap does the sorting on the display-name, so that // // comboboxes are sorted. // m_langMap.insert( name, tag ); -// +// // seenLanguages.insert( tag, true ); // } -// +// // // Also take a look at the installed translations. // // Many of them are already in all_languages but all_languages doesn't // // currently have en_GB or en_US etc. -// +// // const QStringList translationList = KGlobal::dirs()->findAllResources("locale", // QString::fromLatin1("*/entry.desktop")); // for ( QStringList::ConstIterator it = translationList.begin(); @@ -139,52 +138,52 @@ // tag = tag.left(index); // index = tag.findRev('/'); // tag = tag.mid(index+1); -// +// // if ( seenLanguages.find( tag ) == seenLanguages.end() ) { // // KSimpleConfig entry(*it); // // entry.setGroup("KCM Locale"); -// +// // // const QString name = entry.readEntry("Name", tag); // // e.g. name is "US English" and tag is "en_US" // // m_langMap.insert( name, tag ); -// +// // // enable this if writing a third way of finding languages below // //seenLanguages.insert( tag, true ); // } -// +// // } -// +// // // #### We also might not have an entry for a language where spellchecking is supported, // // but no KDE translation is available, like fr_CA. // // How to add them? // } -QString KgvGlobal::tagOfLanguage( const QString & _lang) +QString KgvGlobal::tagOfLanguage(const QString &_lang) { - const LanguageMap& map = self()->m_langMap; - QMap::ConstIterator it = map.find( _lang ); - if ( it != map.end() ) + const LanguageMap &map = self()->m_langMap; + QMap::ConstIterator it = map.find(_lang); + if (it != map.end()) return *it; return QString(); } -QString KgvGlobal::languageFromTag( const QString &langTag ) +QString KgvGlobal::languageFromTag(const QString &langTag) { - const LanguageMap& map = self()->m_langMap; - QMap::ConstIterator it = map.begin(); - const QMap::ConstIterator end = map.end(); - for ( ; it != end; ++it ) - if ( it.value() == langTag ) + const LanguageMap &map = self()->m_langMap; + QMap::ConstIterator it = map.begin(); + const QMap::ConstIterator end = map.end(); + for (; it != end; ++it) + if (it.value() == langTag) return it.key(); // Language code not found. Better return the code (tag) than nothing. return langTag; } -KConfig* KgvGlobal::_kofficeConfig() +KConfig *KgvGlobal::_kofficeConfig() { - if ( !m_kofficeConfig ) { - m_kofficeConfig = new KConfig( "kofficerc" ); + if (!m_kofficeConfig) { + m_kofficeConfig = new KConfig("kofficerc"); } return m_kofficeConfig; } diff --git a/src/part/KgvPageLayout.h b/src/part/KgvPageLayout.h --- a/src/part/KgvPageLayout.h +++ b/src/part/KgvPageLayout.h @@ -77,92 +77,87 @@ /** * Represents the orientation of a printed document. */ -enum KgvOrientation { - PG_PORTRAIT = 0, - PG_LANDSCAPE = 1 -}; +enum KgvOrientation { PG_PORTRAIT = 0, PG_LANDSCAPE = 1 }; namespace KgvPageFormat { - /** - * @brief Convert a KgvFormat into a QPageSize::PageSizeId. - * - * If format is 'screen' it will use A4 landscape. - * If format is 'custom' it will use A4 portrait. - * (you may want to take care of those cases separately). - * Usually passed to QPrinter::setPageSize(). - * - * @note We return int instead of the enum to avoid including QPageSize - */ - int /*QPageSize::PageSizeId*/ printerPageSize( KgvFormat format ); +/** + * @brief Convert a KgvFormat into a QPageSize::PageSizeId. + * + * If format is 'screen' it will use A4 landscape. + * If format is 'custom' it will use A4 portrait. + * (you may want to take care of those cases separately). + * Usually passed to QPrinter::setPageSize(). + * + * @note We return int instead of the enum to avoid including QPageSize + */ +int /*QPageSize::PageSizeId*/ printerPageSize(KgvFormat format); - /** - * Returns the width (in mm) for a given page format and orientation - * 'Custom' isn't supported by this function, obviously. - */ - double width( KgvFormat format, KgvOrientation orientation ); +/** + * Returns the width (in mm) for a given page format and orientation + * 'Custom' isn't supported by this function, obviously. + */ +double width(KgvFormat format, KgvOrientation orientation); - /** - * Returns the height (in mm) for a given page format and orientation - * 'Custom' isn't supported by this function, obviously. - */ - double height( KgvFormat format, KgvOrientation orientation ); +/** + * Returns the height (in mm) for a given page format and orientation + * 'Custom' isn't supported by this function, obviously. + */ +double height(KgvFormat format, KgvOrientation orientation); - /** - * Returns the internal name of the given page format. - * Use for saving. - */ - QString formatString( KgvFormat format ); +/** + * Returns the internal name of the given page format. + * Use for saving. + */ +QString formatString(KgvFormat format); - /** - * Convert a format string (internal name) to a page format value. - * Use for loading. - */ - KgvFormat formatFromString( const QString & string ); +/** + * Convert a format string (internal name) to a page format value. + * Use for loading. + */ +KgvFormat formatFromString(const QString &string); - /** - * Returns the default format (based on the KControl settings) - */ - KgvFormat defaultFormat(); +/** + * Returns the default format (based on the KControl settings) + */ +KgvFormat defaultFormat(); - /** - * Returns the translated name of the given page format. - * Use for showing the user. - */ - QString name( KgvFormat format ); +/** + * Returns the translated name of the given page format. + * Use for showing the user. + */ +QString name(KgvFormat format); - /** - * Lists the translated names of all the available formats - */ - QStringList allFormats(); +/** + * Lists the translated names of all the available formats + */ +QStringList allFormats(); - /** - * Try to find the paper format for the given width and height (in mm). - * Useful to some import filters. - */ - KgvFormat guessFormat( double width, double height ); +/** + * Try to find the paper format for the given width and height (in mm). + * Useful to some import filters. + */ +KgvFormat guessFormat(double width, double height); } - /** * @brief Header/Footer type. * * @note Yes, this should have been a bitfield, but there was only 0, 2, 3 in koffice-1.0. Don't ask why. * In the long run this should be replaced with a more flexible repetition/section concept. */ enum KgvHFType { - HF_SAME = 0, ///< 0: Header/Footer is the same on all pages - HF_FIRST_EO_DIFF = 1, ///< 1: Header/Footer is different on first, even and odd pages (2&3) - HF_FIRST_DIFF = 2, ///< 2: Header/Footer for the first page differs - HF_EO_DIFF = 3 ///< 3: Header/Footer for even - odd pages are different + HF_SAME = 0, ///< 0: Header/Footer is the same on all pages + HF_FIRST_EO_DIFF = 1, ///< 1: Header/Footer is different on first, even and odd pages (2&3) + HF_FIRST_DIFF = 2, ///< 2: Header/Footer for the first page differs + HF_EO_DIFF = 3 ///< 3: Header/Footer for even - odd pages are different }; /** * This structure defines the page layout, including * its size in pt, its format (e.g. A4), orientation, unit, margins etc. */ -struct KgvPageLayout -{ +struct KgvPageLayout { /** Page format */ KgvFormat format; /** Page orientation */ @@ -183,18 +178,13 @@ double ptPageEdge; double ptBindingSide; - bool operator==( const KgvPageLayout& l ) const { - return ( ptWidth == l.ptWidth && - ptHeight == l.ptHeight && - ptLeft == l.ptLeft && - ptRight == l.ptRight && - ptTop == l.ptTop && - ptBottom == l.ptBottom && - ptPageEdge == l.ptPageEdge && - ptBindingSide == l.ptBindingSide); + bool operator==(const KgvPageLayout &l) const + { + return (ptWidth == l.ptWidth && ptHeight == l.ptHeight && ptLeft == l.ptLeft && ptRight == l.ptRight && ptTop == l.ptTop && ptBottom == l.ptBottom && ptPageEdge == l.ptPageEdge && ptBindingSide == l.ptBindingSide); } - bool operator!=( const KgvPageLayout& l ) const { - return !( (*this) == l ); + bool operator!=(const KgvPageLayout &l) const + { + return !((*this) == l); } /** @@ -206,8 +196,7 @@ }; /** structure for header-footer */ -struct KgvHeadFoot -{ +struct KgvHeadFoot { QString headLeft; QString headMid; QString headRight; @@ -217,38 +206,35 @@ }; /** structure for columns */ -struct KgvColumns -{ +struct KgvColumns { int columns; double ptColumnSpacing; - bool operator==( const KgvColumns& rhs ) const { - return columns == rhs.columns && - qAbs(ptColumnSpacing - rhs.ptColumnSpacing) <= 1E-10; + bool operator==(const KgvColumns &rhs) const + { + return columns == rhs.columns && qAbs(ptColumnSpacing - rhs.ptColumnSpacing) <= 1E-10; } - bool operator!=( const KgvColumns& rhs ) const { - return columns != rhs.columns || - qAbs(ptColumnSpacing - rhs.ptColumnSpacing) > 1E-10; + bool operator!=(const KgvColumns &rhs) const + { + return columns != rhs.columns || qAbs(ptColumnSpacing - rhs.ptColumnSpacing) > 1E-10; } }; /** structure for KWord header-footer */ -struct KgvKWHeaderFooter -{ +struct KgvKWHeaderFooter { KgvHFType header; KgvHFType footer; double ptHeaderBodySpacing; double ptFooterBodySpacing; double ptFootNoteBodySpacing; - bool operator==( const KgvKWHeaderFooter& rhs ) const { - return header == rhs.header && footer == rhs.footer && - qAbs(ptHeaderBodySpacing - rhs.ptHeaderBodySpacing) <= 1E-10 && - qAbs(ptFooterBodySpacing - rhs.ptFooterBodySpacing) <= 1E-10 && - qAbs(ptFootNoteBodySpacing - rhs.ptFootNoteBodySpacing) <= 1E-10; + bool operator==(const KgvKWHeaderFooter &rhs) const + { + return header == rhs.header && footer == rhs.footer && qAbs(ptHeaderBodySpacing - rhs.ptHeaderBodySpacing) <= 1E-10 && qAbs(ptFooterBodySpacing - rhs.ptFooterBodySpacing) <= 1E-10 && + qAbs(ptFootNoteBodySpacing - rhs.ptFootNoteBodySpacing) <= 1E-10; } - bool operator!=( const KgvKWHeaderFooter& rhs ) const { - return !( *this == rhs ); + bool operator!=(const KgvKWHeaderFooter &rhs) const + { + return !(*this == rhs); } }; #endif /* KOPAGELAYOUT_H */ - diff --git a/src/part/KgvPageLayout.cpp b/src/part/KgvPageLayout.cpp --- a/src/part/KgvPageLayout.cpp +++ b/src/part/KgvPageLayout.cpp @@ -25,176 +25,161 @@ version 2 of the License, or (at your option) any later version. */ -#include "kgraphviewerlib_debug.h" #include "KgvPageLayout.h" +#include "kgraphviewerlib_debug.h" +#include #include #include -#include #include #include -#include #include +#include KgvPageLayout KgvPageLayout::standardLayout() { KgvPageLayout layout; layout.format = KgvPageFormat::defaultFormat(); layout.orientation = PG_PORTRAIT; - layout.ptWidth = MM_TO_POINT( KgvPageFormat::width( layout.format, layout.orientation ) ); - layout.ptHeight = MM_TO_POINT( KgvPageFormat::height( layout.format, layout.orientation ) ); - layout.ptLeft = MM_TO_POINT( 20.0 ); - layout.ptRight = MM_TO_POINT( 20.0 ); - layout.ptTop = MM_TO_POINT( 20.0 ); - layout.ptBottom = MM_TO_POINT( 20.0 ); + layout.ptWidth = MM_TO_POINT(KgvPageFormat::width(layout.format, layout.orientation)); + layout.ptHeight = MM_TO_POINT(KgvPageFormat::height(layout.format, layout.orientation)); + layout.ptLeft = MM_TO_POINT(20.0); + layout.ptRight = MM_TO_POINT(20.0); + layout.ptTop = MM_TO_POINT(20.0); + layout.ptBottom = MM_TO_POINT(20.0); layout.ptPageEdge = -1; layout.ptBindingSide = -1; qCDebug(KGRAPHVIEWERLIB_LOG) << "Returning standardLayout"; return layout; } -struct PageFormatInfo -{ +struct PageFormatInfo { KgvFormat format; QPageSize::PageSizeId pageSize; - const char* shortName; // Short name - const char* descriptiveName; // Full name, which will be translated; nullptr to use QPageSize + const char *shortName; // Short name + const char *descriptiveName; // Full name, which will be translated; nullptr to use QPageSize }; -const PageFormatInfo pageFormatInfo[]= +const PageFormatInfo pageFormatInfo[] = {{PG_DIN_A3, QPageSize::A3, "A3", nullptr}, + {PG_DIN_A4, QPageSize::A4, "A4", nullptr}, + {PG_DIN_A5, QPageSize::A5, "A5", nullptr}, + {PG_US_LETTER, QPageSize::Letter, "Letter", nullptr}, + {PG_US_LEGAL, QPageSize::Legal, "Legal", nullptr}, + {PG_SCREEN, QPageSize::A4, "Screen", I18N_NOOP2("Page size", "Screen")}, // Custom, so fall back to A4 + {PG_CUSTOM, QPageSize::A4, "Custom", I18N_NOOP2("Page size", "Custom")}, // Custom, so fall back to A4 + {PG_DIN_B5, QPageSize::B5, "B5", nullptr}, + {PG_US_EXECUTIVE, QPageSize::Executive, "Executive", nullptr}, + {PG_DIN_A0, QPageSize::A0, "A0", nullptr}, + {PG_DIN_A1, QPageSize::A1, "A1", nullptr}, + {PG_DIN_A2, QPageSize::A2, "A2", nullptr}, + {PG_DIN_A6, QPageSize::A6, "A6", nullptr}, + {PG_DIN_A7, QPageSize::A7, "A7", nullptr}, + {PG_DIN_A8, QPageSize::A8, "A8", nullptr}, + {PG_DIN_A9, QPageSize::A9, "A9", nullptr}, + {PG_DIN_B0, QPageSize::B0, "B0", nullptr}, + {PG_DIN_B1, QPageSize::B1, "B1", nullptr}, + {PG_DIN_B10, QPageSize::B10, "B10", nullptr}, + {PG_DIN_B2, QPageSize::B2, "B2", nullptr}, + {PG_DIN_B3, QPageSize::B3, "B3", nullptr}, + {PG_DIN_B4, QPageSize::B4, "B4", nullptr}, + {PG_DIN_B6, QPageSize::B6, "B6", nullptr}, + {PG_ISO_C5, QPageSize::C5E, "C5", nullptr}, + {PG_US_COMM10, QPageSize::Comm10E, "Comm10", nullptr}, + {PG_ISO_DL, QPageSize::DLE, "DL", nullptr}, + {PG_US_FOLIO, QPageSize::Folio, "Folio", nullptr}, + {PG_US_LEDGER, QPageSize::Ledger, "Ledger", nullptr}, + {PG_US_TABLOID, QPageSize::Tabloid, "Tabloid", nullptr}}; + +int KgvPageFormat::printerPageSize(KgvFormat format) { - { PG_DIN_A3, QPageSize::A3, "A3", nullptr }, - { PG_DIN_A4, QPageSize::A4, "A4", nullptr }, - { PG_DIN_A5, QPageSize::A5, "A5", nullptr }, - { PG_US_LETTER, QPageSize::Letter, "Letter", nullptr }, - { PG_US_LEGAL, QPageSize::Legal, "Legal", nullptr }, - { PG_SCREEN, QPageSize::A4, "Screen", I18N_NOOP2("Page size", "Screen") }, // Custom, so fall back to A4 - { PG_CUSTOM, QPageSize::A4, "Custom", I18N_NOOP2("Page size", "Custom") }, // Custom, so fall back to A4 - { PG_DIN_B5, QPageSize::B5, "B5", nullptr }, - { PG_US_EXECUTIVE, QPageSize::Executive, "Executive", nullptr }, - { PG_DIN_A0, QPageSize::A0, "A0", nullptr }, - { PG_DIN_A1, QPageSize::A1, "A1", nullptr }, - { PG_DIN_A2, QPageSize::A2, "A2", nullptr }, - { PG_DIN_A6, QPageSize::A6, "A6", nullptr }, - { PG_DIN_A7, QPageSize::A7, "A7", nullptr }, - { PG_DIN_A8, QPageSize::A8, "A8", nullptr }, - { PG_DIN_A9, QPageSize::A9, "A9", nullptr }, - { PG_DIN_B0, QPageSize::B0, "B0", nullptr }, - { PG_DIN_B1, QPageSize::B1, "B1", nullptr }, - { PG_DIN_B10, QPageSize::B10, "B10", nullptr }, - { PG_DIN_B2, QPageSize::B2, "B2", nullptr }, - { PG_DIN_B3, QPageSize::B3, "B3", nullptr }, - { PG_DIN_B4, QPageSize::B4, "B4", nullptr }, - { PG_DIN_B6, QPageSize::B6, "B6", nullptr }, - { PG_ISO_C5, QPageSize::C5E, "C5", nullptr }, - { PG_US_COMM10, QPageSize::Comm10E, "Comm10", nullptr }, - { PG_ISO_DL, QPageSize::DLE, "DL", nullptr }, - { PG_US_FOLIO, QPageSize::Folio, "Folio", nullptr }, - { PG_US_LEDGER, QPageSize::Ledger, "Ledger", nullptr }, - { PG_US_TABLOID, QPageSize::Tabloid, "Tabloid", nullptr } -}; - -int KgvPageFormat::printerPageSize( KgvFormat format ) -{ - if ( format == PG_SCREEN ) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "You use the page layout SCREEN. Printing in DIN A4 LANDSCAPE."; - return QPageSize::A4; - } - else if ( format == PG_CUSTOM ) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "The used page layout (CUSTOM) is not supported by QPrinter. Printing in A4."; - return QPageSize::A4; - } - else if ( format <= PG_LAST_FORMAT ) - return pageFormatInfo[ format ].pageSize; + if (format == PG_SCREEN) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "You use the page layout SCREEN. Printing in DIN A4 LANDSCAPE."; + return QPageSize::A4; + } else if (format == PG_CUSTOM) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "The used page layout (CUSTOM) is not supported by QPrinter. Printing in A4."; + return QPageSize::A4; + } else if (format <= PG_LAST_FORMAT) + return pageFormatInfo[format].pageSize; else return QPageSize::A4; } -double KgvPageFormat::width( KgvFormat format, KgvOrientation orientation ) +double KgvPageFormat::width(KgvFormat format, KgvOrientation orientation) { - if ( orientation == PG_LANDSCAPE ) - return height( format, PG_PORTRAIT ); - if ( format <= PG_LAST_FORMAT ) - return QPageSize::size( pageFormatInfo[ format ].pageSize, QPageSize::Millimeter ).width(); - return QPageSize::size( QPageSize::A4, QPageSize::Millimeter ).width(); // should never happen + if (orientation == PG_LANDSCAPE) + return height(format, PG_PORTRAIT); + if (format <= PG_LAST_FORMAT) + return QPageSize::size(pageFormatInfo[format].pageSize, QPageSize::Millimeter).width(); + return QPageSize::size(QPageSize::A4, QPageSize::Millimeter).width(); // should never happen } -double KgvPageFormat::height( KgvFormat format, KgvOrientation orientation ) +double KgvPageFormat::height(KgvFormat format, KgvOrientation orientation) { - if ( orientation == PG_LANDSCAPE ) - return width( format, PG_PORTRAIT ); - if ( format <= PG_LAST_FORMAT ) - return QPageSize::size( pageFormatInfo[ format ].pageSize, QPageSize::Millimeter ).height(); - return QPageSize::size( QPageSize::A4, QPageSize::Millimeter ).height(); + if (orientation == PG_LANDSCAPE) + return width(format, PG_PORTRAIT); + if (format <= PG_LAST_FORMAT) + return QPageSize::size(pageFormatInfo[format].pageSize, QPageSize::Millimeter).height(); + return QPageSize::size(QPageSize::A4, QPageSize::Millimeter).height(); } -KgvFormat KgvPageFormat::guessFormat( double width, double height ) +KgvFormat KgvPageFormat::guessFormat(double width, double height) { - for ( int i = 0 ; i <= PG_LAST_FORMAT ; ++i ) - { - const QSizeF ps = QPageSize::size( pageFormatInfo[i].pageSize, QPageSize::Millimeter ); + for (int i = 0; i <= PG_LAST_FORMAT; ++i) { + const QSizeF ps = QPageSize::size(pageFormatInfo[i].pageSize, QPageSize::Millimeter); // We have some tolerance. 1pt is a third of a mm, this is // barely noticeable for a page size. - if ( i != PG_CUSTOM - && qAbs( width - ps.width() ) < 1.0 - && qAbs( height - ps.height() ) < 1.0 ) + if (i != PG_CUSTOM && qAbs(width - ps.width()) < 1.0 && qAbs(height - ps.height()) < 1.0) return static_cast(i); } return PG_CUSTOM; } -QString KgvPageFormat::formatString( KgvFormat format ) +QString KgvPageFormat::formatString(KgvFormat format) { - if ( format <= PG_LAST_FORMAT ) - return QString::fromLatin1( pageFormatInfo[ format ].shortName ); - return QString::fromLatin1( "A4" ); + if (format <= PG_LAST_FORMAT) + return QString::fromLatin1(pageFormatInfo[format].shortName); + return QString::fromLatin1("A4"); } -KgvFormat KgvPageFormat::formatFromString( const QString & string ) +KgvFormat KgvPageFormat::formatFromString(const QString &string) { - for ( int i = 0 ; i <= PG_LAST_FORMAT ; ++i ) - { - if (string == QString::fromLatin1( pageFormatInfo[ i ].shortName )) - return pageFormatInfo[ i ].format; + for (int i = 0; i <= PG_LAST_FORMAT; ++i) { + if (string == QString::fromLatin1(pageFormatInfo[i].shortName)) + return pageFormatInfo[i].format; } // We do not know the format name, so we have a custom format return PG_CUSTOM; } KgvFormat KgvPageFormat::defaultFormat() { const QPageSize::PageSizeId pageSize = QPrinterInfo::defaultPrinter().defaultPageSize().id(); - for ( int i = 0 ; i <= PG_LAST_FORMAT ; ++i ) - { - if ( pageFormatInfo[ i ].pageSize == pageSize ) + for (int i = 0; i <= PG_LAST_FORMAT; ++i) { + if (pageFormatInfo[i].pageSize == pageSize) return static_cast(i); } return PG_DIN_A4; } -QString KgvPageFormat::name( KgvFormat format ) +QString KgvPageFormat::name(KgvFormat format) { - if ( format <= PG_LAST_FORMAT ) - { - if ( pageFormatInfo[ format ].descriptiveName ) - return i18nc( "Page size", pageFormatInfo[ format ].descriptiveName ); + if (format <= PG_LAST_FORMAT) { + if (pageFormatInfo[format].descriptiveName) + return i18nc("Page size", pageFormatInfo[format].descriptiveName); else - return QPageSize::name( pageFormatInfo[ format ].pageSize ); + return QPageSize::name(pageFormatInfo[format].pageSize); } - return QPageSize::name( pageFormatInfo[ PG_DIN_A4 ].pageSize ); + return QPageSize::name(pageFormatInfo[PG_DIN_A4].pageSize); } QStringList KgvPageFormat::allFormats() { QStringList lst; - for ( int i = 0 ; i <= PG_LAST_FORMAT ; ++i ) - { - if ( pageFormatInfo[ i ].descriptiveName ) - lst << i18nc( "Page size", pageFormatInfo[ i ].descriptiveName ); + for (int i = 0; i <= PG_LAST_FORMAT; ++i) { + if (pageFormatInfo[i].descriptiveName) + lst << i18nc("Page size", pageFormatInfo[i].descriptiveName); else - lst << QPageSize::name( pageFormatInfo[ i ].pageSize ); + lst << QPageSize::name(pageFormatInfo[i].pageSize); } return lst; } diff --git a/src/part/KgvPageLayoutColumns.h b/src/part/KgvPageLayoutColumns.h --- a/src/part/KgvPageLayoutColumns.h +++ b/src/part/KgvPageLayoutColumns.h @@ -30,8 +30,8 @@ #ifndef kgvpagelayoutcolumns_h #define kgvpagelayoutcolumns_h -#include #include +#include #include class QWidget; @@ -41,7 +41,8 @@ /** * This class is a widget that shows the KgvColumns data structure and allows the user to change it. */ -class KgvPageLayoutColumns : public QWidget, public Ui::KgvPageLayoutColumnsBase { +class KgvPageLayoutColumns : public QWidget, public Ui::KgvPageLayoutColumnsBase +{ Q_OBJECT public: @@ -52,7 +53,7 @@ * @param unit the unit-type (mm/cm/inch) that the dialog should show * @param layout the page layout that the preview should be initialized with. */ - KgvPageLayoutColumns(QWidget *parent, const KgvColumns& columns, KgvUnit::Unit unit, const KgvPageLayout& layout); + KgvPageLayoutColumns(QWidget *parent, const KgvColumns &columns, KgvUnit::Unit unit, const KgvPageLayout &layout); /** * Update the page preview widget with the param layout. @@ -76,8 +77,8 @@ KgvUnitDoubleSpinBox *m_spacing; private Q_SLOTS: - void nColChanged( int ); - void nSpaceChanged( double ); + void nColChanged(int); + void nSpaceChanged(double); }; #endif diff --git a/src/part/KgvPageLayoutColumns.cpp b/src/part/KgvPageLayoutColumns.cpp --- a/src/part/KgvPageLayoutColumns.cpp +++ b/src/part/KgvPageLayoutColumns.cpp @@ -32,50 +32,53 @@ #include #include -//Added by qt3to4: +// Added by qt3to4: #include -KgvPageLayoutColumns::KgvPageLayoutColumns(QWidget *parent, const KgvColumns& columns, KgvUnit::Unit unit, const KgvPageLayout& layout) - : QWidget(parent), Ui::KgvPageLayoutColumnsBase() +KgvPageLayoutColumns::KgvPageLayoutColumns(QWidget *parent, const KgvColumns &columns, KgvUnit::Unit unit, const KgvPageLayout &layout) + : QWidget(parent) + , Ui::KgvPageLayoutColumnsBase() { m_columns = columns; QHBoxLayout *lay = new QHBoxLayout(previewPane); - m_preview = new KgvPagePreview( previewPane, "Preview", layout ); + m_preview = new KgvPagePreview(previewPane, "Preview", layout); lay->addWidget(m_preview); lay = new QHBoxLayout(columnSpacingPane); - m_spacing = new KgvUnitDoubleSpinBox( columnSpacingPane ); - m_spacing->setValue( m_columns.ptColumnSpacing ); - m_spacing->setUnit( unit ); - double dStep = KgvUnit::fromUserValue( 0.2, unit ); - m_spacing->setMinMaxStep( 0, layout.ptWidth/2, dStep ); + m_spacing = new KgvUnitDoubleSpinBox(columnSpacingPane); + m_spacing->setValue(m_columns.ptColumnSpacing); + m_spacing->setUnit(unit); + double dStep = KgvUnit::fromUserValue(0.2, unit); + m_spacing->setMinMaxStep(0, layout.ptWidth / 2, dStep); lay->addWidget(m_spacing); - labelSpacing->setBuddy( m_spacing ); - nColumns->setValue( m_columns.columns ); - m_preview->setPageColumns( m_columns ); + labelSpacing->setBuddy(m_spacing); + nColumns->setValue(m_columns.columns); + m_preview->setPageColumns(m_columns); - connect(nColumns, static_cast(&QSpinBox::valueChanged), - this, &KgvPageLayoutColumns::nColChanged); - connect(m_spacing, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutColumns::nSpaceChanged); + connect(nColumns, static_cast(&QSpinBox::valueChanged), this, &KgvPageLayoutColumns::nColChanged); + connect(m_spacing, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutColumns::nSpaceChanged); } -void KgvPageLayoutColumns::setEnableColumns(bool on) { +void KgvPageLayoutColumns::setEnableColumns(bool on) +{ nColumns->setEnabled(on); m_spacing->setEnabled(on); - nColChanged(on ? nColumns->value(): 1 ); + nColChanged(on ? nColumns->value() : 1); } -void KgvPageLayoutColumns::nColChanged( int columns ) { +void KgvPageLayoutColumns::nColChanged(int columns) +{ m_columns.columns = columns; - m_preview->setPageColumns( m_columns ); + m_preview->setPageColumns(m_columns); emit propertyChange(m_columns); } -void KgvPageLayoutColumns::nSpaceChanged( double spacing ) { +void KgvPageLayoutColumns::nSpaceChanged(double spacing) +{ m_columns.ptColumnSpacing = spacing; emit propertyChange(m_columns); } -void KgvPageLayoutColumns::setLayout(KgvPageLayout &layout) { - m_preview->setPageLayout( layout ); +void KgvPageLayoutColumns::setLayout(KgvPageLayout &layout) +{ + m_preview->setPageLayout(layout); } diff --git a/src/part/KgvPageLayoutDia.h b/src/part/KgvPageLayoutDia.h --- a/src/part/KgvPageLayoutDia.h +++ b/src/part/KgvPageLayoutDia.h @@ -30,21 +30,20 @@ #ifndef KGVPAGELAYOUTDIA_H #define KGVPAGELAYOUTDIA_H -#include -#include -#include #include +#include +#include #include +#include class KLineEdit; class QPaintEvent; class KgvPageLayoutColumns; class KgvPageLayoutSize; class KgvPageLayoutHeader; -enum { FORMAT_AND_BORDERS = 1, HEADER_AND_FOOTER = 2, COLUMNS = 4, DISABLE_BORDERS = 8, - KW_HEADER_AND_FOOTER = 16, DISABLE_UNIT = 32 }; +enum { FORMAT_AND_BORDERS = 1, HEADER_AND_FOOTER = 2, COLUMNS = 4, DISABLE_BORDERS = 8, KW_HEADER_AND_FOOTER = 16, DISABLE_UNIT = 32 }; /** * KgvPagePreview. @@ -55,26 +54,24 @@ Q_OBJECT public: - /** * constructor */ - KgvPagePreview( QWidget*, const char*, const KgvPageLayout & ); + KgvPagePreview(QWidget *, const char *, const KgvPageLayout &); /** * destructor */ ~KgvPagePreview(); /** * set page layout */ - void setPageLayout( const KgvPageLayout& ); - void setPageColumns( const KgvColumns& ); + void setPageLayout(const KgvPageLayout &); + void setPageColumns(const KgvColumns &); protected: - // paint page - void paintEvent(QPaintEvent* event) override; + void paintEvent(QPaintEvent *event) override; double m_pageHeight, m_pageWidth, m_textFrameX, m_textFrameY, m_textFrameWidth, m_textFrameHeight; int columns; @@ -90,7 +87,6 @@ Q_OBJECT public: - /** * Constructor. * @@ -102,9 +98,7 @@ * @param unit The unit to use for displaying the values to the user. * @param modal Whether the dialog is modal or not. */ - KgvPageLayoutDia( QWidget* parent, - KgvPageLayout& layout, - int flags, KgvUnit::Unit unit); + KgvPageLayoutDia(QWidget *parent, KgvPageLayout &layout, int flags, KgvUnit::Unit unit); /** * Constructor. @@ -118,10 +112,7 @@ * @param tabs The number of tabs. * @param unit The unit to use for displaying the values to the user */ - KgvPageLayoutDia( QWidget* parent, - KgvPageLayout& layout, - const KgvColumns& columns, - int tabs, KgvUnit::Unit unit ); + KgvPageLayoutDia(QWidget *parent, KgvPageLayout &layout, const KgvColumns &columns, int tabs, KgvUnit::Unit unit); /** * Destructor. @@ -132,18 +123,21 @@ * Show page layout dialog. * See constructor for documentation on the parameters */ - static bool pageLayout(KgvPageLayout&, KgvHeadFoot&, int tabs, KgvUnit::Unit& unit, QWidget* parent = nullptr); + static bool pageLayout(KgvPageLayout &, KgvHeadFoot &, int tabs, KgvUnit::Unit &unit, QWidget *parent = nullptr); /** * Show page layout dialog. * See constructor for documentation on the parameters */ - static bool pageLayout(KgvPageLayout&, KgvHeadFoot&, KgvColumns&, KgvKWHeaderFooter&, int tabs, KgvUnit::Unit& unit, QWidget* parent = nullptr); + static bool pageLayout(KgvPageLayout &, KgvHeadFoot &, KgvColumns &, KgvKWHeaderFooter &, int tabs, KgvUnit::Unit &unit, QWidget *parent = nullptr); /** * Returns the layout */ - const KgvPageLayout& layout() const { return m_layout; } + const KgvPageLayout &layout() const + { + return m_layout; + } /** * Returns the header and footer information @@ -153,17 +147,23 @@ /** * Returns the unit */ - KgvUnit::Unit unit() const { return m_unit; } + KgvUnit::Unit unit() const + { + return m_unit; + } private: - const KgvColumns& columns() { return m_column; } - const KgvKWHeaderFooter& headerFooter(); + const KgvColumns &columns() + { + return m_column; + } + const KgvKWHeaderFooter &headerFooter(); // setup tabs - void setupTab1( bool enableBorders ); -// void setupTab2( const KgvHeadFoot& hf ); -// void setupTab3(); -// void setupTab4( const KgvKWHeaderFooter kwhf ); + void setupTab1(bool enableBorders); + // void setupTab2( const KgvHeadFoot& hf ); + // void setupTab3(); + // void setupTab4( const KgvKWHeaderFooter kwhf ); // dialog objects QLineEdit *eHeadLeft; @@ -174,7 +174,7 @@ QLineEdit *eFootRight; // layout - struct ::KgvPageLayout& m_layout; + struct ::KgvPageLayout &m_layout; KgvColumns m_column; KgvUnit::Unit m_unit; @@ -186,7 +186,7 @@ private Q_SLOTS: void sizeUpdated(struct ::KgvPageLayout &layout); -// void columnsUpdated(KgvColumns &columns); + // void columnsUpdated(KgvColumns &columns); private: KgvPageLayoutSize *m_pageSizeTab; diff --git a/src/part/KgvPageLayoutDia.cpp b/src/part/KgvPageLayoutDia.cpp --- a/src/part/KgvPageLayoutDia.cpp +++ b/src/part/KgvPageLayoutDia.cpp @@ -30,176 +30,167 @@ /******************************************************************/ #include "kgraphviewerlib_debug.h" -#include #include #include -#include +#include #include +#include #include #include +#include #include #include -#include +#include #include #include #include #include -#include -//Added by qt3to4: +// Added by qt3to4: #include #include -#include #include +#include /******************************************************************/ /* class KgvPagePreview */ /******************************************************************/ /*===================== constructor ==============================*/ -KgvPagePreview::KgvPagePreview( QWidget* parent, const char *name, const KgvPageLayout& layout ) - : QGroupBox( i18n( "Page Preview" ), parent ) +KgvPagePreview::KgvPagePreview(QWidget *parent, const char *name, const KgvPageLayout &layout) + : QGroupBox(i18n("Page Preview"), parent) { setObjectName(name); - setPageLayout( layout ); + setPageLayout(layout); columns = 1; - setMinimumSize( 150, 150 ); + setMinimumSize(150, 150); } /*====================== destructor ==============================*/ KgvPagePreview::~KgvPagePreview() { } /*=================== set layout =================================*/ -void KgvPagePreview::setPageLayout( const KgvPageLayout &layout ) +void KgvPagePreview::setPageLayout(const KgvPageLayout &layout) { // resolution[XY] is in pixel per pt - double resolutionX = POINT_TO_INCH( static_cast(KgvGlobal::dpiX()) ); - double resolutionY = POINT_TO_INCH( static_cast(KgvGlobal::dpiY()) ); + double resolutionX = POINT_TO_INCH(static_cast(KgvGlobal::dpiX())); + double resolutionY = POINT_TO_INCH(static_cast(KgvGlobal::dpiY())); m_pageWidth = layout.ptWidth * resolutionX; m_pageHeight = layout.ptHeight * resolutionY; double zh = 110.0 / m_pageHeight; double zw = 110.0 / m_pageWidth; - double z = qMin( zw, zh ); + double z = qMin(zw, zh); m_pageWidth *= z; m_pageHeight *= z; m_textFrameX = layout.ptLeft * resolutionX * z; m_textFrameY = layout.ptTop * resolutionY * z; - m_textFrameWidth = m_pageWidth - ( layout.ptLeft + layout.ptRight ) * resolutionX * z; - m_textFrameHeight = m_pageHeight - ( layout.ptTop + layout.ptBottom ) * resolutionY * z; + m_textFrameWidth = m_pageWidth - (layout.ptLeft + layout.ptRight) * resolutionX * z; + m_textFrameHeight = m_pageHeight - (layout.ptTop + layout.ptBottom) * resolutionY * z; qCDebug(KGRAPHVIEWERLIB_LOG) << "repaint in setPageLayout"; repaint(); } /*=================== set layout =================================*/ -void KgvPagePreview::setPageColumns( const KgvColumns &_columns ) +void KgvPagePreview::setPageColumns(const KgvColumns &_columns) { columns = _columns.columns; repaint(); } /*======================== draw contents =========================*/ -void KgvPagePreview::paintEvent ( QPaintEvent * event ) +void KgvPagePreview::paintEvent(QPaintEvent *event) { - QGroupBox::paintEvent(event); - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - double cw = m_textFrameWidth; - if(columns!=1) - { - cw/=static_cast(columns); - } - painter.setBrush( Qt::white ); - painter.setPen( QPen( Qt::black ) ); - - int x=static_cast( ( width() - m_pageWidth ) * 0.5 ); - int y=static_cast( ( height() - m_pageHeight ) * 0.5 ); - int w=static_cast(m_pageWidth); - int h=static_cast(m_pageHeight); - //painter.drawRect( x + 1, y + 1, w, h); - painter.drawRect( x, y, w, h ); - - painter.setBrush( QBrush( Qt::black, Qt::HorPattern ) ); - if ( m_textFrameWidth == m_pageWidth || m_textFrameHeight == m_pageHeight ) - { - painter.setPen( Qt::NoPen ); - } - else - { - painter.setPen( Qt::lightGray ); - } - - for ( int i = 0; i < columns; ++i ) - { - painter.drawRect( x + static_cast(m_textFrameX) + static_cast(i * cw), - y + static_cast(m_textFrameY), static_cast(cw), - static_cast(m_textFrameHeight) ); - } + QGroupBox::paintEvent(event); + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + double cw = m_textFrameWidth; + if (columns != 1) { + cw /= static_cast(columns); + } + painter.setBrush(Qt::white); + painter.setPen(QPen(Qt::black)); + + int x = static_cast((width() - m_pageWidth) * 0.5); + int y = static_cast((height() - m_pageHeight) * 0.5); + int w = static_cast(m_pageWidth); + int h = static_cast(m_pageHeight); + // painter.drawRect( x + 1, y + 1, w, h); + painter.drawRect(x, y, w, h); + + painter.setBrush(QBrush(Qt::black, Qt::HorPattern)); + if (m_textFrameWidth == m_pageWidth || m_textFrameHeight == m_pageHeight) { + painter.setPen(Qt::NoPen); + } else { + painter.setPen(Qt::lightGray); + } + + for (int i = 0; i < columns; ++i) { + painter.drawRect(x + static_cast(m_textFrameX) + static_cast(i * cw), y + static_cast(m_textFrameY), static_cast(cw), static_cast(m_textFrameHeight)); + } } /******************************************************************/ /* class KgvPageLayoutDia */ /******************************************************************/ /*==================== constructor ===============================*/ -KgvPageLayoutDia::KgvPageLayoutDia( QWidget* parent, - KgvPageLayout& layout, - int tabs, - KgvUnit::Unit unit) - : KPageDialog(parent), -/* : KDialogBase( KDialogBase::Tabbed, i18n("Page Layout"), KDialogBase::Ok | KDialogBase::Cancel, - KDialogBase::Ok, parent, name, modal),*/ - m_layout(layout), - m_unit(unit), - flags(tabs), - m_pageSizeTab(nullptr), - m_columnsTab(nullptr), - m_headerTab(nullptr) +KgvPageLayoutDia::KgvPageLayoutDia(QWidget *parent, KgvPageLayout &layout, int tabs, KgvUnit::Unit unit) + : KPageDialog(parent) + , + /* : KDialogBase( KDialogBase::Tabbed, i18n("Page Layout"), KDialogBase::Ok | KDialogBase::Cancel, + KDialogBase::Ok, parent, name, modal),*/ + m_layout(layout) + , m_unit(unit) + , flags(tabs) + , m_pageSizeTab(nullptr) + , m_columnsTab(nullptr) + , m_headerTab(nullptr) { - setStandardButtons( QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply ); + setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply); m_column.columns = 1; - if ( tabs & FORMAT_AND_BORDERS ) setupTab1( true ); -// if ( tabs & HEADER_AND_FOOTER ) setupTab2( hf ); + if (tabs & FORMAT_AND_BORDERS) + setupTab1(true); + // if ( tabs & HEADER_AND_FOOTER ) setupTab2( hf ); - setFocusPolicy( Qt::StrongFocus ); + setFocusPolicy(Qt::StrongFocus); setFocus(); // TODO: make validation query code in slotOk work, or rather port to KWarningMessage } /*==================== constructor ===============================*/ -KgvPageLayoutDia::KgvPageLayoutDia( QWidget* parent, - KgvPageLayout& layout, - const KgvColumns& columns, - int tabs, KgvUnit::Unit unit ) - : KPageDialog( parent ), -/* : KDialogBase( KDialogBase::Tabbed, i18n("Page Layout"), KDialogBase::Ok | KDialogBase::Cancel, - KDialogBase::Ok, parent, name, true),*/ - m_layout(layout), - m_column(columns), - m_unit(unit), - flags(tabs), - m_pageSizeTab(nullptr), - m_columnsTab(nullptr), - m_headerTab(nullptr) +KgvPageLayoutDia::KgvPageLayoutDia(QWidget *parent, KgvPageLayout &layout, const KgvColumns &columns, int tabs, KgvUnit::Unit unit) + : KPageDialog(parent) + , + /* : KDialogBase( KDialogBase::Tabbed, i18n("Page Layout"), KDialogBase::Ok | KDialogBase::Cancel, + KDialogBase::Ok, parent, name, true),*/ + m_layout(layout) + , m_column(columns) + , m_unit(unit) + , flags(tabs) + , m_pageSizeTab(nullptr) + , m_columnsTab(nullptr) + , m_headerTab(nullptr) { - setStandardButtons( QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply ); + setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply); - if ( tabs & FORMAT_AND_BORDERS ) setupTab1( !( tabs & DISABLE_BORDERS ) ); -// if ( tabs & HEADER_AND_FOOTER ) setupTab2( hf ); -// if ( tabs & COLUMNS ) setupTab3(); -// if ( tabs & KW_HEADER_AND_FOOTER ) setupTab4(kwhf); + if (tabs & FORMAT_AND_BORDERS) + setupTab1(!(tabs & DISABLE_BORDERS)); + // if ( tabs & HEADER_AND_FOOTER ) setupTab2( hf ); + // if ( tabs & COLUMNS ) setupTab3(); + // if ( tabs & KW_HEADER_AND_FOOTER ) setupTab4(kwhf); - setFocusPolicy( Qt::StrongFocus ); + setFocusPolicy(Qt::StrongFocus); setFocus(); // TODO: make validation query code in slotOk work, or rather port to KWarningMessage @@ -211,15 +202,17 @@ } /*======================= show dialog ============================*/ -bool KgvPageLayoutDia::pageLayout( KgvPageLayout& layout, KgvHeadFoot& hf, int tabs, KgvUnit::Unit& unit, QWidget* parent ) +bool KgvPageLayoutDia::pageLayout(KgvPageLayout &layout, KgvHeadFoot &hf, int tabs, KgvUnit::Unit &unit, QWidget *parent) { bool res = false; - QPointer dlg = new KgvPageLayoutDia( parent, layout, tabs, unit ); + QPointer dlg = new KgvPageLayoutDia(parent, layout, tabs, unit); - if ( dlg->exec() == QDialog::Accepted ) { + if (dlg->exec() == QDialog::Accepted) { res = true; - if ( tabs & FORMAT_AND_BORDERS ) layout = dlg->layout(); - if ( tabs & HEADER_AND_FOOTER ) hf = dlg->headFoot(); + if (tabs & FORMAT_AND_BORDERS) + layout = dlg->layout(); + if (tabs & HEADER_AND_FOOTER) + hf = dlg->headFoot(); unit = dlg->unit(); } @@ -229,18 +222,21 @@ } /*======================= show dialog ============================*/ -bool KgvPageLayoutDia::pageLayout( KgvPageLayout& layout, KgvHeadFoot& hf, KgvColumns& columns, - KgvKWHeaderFooter &_kwhf, int tabs, KgvUnit::Unit& unit, QWidget* parent ) +bool KgvPageLayoutDia::pageLayout(KgvPageLayout &layout, KgvHeadFoot &hf, KgvColumns &columns, KgvKWHeaderFooter &_kwhf, int tabs, KgvUnit::Unit &unit, QWidget *parent) { bool res = false; - QPointer dlg = new KgvPageLayoutDia( parent, layout, columns, tabs, unit ); + QPointer dlg = new KgvPageLayoutDia(parent, layout, columns, tabs, unit); - if ( dlg->exec() == QDialog::Accepted ) { + if (dlg->exec() == QDialog::Accepted) { res = true; - if ( tabs & FORMAT_AND_BORDERS ) layout = dlg->layout(); - if ( tabs & HEADER_AND_FOOTER ) hf = dlg->headFoot(); - if ( tabs & COLUMNS ) columns = dlg->columns(); - if ( tabs & KW_HEADER_AND_FOOTER ) _kwhf = dlg->headerFooter(); + if (tabs & FORMAT_AND_BORDERS) + layout = dlg->layout(); + if (tabs & HEADER_AND_FOOTER) + hf = dlg->headFoot(); + if (tabs & COLUMNS) + columns = dlg->columns(); + if (tabs & KW_HEADER_AND_FOOTER) + _kwhf = dlg->headerFooter(); unit = dlg->unit(); } @@ -269,115 +265,115 @@ } /*================================================================*/ -const KgvKWHeaderFooter& KgvPageLayoutDia::headerFooter() +const KgvKWHeaderFooter &KgvPageLayoutDia::headerFooter() { return m_headerTab->headerFooter(); } /*================ setup page size & margins tab ==================*/ -void KgvPageLayoutDia::setupTab1( bool enableBorders ) +void KgvPageLayoutDia::setupTab1(bool enableBorders) { - m_pageSizeTab = new KgvPageLayoutSize(nullptr, m_layout, m_unit, m_column, !(flags & DISABLE_UNIT), enableBorders ); - addPage(m_pageSizeTab, i18n( "Page Size & Margins" )); - connect(m_pageSizeTab, &KgvPageLayoutSize::propertyChange, - this, &KgvPageLayoutDia::sizeUpdated); + m_pageSizeTab = new KgvPageLayoutSize(nullptr, m_layout, m_unit, m_column, !(flags & DISABLE_UNIT), enableBorders); + addPage(m_pageSizeTab, i18n("Page Size & Margins")); + connect(m_pageSizeTab, &KgvPageLayoutSize::propertyChange, this, &KgvPageLayoutDia::sizeUpdated); } -void KgvPageLayoutDia::sizeUpdated(KgvPageLayout &layout) { +void KgvPageLayoutDia::sizeUpdated(KgvPageLayout &layout) +{ m_layout.ptWidth = layout.ptWidth; m_layout.ptHeight = layout.ptHeight; m_layout.ptLeft = layout.ptLeft; m_layout.ptRight = layout.ptRight; m_layout.ptTop = layout.ptTop; m_layout.ptBottom = layout.ptBottom; m_layout.format = layout.format; m_layout.orientation = layout.orientation; - if(m_columnsTab) + if (m_columnsTab) m_columnsTab->setLayout(layout); } // /*================ setup header and footer tab ===================*/ // void KgvPageLayoutDia::setupTab2( const KgvHeadFoot& hf ) // { // QWidget *tab2 = addPage(i18n( "H&eader && Footer" )); // QGridLayout *grid2 = new QGridLayout( tab2, 7, 2, 0, KDialog::spacingHint() ); -// +// // // ------------- header --------------- // QGroupBox *gHead = new QGroupBox( 0, Qt::Vertical, i18n( "Head Line" ), tab2 ); // gHead->layout()->setSpacing(KDialog::spacingHint()); // gHead->layout()->setMargin(KDialog::marginHint()); // QGridLayout *headGrid = new QGridLayout( gHead->layout(), 2, 3 ); -// +// // QLabel *lHeadLeft = new QLabel( i18n( "Left:" ), gHead ); // headGrid->addWidget( lHeadLeft, 0, 0 ); -// +// // eHeadLeft = new KLineEdit( gHead ); // headGrid->addWidget( eHeadLeft, 1, 0 ); // eHeadLeft->setText( hf.headLeft ); -// +// // QLabel *lHeadMid = new QLabel( i18n( "Mid:" ), gHead ); // headGrid->addWidget( lHeadMid, 0, 1 ); -// +// // eHeadMid = new KLineEdit( gHead ); // headGrid->addWidget( eHeadMid, 1, 1 ); // eHeadMid->setText( hf.headMid ); -// +// // QLabel *lHeadRight = new QLabel( i18n( "Right:" ), gHead ); // headGrid->addWidget( lHeadRight, 0, 2 ); -// +// // eHeadRight = new KLineEdit( gHead ); // headGrid->addWidget( eHeadRight, 1, 2 ); // eHeadRight->setText( hf.headRight ); -// +// // grid2->addMultiCellWidget( gHead, 0, 1, 0, 1 ); -// +// // // ------------- footer --------------- // QGroupBox *gFoot = new QGroupBox( 0, Qt::Vertical, i18n( "Foot Line" ), tab2 ); // gFoot->layout()->setSpacing(KDialog::spacingHint()); // gFoot->layout()->setMargin(KDialog::marginHint()); // QGridLayout *footGrid = new QGridLayout( gFoot->layout(), 2, 3 ); -// +// // QLabel *lFootLeft = new QLabel( i18n( "Left:" ), gFoot ); // footGrid->addWidget( lFootLeft, 0, 0 ); -// +// // eFootLeft = new KLineEdit( gFoot ); // footGrid->addWidget( eFootLeft, 1, 0 ); // eFootLeft->setText( hf.footLeft ); -// +// // QLabel *lFootMid = new QLabel( i18n( "Mid:" ), gFoot ); // footGrid->addWidget( lFootMid, 0, 1 ); -// +// // eFootMid = new KLineEdit( gFoot ); // footGrid->addWidget( eFootMid, 1, 1 ); // eFootMid->setText( hf.footMid ); -// +// // QLabel *lFootRight = new QLabel( i18n( "Right:" ), gFoot ); // footGrid->addWidget( lFootRight, 0, 2 ); -// +// // eFootRight = new KLineEdit( gFoot ); // footGrid->addWidget( eFootRight, 1, 2 ); // eFootRight->setText( hf.footRight ); -// +// // grid2->addMultiCellWidget( gFoot, 2, 3, 0, 1 ); -// +// // QLabel *lMacros2 = new QLabel( i18n( "You can insert several tags in the text:" ), tab2 ); // grid2->addMultiCellWidget( lMacros2, 4, 4, 0, 1 ); -// +// // QLabel *lMacros3 = new QLabel( i18n("
  • <sheet> The sheet name
  • " // "
  • <page> The current page
  • " // "
  • <pages> The total number of pages
  • " // "
  • <name> The filename or URL
  • " // "
  • <file> The filename with complete path or the URL
"), tab2 ); // grid2->addMultiCellWidget( lMacros3, 5, 6, 0, 0, Qt::AlignTop ); -// +// // QLabel *lMacros4 = new QLabel( i18n("
  • <time> The current time
  • " // "
  • <date> The current date
  • " // "
  • <author> Your full name
  • " // "
  • <org> Your organization
  • " // "
  • <email> Your email address
"), tab2 ); // grid2->addMultiCellWidget( lMacros4, 5, 6, 1, 1, Qt::AlignTop ); // } -// +// // /*================================================================*/ // void KgvPageLayoutDia::setupTab3() // { @@ -390,14 +386,14 @@ // connect (m_columnsTab, SIGNAL(propertyChange(KgvColumns&)), // this, SLOT(columnsUpdated(KgvColumns&))); // } -// +// // void KgvPageLayoutDia::columnsUpdated(KgvColumns &columns) { // m_column.columns = columns.columns; // m_column.ptColumnSpacing = columns.ptColumnSpacing; // if(m_pageSizeTab) // m_pageSizeTab->setColumns(columns); // } -// +// // /*================================================================*/ // void KgvPageLayoutDia::setupTab4(const KgvKWHeaderFooter kwhf ) // { @@ -407,16 +403,16 @@ // m_headerTab->layout()->setMargin(0); // lay->addWidget(m_headerTab); // m_headerTab->show(); -// +// // } -// +// /* Validation when closing. Error messages are never liked, but better let the users enter all values in any order, and have one final validation, than preventing them from entering values. */ void KgvPageLayoutDia::slotOk() { - if( m_pageSizeTab ) + if (m_pageSizeTab) m_pageSizeTab->queryClose(); KPageDialog::accept(); // accept } diff --git a/src/part/KgvPageLayoutHeader.h b/src/part/KgvPageLayoutHeader.h --- a/src/part/KgvPageLayoutHeader.h +++ b/src/part/KgvPageLayoutHeader.h @@ -28,17 +28,17 @@ #ifndef kgvpagelayoutheader_h #define kgvpagelayoutheader_h -#include #include +#include #include class QWidget; class KgvUnitDoubleSpinBox; /** * This class is a widget that shows the KgvKWHeaderFooter data structure and allows the user to change it. */ -class KgvPageLayoutHeader : public QWidget, public Ui::KgvPageLayoutHeaderBase +class KgvPageLayoutHeader : public QWidget, public Ui::KgvPageLayoutHeaderBase { Q_OBJECT @@ -53,13 +53,12 @@ /** * @return the altered data as it is currently set by the user. */ - const KgvKWHeaderFooter& headerFooter(); + const KgvKWHeaderFooter &headerFooter(); private: KgvUnitDoubleSpinBox *m_headerSpacing, *m_footerSpacing, *m_footnoteSpacing; KgvKWHeaderFooter m_headerFooters; }; #endif - diff --git a/src/part/KgvPageLayoutHeader.cpp b/src/part/KgvPageLayoutHeader.cpp --- a/src/part/KgvPageLayoutHeader.cpp +++ b/src/part/KgvPageLayoutHeader.cpp @@ -28,55 +28,57 @@ #include #include -#include #include -//Added by qt3to4: +#include +// Added by qt3to4: #include KgvPageLayoutHeader::KgvPageLayoutHeader(QWidget *parent, KgvUnit::Unit unit, const KgvKWHeaderFooter &kwhf) - : QWidget(parent), Ui::KgvPageLayoutHeaderBase() + : QWidget(parent) + , Ui::KgvPageLayoutHeaderBase() { m_headerFooters = kwhf; QHBoxLayout *lay = new QHBoxLayout(headerSpacingPane); - m_headerSpacing = new KgvUnitDoubleSpinBox( headerSpacingPane, 0.0, 999.0, 0.5, kwhf.ptHeaderBodySpacing, unit ); + m_headerSpacing = new KgvUnitDoubleSpinBox(headerSpacingPane, 0.0, 999.0, 0.5, kwhf.ptHeaderBodySpacing, unit); lay->addWidget(m_headerSpacing); lay = new QHBoxLayout(footerSpacingPane); - m_footerSpacing = new KgvUnitDoubleSpinBox( footerSpacingPane, 0.0, 999.0, 0.5, kwhf.ptFooterBodySpacing, unit ); + m_footerSpacing = new KgvUnitDoubleSpinBox(footerSpacingPane, 0.0, 999.0, 0.5, kwhf.ptFooterBodySpacing, unit); lay->addWidget(m_footerSpacing); lay = new QHBoxLayout(footnotePane); - m_footnoteSpacing = new KgvUnitDoubleSpinBox( footnotePane, 0.0, 999.0, 0.5, kwhf.ptFootNoteBodySpacing, unit ); + m_footnoteSpacing = new KgvUnitDoubleSpinBox(footnotePane, 0.0, 999.0, 0.5, kwhf.ptFootNoteBodySpacing, unit); lay->addWidget(m_footnoteSpacing); - if ( kwhf.header == HF_FIRST_DIFF || kwhf.header == HF_FIRST_EO_DIFF ) - rhFirst->setChecked( true ); - if ( kwhf.header == HF_EO_DIFF || kwhf.header == HF_FIRST_EO_DIFF ) - rhEvenOdd->setChecked( true ); - if ( kwhf.footer == HF_FIRST_DIFF || kwhf.footer == HF_FIRST_EO_DIFF ) - rfFirst->setChecked( true ); - if ( kwhf.footer == HF_EO_DIFF || kwhf.footer == HF_FIRST_EO_DIFF ) - rfEvenOdd->setChecked( true ); + if (kwhf.header == HF_FIRST_DIFF || kwhf.header == HF_FIRST_EO_DIFF) + rhFirst->setChecked(true); + if (kwhf.header == HF_EO_DIFF || kwhf.header == HF_FIRST_EO_DIFF) + rhEvenOdd->setChecked(true); + if (kwhf.footer == HF_FIRST_DIFF || kwhf.footer == HF_FIRST_EO_DIFF) + rfFirst->setChecked(true); + if (kwhf.footer == HF_EO_DIFF || kwhf.footer == HF_FIRST_EO_DIFF) + rfEvenOdd->setChecked(true); } -const KgvKWHeaderFooter& KgvPageLayoutHeader::headerFooter() { - if ( rhFirst->isChecked() && rhEvenOdd->isChecked() ) +const KgvKWHeaderFooter &KgvPageLayoutHeader::headerFooter() +{ + if (rhFirst->isChecked() && rhEvenOdd->isChecked()) m_headerFooters.header = HF_FIRST_EO_DIFF; - else if ( rhFirst->isChecked() ) + else if (rhFirst->isChecked()) m_headerFooters.header = HF_FIRST_DIFF; - else if ( rhEvenOdd->isChecked() ) + else if (rhEvenOdd->isChecked()) m_headerFooters.header = HF_EO_DIFF; else m_headerFooters.header = HF_SAME; m_headerFooters.ptHeaderBodySpacing = m_headerSpacing->value(); m_headerFooters.ptFooterBodySpacing = m_footerSpacing->value(); m_headerFooters.ptFootNoteBodySpacing = m_footnoteSpacing->value(); - if ( rfFirst->isChecked() && rfEvenOdd->isChecked() ) + if (rfFirst->isChecked() && rfEvenOdd->isChecked()) m_headerFooters.footer = HF_FIRST_EO_DIFF; - else if ( rfFirst->isChecked() ) + else if (rfFirst->isChecked()) m_headerFooters.footer = HF_FIRST_DIFF; - else if ( rfEvenOdd->isChecked() ) + else if (rfEvenOdd->isChecked()) m_headerFooters.footer = HF_EO_DIFF; else m_headerFooters.footer = HF_SAME; diff --git a/src/part/KgvPageLayoutSize.h b/src/part/KgvPageLayoutSize.h --- a/src/part/KgvPageLayoutSize.h +++ b/src/part/KgvPageLayoutSize.h @@ -28,22 +28,23 @@ #ifndef kgvpagelayoutsize_h #define kgvpagelayoutsize_h -#include #include +#include // #include -#include -#include #include #include +#include #include +#include class KComboBox; class KgvUnitDoubleSpinBox; /** * This class is a widget that shows the KgvPageLayout data structure and allows the user to change it. */ -class KgvPageLayoutSize : public QWidget { +class KgvPageLayoutSize : public QWidget +{ Q_OBJECT public: @@ -56,8 +57,7 @@ * @param unitChooser if true a combobox with the unit-type is shown for the user to change * @param enableBorders if true enable the user to change the margins (aka borders) of the page */ - KgvPageLayoutSize(QWidget *parent, const KgvPageLayout& layout, KgvUnit::Unit unit, - const KgvColumns& columns, bool unitChooser, bool enableBorders); + KgvPageLayoutSize(QWidget *parent, const KgvPageLayout &layout, KgvUnit::Unit unit, const KgvColumns &columns, bool unitChooser, bool enableBorders); /** * @return if the dialog is in a sane state and the values can be used. @@ -74,7 +74,7 @@ * Set a new unit for the widget updating the widgets. * @param unit the new unit */ - void setUnit( KgvUnit::Unit unit ); + void setUnit(KgvUnit::Unit unit); /** * Enable the user to edit the page border size * @param on if true enable the user to change the margins (aka borders) of the page @@ -101,17 +101,17 @@ KgvPagePreview *pgPreview; QGroupBox *m_orientGroup; QButtonGroup m_orientButtons; - + protected Q_SLOTS: - void formatChanged( int ); - void widthChanged( double ); - void heightChanged( double ); - void leftChanged( double ); - void rightChanged( double ); - void topChanged( double ); - void bottomChanged( double ); - void orientationChanged( int ); - void setUnitInt( int unit ); + void formatChanged(int); + void widthChanged(double); + void heightChanged(double); + void leftChanged(double); + void rightChanged(double); + void topChanged(double); + void bottomChanged(double); + void orientationChanged(int); + void setUnitInt(int unit); private: void updatePreview(); diff --git a/src/part/KgvPageLayoutSize.cpp b/src/part/KgvPageLayoutSize.cpp --- a/src/part/KgvPageLayoutSize.cpp +++ b/src/part/KgvPageLayoutSize.cpp @@ -26,381 +26,372 @@ */ #include "kgraphviewerlib_debug.h" -#include #include +#include #include #include +#include #include #include -#include #include #include #include -//Added by qt3to4: -#include +// Added by qt3to4: +#include "klocalizedstring.h" +#include #include +#include #include -#include -#include "klocalizedstring.h" -KgvPageLayoutSize::KgvPageLayoutSize( - QWidget *parent, - const KgvPageLayout& layout, - KgvUnit::Unit unit, - const KgvColumns& columns, - bool unitChooser, - bool enableBorders) - : QWidget(parent), - m_blockSignals(false) +KgvPageLayoutSize::KgvPageLayoutSize(QWidget *parent, const KgvPageLayout &layout, KgvUnit::Unit unit, const KgvColumns &columns, bool unitChooser, bool enableBorders) + : QWidget(parent) + , m_blockSignals(false) { m_layout = layout; m_unit = unit; - QGridLayout *grid1 = new QGridLayout( this ); - if ( unitChooser ) { + QGridLayout *grid1 = new QGridLayout(this); + if (unitChooser) { // ------------- unit _______________ - QWidget* unitFrame = new QWidget( this ); - grid1->addWidget( unitFrame, 0, 0, Qt::AlignLeft ); - QBoxLayout* unitLayout = new QHBoxLayout( unitFrame ); + QWidget *unitFrame = new QWidget(this); + grid1->addWidget(unitFrame, 0, 0, Qt::AlignLeft); + QBoxLayout *unitLayout = new QHBoxLayout(unitFrame); // label unit - QLabel *lpgUnit = new QLabel( i18n( "Unit:" ), unitFrame ); - unitLayout->addWidget( lpgUnit, 0, Qt::AlignRight | Qt::AlignVCenter ); + QLabel *lpgUnit = new QLabel(i18n("Unit:"), unitFrame); + unitLayout->addWidget(lpgUnit, 0, Qt::AlignRight | Qt::AlignVCenter); // combo unit - QComboBox *cpgUnit = new QComboBox( unitFrame ); - lpgUnit->setBuddy( cpgUnit ); - cpgUnit->addItems( KgvUnit::listOfUnitName() ); - cpgUnit->setCurrentIndex( unit ); - unitLayout->addWidget( cpgUnit, 0, Qt::AlignLeft | Qt::AlignVCenter ); - connect(cpgUnit, static_cast(&QComboBox::activated), - this, &KgvPageLayoutSize::setUnitInt); - } - else { - QString str=KgvUnit::unitDescription(unit); - - QLabel *lpgUnit = new QLabel( i18n("All values are given in %1.",str), this ); - grid1->addWidget( lpgUnit, 0, 0, Qt::AlignLeft ); + QComboBox *cpgUnit = new QComboBox(unitFrame); + lpgUnit->setBuddy(cpgUnit); + cpgUnit->addItems(KgvUnit::listOfUnitName()); + cpgUnit->setCurrentIndex(unit); + unitLayout->addWidget(cpgUnit, 0, Qt::AlignLeft | Qt::AlignVCenter); + connect(cpgUnit, static_cast(&QComboBox::activated), this, &KgvPageLayoutSize::setUnitInt); + } else { + QString str = KgvUnit::unitDescription(unit); + + QLabel *lpgUnit = new QLabel(i18n("All values are given in %1.", str), this); + grid1->addWidget(lpgUnit, 0, 0, Qt::AlignLeft); } // -------------- page size ----------------- - QGroupBox* formatFrame = new QGroupBox( i18n( "Page Size" ), this ); - grid1->addWidget( formatFrame, 1, 0 ); + QGroupBox *formatFrame = new QGroupBox(i18n("Page Size"), this); + grid1->addWidget(formatFrame, 1, 0); QVBoxLayout *vlay = new QVBoxLayout; - QWidget *formatPageSize = new QWidget( formatFrame ); + QWidget *formatPageSize = new QWidget(formatFrame); vlay->addWidget(formatPageSize); -// formatPageSize->setSpacing( KDialog::spacingHint() ); + // formatPageSize->setSpacing( KDialog::spacingHint() ); // label page size - QLabel *lpgFormat = new QLabel( i18n( "&Size:" ), formatPageSize ); + QLabel *lpgFormat = new QLabel(i18n("&Size:"), formatPageSize); // combo size - cpgFormat = new QComboBox( formatPageSize ); - cpgFormat->addItems( KgvPageFormat::allFormats() ); - lpgFormat->setBuddy( cpgFormat ); - connect(cpgFormat, static_cast(&QComboBox::activated), - this, &KgvPageLayoutSize::formatChanged); + cpgFormat = new QComboBox(formatPageSize); + cpgFormat->addItems(KgvPageFormat::allFormats()); + lpgFormat->setBuddy(cpgFormat); + connect(cpgFormat, static_cast(&QComboBox::activated), this, &KgvPageLayoutSize::formatChanged); QHBoxLayout *lay = new QHBoxLayout; lay->addWidget(lpgFormat); lay->addWidget(cpgFormat); formatPageSize->setLayout(lay); // spacer -// formatPageSize->setStretchFactor( new QWidget( formatPageSize ), 10 ); + // formatPageSize->setStretchFactor( new QWidget( formatPageSize ), 10 ); QHBoxLayout *lay2 = new QHBoxLayout; - QWidget *formatCustomSize = new QWidget( formatFrame ); + QWidget *formatCustomSize = new QWidget(formatFrame); vlay->addWidget(formatCustomSize); formatFrame->setLayout(vlay); -// formatCustomSize->setSpacing( KDialog::spacingHint() ); + // formatCustomSize->setSpacing( KDialog::spacingHint() ); // label width - QLabel *lpgWidth = new QLabel( i18n( "&Width:" ), formatCustomSize ); + QLabel *lpgWidth = new QLabel(i18n("&Width:"), formatCustomSize); lay2->addWidget(lpgWidth); // linedit width epgWidth = new KgvUnitDoubleSpinBox(formatCustomSize); lay2->addWidget(epgWidth); - lpgWidth->setBuddy( epgWidth ); - if ( m_layout.format != PG_CUSTOM ) - epgWidth->setEnabled( false ); - connect(epgWidth, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::widthChanged); + lpgWidth->setBuddy(epgWidth); + if (m_layout.format != PG_CUSTOM) + epgWidth->setEnabled(false); + connect(epgWidth, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::widthChanged); // label height - QLabel *lpgHeight = new QLabel( i18n( "&Height:" ), formatCustomSize ); + QLabel *lpgHeight = new QLabel(i18n("&Height:"), formatCustomSize); lay2->addWidget(lpgHeight); // linedit height epgHeight = new KgvUnitDoubleSpinBox(formatCustomSize); lay2->addWidget(epgHeight); - lpgHeight->setBuddy( epgHeight ); - if ( m_layout.format != PG_CUSTOM ) - epgHeight->setEnabled( false ); - connect(epgHeight, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::heightChanged); + lpgHeight->setBuddy(epgHeight); + if (m_layout.format != PG_CUSTOM) + epgHeight->setEnabled(false); + connect(epgHeight, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::heightChanged); formatCustomSize->setLayout(lay2); - + // --------------- orientation --------------- QHBoxLayout *lay3 = new QHBoxLayout; - m_orientGroup = new QGroupBox( i18n( "Orientation" ), this ); -// m_orientGroup->setInsideSpacing( KDialog::spacingHint() ); - grid1->addWidget( m_orientGroup, 2, 0 ); + m_orientGroup = new QGroupBox(i18n("Orientation"), this); + // m_orientGroup->setInsideSpacing( KDialog::spacingHint() ); + grid1->addWidget(m_orientGroup, 2, 0); const int iconSize = KIconTheme(KIconTheme::current()).defaultSize(KIconLoader::Small); - QLabel* lbPortrait = new QLabel( m_orientGroup ); - lbPortrait->setPixmap( QPixmap( QIcon::fromTheme( "koPortrait" ).pixmap(iconSize, iconSize) ) ); - lbPortrait->setMaximumWidth( lbPortrait->pixmap()->width() ); + QLabel *lbPortrait = new QLabel(m_orientGroup); + lbPortrait->setPixmap(QPixmap(QIcon::fromTheme("koPortrait").pixmap(iconSize, iconSize))); + lbPortrait->setMaximumWidth(lbPortrait->pixmap()->width()); lay3->addWidget(lbPortrait); - QRadioButton* rbPortrait = new QRadioButton( i18n("&Portrait"), m_orientGroup ); + QRadioButton *rbPortrait = new QRadioButton(i18n("&Portrait"), m_orientGroup); lay3->addWidget(rbPortrait); m_orientButtons.addButton(rbPortrait); - - QLabel* lbLandscape = new QLabel( m_orientGroup ); - lbLandscape->setPixmap( QPixmap( QIcon::fromTheme( "koLandscape" ).pixmap(iconSize, iconSize) ) ); - lbLandscape->setMaximumWidth( lbLandscape->pixmap()->width() ); + + QLabel *lbLandscape = new QLabel(m_orientGroup); + lbLandscape->setPixmap(QPixmap(QIcon::fromTheme("koLandscape").pixmap(iconSize, iconSize))); + lbLandscape->setMaximumWidth(lbLandscape->pixmap()->width()); lay3->addWidget(lbLandscape); - QRadioButton* rbLandscape = new QRadioButton( i18n("La&ndscape"), m_orientGroup ); + QRadioButton *rbLandscape = new QRadioButton(i18n("La&ndscape"), m_orientGroup); lay3->addWidget(rbLandscape); m_orientGroup->setLayout(lay3); m_orientButtons.addButton(rbLandscape); - - connect(&m_orientButtons, static_cast(&QButtonGroup::buttonClicked), - this, &KgvPageLayoutSize::orientationChanged); - + + connect(&m_orientButtons, static_cast(&QButtonGroup::buttonClicked), this, &KgvPageLayoutSize::orientationChanged); + // --------------- page margins --------------- - QGroupBox* marginsFrame = new QGroupBox( i18n( "Margins" ), this ); -// marginsFrame->setColumnLayout( 0, Qt::Vertical ); -// marginsFrame->setMargin( KDialog::marginHint() ); - grid1->addWidget( marginsFrame, 3, 0 ); - - QWidget* marginsWidget = new QWidget(marginsFrame); - QGridLayout *marginsLayout = new QGridLayout( marginsFrame ); + QGroupBox *marginsFrame = new QGroupBox(i18n("Margins"), this); + // marginsFrame->setColumnLayout( 0, Qt::Vertical ); + // marginsFrame->setMargin( KDialog::marginHint() ); + grid1->addWidget(marginsFrame, 3, 0); + + QWidget *marginsWidget = new QWidget(marginsFrame); + QGridLayout *marginsLayout = new QGridLayout(marginsFrame); // left margin ebrLeft = new KgvUnitDoubleSpinBox(marginsWidget); - marginsLayout->addWidget( ebrLeft, 1, 0 ); - connect(ebrLeft, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::leftChanged); + marginsLayout->addWidget(ebrLeft, 1, 0); + connect(ebrLeft, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::leftChanged); // right margin ebrRight = new KgvUnitDoubleSpinBox(marginsWidget); - marginsLayout->addWidget( ebrRight, 1, 2 ); - connect(ebrRight, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::rightChanged); + marginsLayout->addWidget(ebrRight, 1, 2); + connect(ebrRight, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::rightChanged); // top margin ebrTop = new KgvUnitDoubleSpinBox(marginsWidget); - marginsLayout->addWidget( ebrTop, 0, 1 , Qt::AlignCenter ); - connect(ebrTop, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::topChanged); + marginsLayout->addWidget(ebrTop, 0, 1, Qt::AlignCenter); + connect(ebrTop, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::topChanged); // bottom margin ebrBottom = new KgvUnitDoubleSpinBox(marginsWidget); - marginsLayout->addWidget( ebrBottom, 2, 1, Qt::AlignCenter ); - connect(ebrBottom, &KgvUnitDoubleSpinBox::valueChangedPt, - this, &KgvPageLayoutSize::bottomChanged); + marginsLayout->addWidget(ebrBottom, 2, 1, Qt::AlignCenter); + connect(ebrBottom, &KgvUnitDoubleSpinBox::valueChangedPt, this, &KgvPageLayoutSize::bottomChanged); marginsFrame->setLayout(marginsLayout); // ------------- preview ----------- - pgPreview = new KgvPagePreview( this, "Preview", m_layout ); - grid1->addWidget( pgPreview, 1, 1, 3, 1 ); + pgPreview = new KgvPagePreview(this, "Preview", m_layout); + grid1->addWidget(pgPreview, 1, 1, 3, 1); // ------------- spacers ----------- - QWidget* spacer1 = new QWidget( this ); - QWidget* spacer2 = new QWidget( this ); - spacer1->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, - QSizePolicy::Expanding ) ); - spacer2->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, - QSizePolicy::Expanding ) ); - grid1->addWidget( spacer1, 4, 0 ); - grid1->addWidget( spacer2, 4, 1 ); + QWidget *spacer1 = new QWidget(this); + QWidget *spacer2 = new QWidget(this); + spacer1->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + spacer2->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + grid1->addWidget(spacer1, 4, 0); + grid1->addWidget(spacer2, 4, 1); setValues(); updatePreview(); - pgPreview->setPageColumns( columns ); + pgPreview->setPageColumns(columns); setEnableBorders(enableBorders); } -void KgvPageLayoutSize::setEnableBorders(bool on) { +void KgvPageLayoutSize::setEnableBorders(bool on) +{ m_haveBorders = on; - ebrLeft->setEnabled( on ); - ebrRight->setEnabled( on ); - ebrTop->setEnabled( on ); - ebrBottom->setEnabled( on ); + ebrLeft->setEnabled(on); + ebrRight->setEnabled(on); + ebrTop->setEnabled(on); + ebrBottom->setEnabled(on); // update m_layout - m_layout.ptLeft = on?ebrLeft->value():0; - m_layout.ptRight = on?ebrRight->value():0; - m_layout.ptTop = on?ebrTop->value():0; - m_layout.ptBottom = on?ebrBottom->value():0; + m_layout.ptLeft = on ? ebrLeft->value() : 0; + m_layout.ptRight = on ? ebrRight->value() : 0; + m_layout.ptTop = on ? ebrTop->value() : 0; + m_layout.ptBottom = on ? ebrBottom->value() : 0; // use updated m_layout updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::updatePreview() { - pgPreview->setPageLayout( m_layout ); +void KgvPageLayoutSize::updatePreview() +{ + pgPreview->setPageLayout(m_layout); } -void KgvPageLayoutSize::setValues() { +void KgvPageLayoutSize::setValues() +{ // page format - cpgFormat->setCurrentIndex( m_layout.format ); + cpgFormat->setCurrentIndex(m_layout.format); // orientation -// m_orientGroup->setButton( m_layout.orientation == PG_PORTRAIT ? 0: 1 ); + // m_orientGroup->setButton( m_layout.orientation == PG_PORTRAIT ? 0: 1 ); - setUnit( m_unit ); + setUnit(m_unit); updatePreview(); } -void KgvPageLayoutSize::setUnit( KgvUnit::Unit unit ) { +void KgvPageLayoutSize::setUnit(KgvUnit::Unit unit) +{ m_unit = unit; m_blockSignals = true; // due to non-atomic changes the propertyChange emits should be blocked - epgWidth->setUnit( m_unit ); - epgWidth->setMinMaxStep( 0, KgvUnit::fromUserValue( 9999, m_unit ), KgvUnit::fromUserValue( 0.01, m_unit ) ); - epgWidth->changeValue( m_layout.ptWidth ); + epgWidth->setUnit(m_unit); + epgWidth->setMinMaxStep(0, KgvUnit::fromUserValue(9999, m_unit), KgvUnit::fromUserValue(0.01, m_unit)); + epgWidth->changeValue(m_layout.ptWidth); - epgHeight->setUnit( m_unit ); - epgHeight->setMinMaxStep( 0, KgvUnit::fromUserValue( 9999, m_unit ), KgvUnit::fromUserValue( 0.01, m_unit ) ); - epgHeight->changeValue( m_layout.ptHeight ); + epgHeight->setUnit(m_unit); + epgHeight->setMinMaxStep(0, KgvUnit::fromUserValue(9999, m_unit), KgvUnit::fromUserValue(0.01, m_unit)); + epgHeight->changeValue(m_layout.ptHeight); - double dStep = KgvUnit::fromUserValue( 0.2, m_unit ); + double dStep = KgvUnit::fromUserValue(0.2, m_unit); - ebrLeft->setUnit( m_unit ); - ebrLeft->changeValue( m_layout.ptLeft ); - ebrLeft->setMinMaxStep( 0, m_layout.ptWidth, dStep ); + ebrLeft->setUnit(m_unit); + ebrLeft->changeValue(m_layout.ptLeft); + ebrLeft->setMinMaxStep(0, m_layout.ptWidth, dStep); - ebrRight->setUnit( m_unit ); - ebrRight->changeValue( m_layout.ptRight ); - ebrRight->setMinMaxStep( 0, m_layout.ptWidth, dStep ); + ebrRight->setUnit(m_unit); + ebrRight->changeValue(m_layout.ptRight); + ebrRight->setMinMaxStep(0, m_layout.ptWidth, dStep); - ebrTop->setUnit( m_unit ); - ebrTop->changeValue( m_layout.ptTop ); - ebrTop->setMinMaxStep( 0, m_layout.ptHeight, dStep ); + ebrTop->setUnit(m_unit); + ebrTop->changeValue(m_layout.ptTop); + ebrTop->setMinMaxStep(0, m_layout.ptHeight, dStep); - ebrBottom->setUnit( m_unit ); - ebrBottom->changeValue( m_layout.ptBottom ); - ebrBottom->setMinMaxStep( 0, m_layout.ptHeight, dStep ); + ebrBottom->setUnit(m_unit); + ebrBottom->changeValue(m_layout.ptBottom); + ebrBottom->setMinMaxStep(0, m_layout.ptHeight, dStep); m_blockSignals = false; } -void KgvPageLayoutSize::setUnitInt( int unit ) { +void KgvPageLayoutSize::setUnitInt(int unit) +{ setUnit((KgvUnit::Unit)unit); } -void KgvPageLayoutSize::formatChanged( int format ) { - if ( ( KgvFormat )format == m_layout.format ) +void KgvPageLayoutSize::formatChanged(int format) +{ + if ((KgvFormat)format == m_layout.format) return; - m_layout.format = ( KgvFormat )format; - bool enable = (KgvFormat) format == PG_CUSTOM; - epgWidth->setEnabled( enable ); - epgHeight->setEnabled( enable ); - - if ( m_layout.format != PG_CUSTOM ) { - m_layout.ptWidth = MM_TO_POINT( KgvPageFormat::width( - m_layout.format, m_layout.orientation ) ); - m_layout.ptHeight = MM_TO_POINT( KgvPageFormat::height( - m_layout.format, m_layout.orientation ) ); + m_layout.format = (KgvFormat)format; + bool enable = (KgvFormat)format == PG_CUSTOM; + epgWidth->setEnabled(enable); + epgHeight->setEnabled(enable); + + if (m_layout.format != PG_CUSTOM) { + m_layout.ptWidth = MM_TO_POINT(KgvPageFormat::width(m_layout.format, m_layout.orientation)); + m_layout.ptHeight = MM_TO_POINT(KgvPageFormat::height(m_layout.format, m_layout.orientation)); } - epgWidth->changeValue( m_layout.ptWidth ); - epgHeight->changeValue( m_layout.ptHeight ); + epgWidth->changeValue(m_layout.ptWidth); + epgHeight->changeValue(m_layout.ptHeight); - updatePreview( ); + updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::orientationChanged(int which) +void KgvPageLayoutSize::orientationChanged(int which) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "KgvPageLayoutSize::orientationChanged"; - m_layout.orientation = which == 0 ? PG_PORTRAIT : PG_LANDSCAPE; - - // swap dimension - double val = epgWidth->value(); - epgWidth->changeValue(epgHeight->value()); - epgHeight->changeValue(val); - // and adjust margins - m_blockSignals = true; - val = ebrTop->value(); - if(m_layout.orientation == PG_PORTRAIT) - { // clockwise - ebrTop->changeValue(ebrRight->value()); - ebrRight->changeValue(ebrBottom->value()); - ebrBottom->changeValue(ebrLeft->value()); - ebrLeft->changeValue(val); - } - else - { // counter clockwise - ebrTop->changeValue(ebrLeft->value()); - ebrLeft->changeValue(ebrBottom->value()); - ebrBottom->changeValue(ebrRight->value()); - ebrRight->changeValue(val); - } - m_blockSignals = false; - - setEnableBorders(m_haveBorders); // will update preview+emit + qCDebug(KGRAPHVIEWERLIB_LOG) << "KgvPageLayoutSize::orientationChanged"; + m_layout.orientation = which == 0 ? PG_PORTRAIT : PG_LANDSCAPE; + + // swap dimension + double val = epgWidth->value(); + epgWidth->changeValue(epgHeight->value()); + epgHeight->changeValue(val); + // and adjust margins + m_blockSignals = true; + val = ebrTop->value(); + if (m_layout.orientation == PG_PORTRAIT) { // clockwise + ebrTop->changeValue(ebrRight->value()); + ebrRight->changeValue(ebrBottom->value()); + ebrBottom->changeValue(ebrLeft->value()); + ebrLeft->changeValue(val); + } else { // counter clockwise + ebrTop->changeValue(ebrLeft->value()); + ebrLeft->changeValue(ebrBottom->value()); + ebrBottom->changeValue(ebrRight->value()); + ebrRight->changeValue(val); + } + m_blockSignals = false; + + setEnableBorders(m_haveBorders); // will update preview+emit } -void KgvPageLayoutSize::widthChanged(double width) { - if(m_blockSignals) return; +void KgvPageLayoutSize::widthChanged(double width) +{ + if (m_blockSignals) + return; m_layout.ptWidth = width; updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::heightChanged(double height) { - if(m_blockSignals) return; +void KgvPageLayoutSize::heightChanged(double height) +{ + if (m_blockSignals) + return; m_layout.ptHeight = height; - updatePreview( ); + updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::leftChanged( double left ) { - if(m_blockSignals) return; +void KgvPageLayoutSize::leftChanged(double left) +{ + if (m_blockSignals) + return; m_layout.ptLeft = left; updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::rightChanged(double right) { - if(m_blockSignals) return; +void KgvPageLayoutSize::rightChanged(double right) +{ + if (m_blockSignals) + return; m_layout.ptRight = right; updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::topChanged(double top) { - if(m_blockSignals) return; +void KgvPageLayoutSize::topChanged(double top) +{ + if (m_blockSignals) + return; m_layout.ptTop = top; updatePreview(); emit propertyChange(m_layout); } -void KgvPageLayoutSize::bottomChanged(double bottom) { - if(m_blockSignals) return; +void KgvPageLayoutSize::bottomChanged(double bottom) +{ + if (m_blockSignals) + return; m_layout.ptBottom = bottom; updatePreview(); emit propertyChange(m_layout); } -bool KgvPageLayoutSize::queryClose() { - if ( m_layout.ptLeft + m_layout.ptRight > m_layout.ptWidth ) { - QMessageBox::critical( this, - i18n("Page Layout Problem"), - i18n("The page width is smaller than the left and right margins.") - ); +bool KgvPageLayoutSize::queryClose() +{ + if (m_layout.ptLeft + m_layout.ptRight > m_layout.ptWidth) { + QMessageBox::critical(this, i18n("Page Layout Problem"), i18n("The page width is smaller than the left and right margins.")); return false; } - if ( m_layout.ptTop + m_layout.ptBottom > m_layout.ptHeight ) { - QMessageBox::critical( this, - i18n("Page Layout Problem"), - i18n("The page height is smaller than the top and bottom margins.") - ); + if (m_layout.ptTop + m_layout.ptBottom > m_layout.ptHeight) { + QMessageBox::critical(this, i18n("Page Layout Problem"), i18n("The page height is smaller than the top and bottom margins.")); return false; } return true; } -void KgvPageLayoutSize::setColumns(KgvColumns &columns) { +void KgvPageLayoutSize::setColumns(KgvColumns &columns) +{ pgPreview->setPageColumns(columns); } diff --git a/src/part/KgvUnit.h b/src/part/KgvUnit.h --- a/src/part/KgvUnit.h +++ b/src/part/KgvUnit.h @@ -28,9 +28,9 @@ #ifndef KGVUNIT_H #define KGVUNIT_H +#include // for floor #include #include -#include // for floor // 1 inch ^= 72 pt // 1 inch ^= 25.399956 mm (-pedantic ;p) @@ -49,12 +49,12 @@ #define INCH_TO_POINT(inch) ((inch)*72.0) #define MM_TO_INCH(mm) ((mm)*0.039370147) #define INCH_TO_MM(inch) ((inch)*25.399956) -#define POINT_TO_PI(px)((px)*0.083333333) -#define POINT_TO_DD(px)((px)*0.006490083) -#define POINT_TO_CC(px)((px)*0.077880997) -#define PI_TO_POINT(pi)((pi)*12) -#define DD_TO_POINT(dd)((dd)*154.08124) -#define CC_TO_POINT(cc)((cc)*12.840103) +#define POINT_TO_PI(px) ((px)*0.083333333) +#define POINT_TO_DD(px) ((px)*0.006490083) +#define POINT_TO_CC(px) ((px)*0.077880997) +#define PI_TO_POINT(pi) ((pi)*12) +#define DD_TO_POINT(dd) ((dd)*154.08124) +#define CC_TO_POINT(cc) ((cc)*12.840103) /** * %KOffice stores everything in pt (using "double") internally. * When displaying a value to the user, the value is converted to the user's unit @@ -70,107 +70,113 @@ U_INCH = 2, U_CM = 3, U_DM = 4, - U_PI = 5, // pica - U_DD = 6, // didot - U_CC = 7, // cicero + U_PI = 5, // pica + U_DD = 6, // didot + U_CC = 7, // cicero U_LASTUNIT = U_CC // update when adding a new unit // when adding a new unit, make sure to implement support for it in koRuler too }; /// Prepare ptValue to be displayed in pt - static double toPoint( double ptValue ) { + static double toPoint(double ptValue) + { // No conversion, only rounding (to 0.001 precision) - return floor( ptValue * 1000.0 ) / 1000.0; + return floor(ptValue * 1000.0) / 1000.0; } /// Prepare ptValue to be displayed in mm - static double toMM( double ptValue ) { + static double toMM(double ptValue) + { // "mm" values are rounded to 0.0001 millimeters - return floor( POINT_TO_MM( ptValue ) * 10000.0 ) / 10000.0; + return floor(POINT_TO_MM(ptValue) * 10000.0) / 10000.0; } /// Prepare ptValue to be displayed in cm - static double toCM( double ptValue ) { - return floor( POINT_TO_CM( ptValue ) * 10000.0 ) / 10000.0; + static double toCM(double ptValue) + { + return floor(POINT_TO_CM(ptValue) * 10000.0) / 10000.0; } /// Prepare ptValue to be displayed in dm - static double toDM( double ptValue ) { - return floor( POINT_TO_DM( ptValue ) * 10000.0 ) / 10000.0; + static double toDM(double ptValue) + { + return floor(POINT_TO_DM(ptValue) * 10000.0) / 10000.0; } /// Prepare ptValue to be displayed in inch - static double toInch( double ptValue ) { + static double toInch(double ptValue) + { // "in" values are rounded to 0.00001 inches - return floor( POINT_TO_INCH( ptValue ) * 100000.0 ) / 100000.0; + return floor(POINT_TO_INCH(ptValue) * 100000.0) / 100000.0; } /// Prepare ptValue to be displayed in pica - static double toPI( double ptValue ) { + static double toPI(double ptValue) + { // "pi" values are rounded to 0.00001 inches - return floor( POINT_TO_PI( ptValue ) * 100000.0 ) / 100000.0; + return floor(POINT_TO_PI(ptValue) * 100000.0) / 100000.0; } /// Prepare ptValue to be displayed in didot - static double toDD( double ptValue ) { + static double toDD(double ptValue) + { // "dd" values are rounded to 0.00001 inches - return floor( POINT_TO_DD( ptValue ) * 100000.0 ) / 100000.0; + return floor(POINT_TO_DD(ptValue) * 100000.0) / 100000.0; } /// Prepare ptValue to be displayed in cicero - static double toCC( double ptValue ) { + static double toCC(double ptValue) + { // "cc" values are rounded to 0.00001 inches - return floor( POINT_TO_CC( ptValue ) * 100000.0 ) / 100000.0; + return floor(POINT_TO_CC(ptValue) * 100000.0) / 100000.0; } /** * This method is the one to use to display a value in a dialog * \return the value @p ptValue converted to @p unit and rounded, ready to be displayed * Old name: ptToUnit */ - static double toUserValue( double ptValue, Unit unit ); + static double toUserValue(double ptValue, Unit unit); /** * Convert the value @p ptValue to a given unit @p unit * Unlike KoUnit::ptToUnit the return value remains unrounded, so that it can be used in complex calculation * \return the converted value * Old name: ptToUnitUnrounded */ - static double ptToUnit( const double ptValue, const Unit unit ); + static double ptToUnit(const double ptValue, const Unit unit); /// This method is the one to use to display a value in a dialog /// @return the value @p ptValue converted to @p unit and rounded, ready to be displayed /// Old name: userValue - static QString toUserStringValue( double ptValue, Unit unit ); + static QString toUserStringValue(double ptValue, Unit unit); /// This method is the one to use to read a value from a dialog /// @return the value in @p unit, converted to points for internal use /// Old name: ptFromUnit - static double fromUserValue( double value, Unit unit ); + static double fromUserValue(double value, Unit unit); /// This method is the one to use to read a value from a dialog /// @param value value entered by the user /// @param unit unit type selected by the user /// @param ok if set, the pointed bool is set to true if the value could be /// converted to a double, and to false otherwise. /// @return the value in @p unit, converted to points for internal use - static double fromUserValue(const QString& value, Unit unit, bool* ok = nullptr); + static double fromUserValue(const QString &value, Unit unit, bool *ok = nullptr); /// Convert a unit name into a Unit enum /// @param _unitName name to convert /// @param ok if set, it will be true if the unit was known, false if unknown - static Unit unit(const QString &_unitName, bool* ok = nullptr); + static Unit unit(const QString &_unitName, bool *ok = nullptr); /// Get the name of a unit - static QString unitName( Unit _unit ); + static QString unitName(Unit _unit); /// Get the full (translated) description of a unit - static QString unitDescription( Unit _unit ); + static QString unitDescription(Unit _unit); static QStringList listOfUnitName(); /// parse common %KOffice and OO values, like "10cm", "5mm" to pt - static double parseValue( const QString& value, double defaultVal = 0.0 ); + static double parseValue(const QString &value, double defaultVal = 0.0); // Note: the above method doesn't take a const ref, since it modifies the arg. - }; - #endif // KGVUNIT_H diff --git a/src/part/KgvUnit.cpp b/src/part/KgvUnit.cpp --- a/src/part/KgvUnit.cpp +++ b/src/part/KgvUnit.cpp @@ -26,29 +26,27 @@ */ //#include -#include "kgraphviewerlib_debug.h" #include "KgvUnit.h" +#include "kgraphviewerlib_debug.h" +#include #include #include -#include #include QStringList KgvUnit::listOfUnitName() { QStringList lst; - for ( uint i = 0 ; i <= KgvUnit::U_LASTUNIT ; ++i ) - { - KgvUnit::Unit unit = static_cast( i ); - lst.append( KgvUnit::unitDescription( unit ) ); + for (uint i = 0; i <= KgvUnit::U_LASTUNIT; ++i) { + KgvUnit::Unit unit = static_cast(i); + lst.append(KgvUnit::unitDescription(unit)); } return lst; } -QString KgvUnit::unitDescription( Unit _unit ) +QString KgvUnit::unitDescription(Unit _unit) { - switch ( _unit ) - { + switch (_unit) { case KgvUnit::U_MM: return i18n("Millimeters (mm)"); case KgvUnit::U_CM: @@ -64,154 +62,166 @@ case KgvUnit::U_CC: return i18n("Cicero (cc)"); case KgvUnit::U_PT: - return i18n("Points (pt)" ); + return i18n("Points (pt)"); default: return i18n("Error."); } } -double KgvUnit::toUserValue( double ptValue, Unit unit ) +double KgvUnit::toUserValue(double ptValue, Unit unit) { - switch ( unit ) { + switch (unit) { case U_MM: - return toMM( ptValue ); + return toMM(ptValue); case U_CM: - return toCM( ptValue ); + return toCM(ptValue); case U_DM: - return toDM( ptValue ); + return toDM(ptValue); case U_INCH: - return toInch( ptValue ); + return toInch(ptValue); case U_PI: - return toPI( ptValue ); + return toPI(ptValue); case U_DD: - return toDD( ptValue ); + return toDD(ptValue); case U_CC: - return toCC( ptValue ); + return toCC(ptValue); case U_PT: default: - return toPoint( ptValue ); + return toPoint(ptValue); } } -double KgvUnit::ptToUnit( const double ptValue, const Unit unit ) +double KgvUnit::ptToUnit(const double ptValue, const Unit unit) { - switch ( unit ) - { + switch (unit) { case U_MM: - return POINT_TO_MM( ptValue ); + return POINT_TO_MM(ptValue); case U_CM: - return POINT_TO_CM( ptValue ); + return POINT_TO_CM(ptValue); case U_DM: - return POINT_TO_DM( ptValue ); + return POINT_TO_DM(ptValue); case U_INCH: - return POINT_TO_INCH( ptValue ); + return POINT_TO_INCH(ptValue); case U_PI: - return POINT_TO_PI( ptValue ); + return POINT_TO_PI(ptValue); case U_DD: - return POINT_TO_DD( ptValue ); + return POINT_TO_DD(ptValue); case U_CC: - return POINT_TO_CC( ptValue ); + return POINT_TO_CC(ptValue); case U_PT: default: return ptValue; } } -QString KgvUnit::toUserStringValue( double ptValue, Unit unit ) +QString KgvUnit::toUserStringValue(double ptValue, Unit unit) { - return QLocale().toString(toUserValue( ptValue, unit ) ); + return QLocale().toString(toUserValue(ptValue, unit)); } -double KgvUnit::fromUserValue( double value, Unit unit ) +double KgvUnit::fromUserValue(double value, Unit unit) { - switch ( unit ) { + switch (unit) { case U_MM: - return MM_TO_POINT( value ); + return MM_TO_POINT(value); case U_CM: - return CM_TO_POINT( value ); + return CM_TO_POINT(value); case U_DM: - return DM_TO_POINT( value ); + return DM_TO_POINT(value); case U_INCH: - return INCH_TO_POINT( value ); + return INCH_TO_POINT(value); case U_PI: - return PI_TO_POINT( value ); + return PI_TO_POINT(value); case U_DD: - return DD_TO_POINT( value ); + return DD_TO_POINT(value); case U_CC: - return CC_TO_POINT( value ); + return CC_TO_POINT(value); case U_PT: default: return value; } } -double KgvUnit::fromUserValue( const QString& value, Unit unit, bool* ok ) +double KgvUnit::fromUserValue(const QString &value, Unit unit, bool *ok) { - return fromUserValue( QLocale().toDouble(value, ok ), unit ); + return fromUserValue(QLocale().toDouble(value, ok), unit); } -double KgvUnit::parseValue( const QString& sval, double defaultVal ) +double KgvUnit::parseValue(const QString &sval, double defaultVal) { - QString value = sval; - value = value.simplified(); - value.remove( ' ' ); + QString value = sval; + value = value.simplified(); + value.remove(' '); - if( value.isEmpty() ) - return defaultVal; + if (value.isEmpty()) + return defaultVal; - int index = value.indexOf(QRegExp("[a-z]+$")); - if ( index == -1 ) - return value.toDouble(); + int index = value.indexOf(QRegExp("[a-z]+$")); + if (index == -1) + return value.toDouble(); - QString unit = value.mid( index ); - value.truncate ( index ); - double val = value.toDouble(); + QString unit = value.mid(index); + value.truncate(index); + double val = value.toDouble(); - if ( unit == "pt" ) - return val; + if (unit == "pt") + return val; - bool ok; - Unit u = KgvUnit::unit( unit, &ok ); - if( ok ) - return fromUserValue( val, u ); + bool ok; + Unit u = KgvUnit::unit(unit, &ok); + if (ok) + return fromUserValue(val, u); - if( unit == "m" ) - return fromUserValue( val * 10.0, U_DM ); - else if( unit == "km" ) - return fromUserValue( val * 10000.0, U_DM ); - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unit" << unit << "is not supported, please report."; + if (unit == "m") + return fromUserValue(val * 10.0, U_DM); + else if (unit == "km") + return fromUserValue(val * 10000.0, U_DM); + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unit" << unit << "is not supported, please report."; - // TODO : add support for mi/ft ? - return defaultVal; + // TODO : add support for mi/ft ? + return defaultVal; } -KgvUnit::Unit KgvUnit::unit( const QString &_unitName, bool* ok ) +KgvUnit::Unit KgvUnit::unit(const QString &_unitName, bool *ok) { - if ( ok ) + if (ok) *ok = true; - if ( _unitName == QString::fromLatin1( "mm" ) ) return U_MM; - if ( _unitName == QString::fromLatin1( "cm" ) ) return U_CM; - if ( _unitName == QString::fromLatin1( "dm" ) ) return U_DM; - if ( _unitName == QString::fromLatin1( "in" ) - || _unitName == QString::fromLatin1("inch") /*compat*/ ) return U_INCH; - if ( _unitName == QString::fromLatin1( "pi" ) ) return U_PI; - if ( _unitName == QString::fromLatin1( "dd" ) ) return U_DD; - if ( _unitName == QString::fromLatin1( "cc" ) ) return U_CC; - if ( _unitName == QString::fromLatin1( "pt" ) ) return U_PT; - if ( ok ) + if (_unitName == QString::fromLatin1("mm")) + return U_MM; + if (_unitName == QString::fromLatin1("cm")) + return U_CM; + if (_unitName == QString::fromLatin1("dm")) + return U_DM; + if (_unitName == QString::fromLatin1("in") || _unitName == QString::fromLatin1("inch") /*compat*/) + return U_INCH; + if (_unitName == QString::fromLatin1("pi")) + return U_PI; + if (_unitName == QString::fromLatin1("dd")) + return U_DD; + if (_unitName == QString::fromLatin1("cc")) + return U_CC; + if (_unitName == QString::fromLatin1("pt")) + return U_PT; + if (ok) *ok = false; return U_PT; } -QString KgvUnit::unitName( Unit _unit ) +QString KgvUnit::unitName(Unit _unit) { - if ( _unit == U_MM ) return QString::fromLatin1( "mm" ); - if ( _unit == U_CM ) return QString::fromLatin1( "cm" ); - if ( _unit == U_DM ) return QString::fromLatin1( "dm" ); - if ( _unit == U_INCH ) return QString::fromLatin1( "in" ); - if ( _unit == U_PI ) return QString::fromLatin1( "pi" ); - if ( _unit == U_DD ) return QString::fromLatin1( "dd" ); - if ( _unit == U_CC ) return QString::fromLatin1( "cc" ); - return QString::fromLatin1( "pt" ); + if (_unit == U_MM) + return QString::fromLatin1("mm"); + if (_unit == U_CM) + return QString::fromLatin1("cm"); + if (_unit == U_DM) + return QString::fromLatin1("dm"); + if (_unit == U_INCH) + return QString::fromLatin1("in"); + if (_unit == U_PI) + return QString::fromLatin1("pi"); + if (_unit == U_DD) + return QString::fromLatin1("dd"); + if (_unit == U_CC) + return QString::fromLatin1("cc"); + return QString::fromLatin1("pt"); } - diff --git a/src/part/KgvUnitWidgets.h b/src/part/KgvUnitWidgets.h --- a/src/part/KgvUnitWidgets.h +++ b/src/part/KgvUnitWidgets.h @@ -28,18 +28,17 @@ #ifndef KGVUNITWIDGETS_H #define KGVUNITWIDGETS_H -#include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include // ---------------------------------------------------------------- // Support classes - class KgvUnitDoubleBase; // ### TODO: put it out of the public header file (if possible) @@ -53,60 +52,66 @@ public: KgvUnitDoubleValidator(KgvUnitDoubleBase *base, QObject *parent); - QValidator::State validate(QString&, int&) const override; + QValidator::State validate(QString &, int &) const override; private: KgvUnitDoubleBase *m_base; }; - /** * Base for the unit widgets * \since 1.4 (change of behavior) */ class KgvUnitDoubleBase { public: - KgvUnitDoubleBase( KgvUnit::Unit unit, unsigned int precision ) : m_unit( unit ), m_precision( precision ) {} - virtual ~KgvUnitDoubleBase() {} + KgvUnitDoubleBase(KgvUnit::Unit unit, unsigned int precision) + : m_unit(unit) + , m_precision(precision) + { + } + virtual ~KgvUnitDoubleBase() + { + } - virtual void changeValue( double ) = 0; - virtual void setUnit( KgvUnit::Unit = KgvUnit::U_PT ) = 0; + virtual void changeValue(double) = 0; + virtual void setUnit(KgvUnit::Unit = KgvUnit::U_PT) = 0; - void setValueInUnit( double value, KgvUnit::Unit unit ) + void setValueInUnit(double value, KgvUnit::Unit unit) { - changeValue( KgvUnit::ptToUnit( KgvUnit::fromUserValue( value, unit ), m_unit ) ); + changeValue(KgvUnit::ptToUnit(KgvUnit::fromUserValue(value, unit), m_unit)); } - void setPrecision( unsigned int precision ) { m_precision = precision; }; + void setPrecision(unsigned int precision) + { + m_precision = precision; + }; protected: friend class KgvUnitDoubleValidator; /** * Transform the double in a nice text, using locale symbols * @param value the number as double * @return the resulting string */ - QString getVisibleText( double value ) const; + QString getVisibleText(double value) const; /** * Transform a string into a double, while taking care of locale specific symbols. * @param str the string to transform into a number * @param ok true, if the conversion was successful * @return the value as double */ - double toDouble( const QString& str, bool* ok ) const; + double toDouble(const QString &str, bool *ok) const; protected: KgvUnitDoubleValidator *m_validator; KgvUnit::Unit m_unit; unsigned int m_precision; }; - // ---------------------------------------------------------------- // Widget classes - /** * Spin box for double precision numbers with unit display * \since 1.4 (change of behavior) @@ -117,14 +122,13 @@ public: explicit KgvUnitDoubleSpinBox(QWidget *parent = nullptr); // lower, upper, step and value are in pt - KgvUnitDoubleSpinBox( QWidget *parent, double lower, double upper, double step, double value = 0.0, - KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); + KgvUnitDoubleSpinBox(QWidget *parent, double lower, double upper, double step, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); // added so the class can be used in .ui files(by Tymoteusz Majewski, maju7@o2.pl) void changeValue(double) override; void setUnit(KgvUnit::Unit = KgvUnit::U_PT) override; /// @return the current value, converted in points - double value( void ) const; + double value(void) const; /// Set minimum value in points. void setMinValue(double min); @@ -139,12 +143,11 @@ void setLineStepPt(double step); /// Set minimum, maximum value and the step size (all in points) (by Tymoteusz Majewski, maju7@o2.pl) - void setMinMaxStep( double min, double max, double step ); + void setMinMaxStep(double min, double max, double step); Q_SIGNALS: /// emitted like valueChanged in the parent, but this one emits the point value - void valueChangedPt( double ); - + void valueChangedPt(double); private: double m_lowerInPoints; ///< lowest value in points @@ -156,7 +159,6 @@ void privateValueChanged(); }; - /** * Line edit for double precision numbers with unit display * \since 1.4 (change of behavior) @@ -166,16 +168,16 @@ Q_OBJECT public: explicit KgvUnitDoubleLineEdit(QWidget *parent = nullptr); - KgvUnitDoubleLineEdit( QWidget *parent, double lower, double upper, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); + KgvUnitDoubleLineEdit(QWidget *parent, double lower, double upper, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); void changeValue(double) override; void setUnit(KgvUnit::Unit = KgvUnit::U_PT) override; /// @return the current value, converted in points - double value( void ) const; + double value(void) const; protected: - bool eventFilter(QObject* obj, QEvent* ev) override; + bool eventFilter(QObject *obj, QEvent *ev) override; private: double m_value; @@ -194,24 +196,24 @@ Q_OBJECT public: explicit KgvUnitDoubleComboBox(QWidget *parent = nullptr); - KgvUnitDoubleComboBox( QWidget *parent, double lower, double upper, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); + KgvUnitDoubleComboBox(QWidget *parent, double lower, double upper, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); void changeValue(double) override; - void updateValue( double ); + void updateValue(double); void setUnit(KgvUnit::Unit = KgvUnit::U_PT) override; /// @return the current value, converted in points - double value( void ) const; - void insertItem( double, int index = -1 ); + double value(void) const; + void insertItem(double, int index = -1); protected: - bool eventFilter(QObject* obj, QEvent* ev) override; + bool eventFilter(QObject *obj, QEvent *ev) override; Q_SIGNALS: void valueChanged(double); private Q_SLOTS: - void slotActivated( int ); + void slotActivated(int); protected: double m_value; @@ -230,12 +232,12 @@ Q_OBJECT public: explicit KgvUnitDoubleSpinComboBox(QWidget *parent = nullptr); - KgvUnitDoubleSpinComboBox( QWidget *parent, double lower, double upper, double step, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); + KgvUnitDoubleSpinComboBox(QWidget *parent, double lower, double upper, double step, double value = 0.0, KgvUnit::Unit unit = KgvUnit::U_PT, unsigned int precision = 2); - void insertItem( double, int index = -1 ); - void updateValue( double ); + void insertItem(double, int index = -1); + void updateValue(double); /// @return the current value, converted in points - double value( void ) const; + double value(void) const; Q_SIGNALS: void valueChanged(double); @@ -250,4 +252,3 @@ }; #endif // KGVUNITWIDGETS_H - diff --git a/src/part/KgvUnitWidgets.cpp b/src/part/KgvUnitWidgets.cpp --- a/src/part/KgvUnitWidgets.cpp +++ b/src/part/KgvUnitWidgets.cpp @@ -25,260 +25,249 @@ version 2 of the License, or (at your option) any later version. */ -#include "kgraphviewerlib_debug.h" #include "KgvUnitWidgets.h" +#include "kgraphviewerlib_debug.h" #include +#include +#include #include -#include #include -#include -#include +#include // ---------------------------------------------------------------- // Support classes - KgvUnitDoubleValidator::KgvUnitDoubleValidator(KgvUnitDoubleBase *base, QObject *parent) -: QDoubleValidator( parent ), m_base( base ) + : QDoubleValidator(parent) + , m_base(base) { } -QValidator::State -KgvUnitDoubleValidator::validate( QString &s, int &pos ) const +QValidator::State KgvUnitDoubleValidator::validate(QString &s, int &pos) const { - qCDebug(KGRAPHVIEWERLIB_LOG) << "KgvUnitDoubleValidator::validate : " << s << " at " << pos; QValidator::State result = Acceptable; - QRegExp regexp ("([ a-zA-Z]+)$"); // Letters or spaces at end + QRegExp regexp("([ a-zA-Z]+)$"); // Letters or spaces at end const int res = regexp.indexIn(s); - if ( res == -1 ) - { + if (res == -1) { // Nothing like an unit? The user is probably editing the unit qCDebug(KGRAPHVIEWERLIB_LOG) << "Intermediate (no unit)"; return Intermediate; } // ### TODO: are all the QString::trimmed really necessary? - const QString number ( s.left( res ).trimmed() ); - const QString unitName ( regexp.cap( 1 ).trimmed().toLower() ); + const QString number(s.left(res).trimmed()); + const QString unitName(regexp.cap(1).trimmed().toLower()); qCDebug(KGRAPHVIEWERLIB_LOG) << "Split:" << number << ":" << unitName << ":"; bool ok = false; - const double value = m_base->toDouble( number, &ok ); + const double value = m_base->toDouble(number, &ok); double newVal = 0.0; - if( ok ) - { - KgvUnit::Unit unit = KgvUnit::unit( unitName, &ok ); - if ( ok ) - newVal = KgvUnit::fromUserValue( value, unit ); - else - { + if (ok) { + KgvUnit::Unit unit = KgvUnit::unit(unitName, &ok); + if (ok) + newVal = KgvUnit::fromUserValue(value, unit); + else { // Probably the user is trying to edit the unit qCDebug(KGRAPHVIEWERLIB_LOG) << "Intermediate (unknown unit)"; return Intermediate; } - } - else - { + } else { qCWarning(KGRAPHVIEWERLIB_LOG) << "Not a number:" << number; return Invalid; } - newVal = KgvUnit::ptToUnit( newVal, m_base->m_unit ); + newVal = KgvUnit::ptToUnit(newVal, m_base->m_unit); - s = m_base->getVisibleText( newVal ); + s = m_base->getVisibleText(newVal); return result; } - -QString KgvUnitDoubleBase::getVisibleText( double value ) const +QString KgvUnitDoubleBase::getVisibleText(double value) const { - const QString num ( QString( "%1%2").arg( QLocale().toString( value, m_precision ), KgvUnit::unitName( m_unit ) ) ); - qCDebug(KGRAPHVIEWERLIB_LOG) << "getVisibleText: " << QString::number( value, 'f', 12 ) << " => " << num; + const QString num(QString("%1%2").arg(QLocale().toString(value, m_precision), KgvUnit::unitName(m_unit))); + qCDebug(KGRAPHVIEWERLIB_LOG) << "getVisibleText: " << QString::number(value, 'f', 12) << " => " << num; return num; } -double KgvUnitDoubleBase::toDouble( const QString& str, bool* ok ) const +double KgvUnitDoubleBase::toDouble(const QString &str, bool *ok) const { - QString str2( str ); + QString str2(str); /* KLocale::readNumber wants the thousand separator exactly at 1000. But when editing, it might be anywhere. So we need to remove it. */ - const QString sep( QLocale().groupSeparator() ); - if ( !sep.isEmpty() ) - str2.remove( sep ); - str2.remove( KgvUnit::unitName( m_unit ) ); - const double dbl = QLocale().toDouble( str2, ok ); - if ( ok ) - qCDebug(KGRAPHVIEWERLIB_LOG) << "toDouble:" << str << ": => :" << str2 << ": => " << QString::number( dbl, 'f', 12 ); + const QString sep(QLocale().groupSeparator()); + if (!sep.isEmpty()) + str2.remove(sep); + str2.remove(KgvUnit::unitName(m_unit)); + const double dbl = QLocale().toDouble(str2, ok); + if (ok) + qCDebug(KGRAPHVIEWERLIB_LOG) << "toDouble:" << str << ": => :" << str2 << ": => " << QString::number(dbl, 'f', 12); else qCWarning(KGRAPHVIEWERLIB_LOG) << "error:" << str << ": => :" << str2 << ":" << endl; return dbl; } - // ---------------------------------------------------------------- // Widget classes - KgvUnitDoubleSpinBox::KgvUnitDoubleSpinBox(QWidget *parent) - : QDoubleSpinBox( parent ), KgvUnitDoubleBase( KgvUnit::U_PT, 2 ) - , m_lowerInPoints( -9999 ) - , m_upperInPoints( 9999 ) - , m_stepInPoints( 1 ) -{ - QDoubleSpinBox::setDecimals( 2 ); - m_validator = new KgvUnitDoubleValidator( this, this ); -// QSpinBox::setValidator( m_validator ); - //setAcceptLocalizedNumbers( true ); - setUnit( KgvUnit::U_PT ); - - connect(this, static_cast(&KgvUnitDoubleSpinBox::valueChanged), - this, &KgvUnitDoubleSpinBox::privateValueChanged); -} - - -KgvUnitDoubleSpinBox::KgvUnitDoubleSpinBox( QWidget *parent, - double lower, double upper, - double step, - double value, - KgvUnit::Unit unit, - unsigned int precision) - : QDoubleSpinBox( parent), - KgvUnitDoubleBase( unit, precision ), - m_lowerInPoints( lower ), m_upperInPoints( upper ), m_stepInPoints( step ) -{ + : QDoubleSpinBox(parent) + , KgvUnitDoubleBase(KgvUnit::U_PT, 2) + , m_lowerInPoints(-9999) + , m_upperInPoints(9999) + , m_stepInPoints(1) +{ + QDoubleSpinBox::setDecimals(2); + m_validator = new KgvUnitDoubleValidator(this, this); + // QSpinBox::setValidator( m_validator ); + // setAcceptLocalizedNumbers( true ); + setUnit(KgvUnit::U_PT); + + connect(this, static_cast(&KgvUnitDoubleSpinBox::valueChanged), this, &KgvUnitDoubleSpinBox::privateValueChanged); +} + +KgvUnitDoubleSpinBox::KgvUnitDoubleSpinBox(QWidget *parent, double lower, double upper, double step, double value, KgvUnit::Unit unit, unsigned int precision) + : QDoubleSpinBox(parent) + , KgvUnitDoubleBase(unit, precision) + , m_lowerInPoints(lower) + , m_upperInPoints(upper) + , m_stepInPoints(step) +{ setMinimum(lower); setMaximum(upper); setSingleStep(step); setValue(value); setDecimals(precision); - QDoubleSpinBox::setMinimum(lower); - QDoubleSpinBox::setMaximum(upper); - QDoubleSpinBox::setSingleStep(step); - QDoubleSpinBox::setValue(value); + QDoubleSpinBox::setMinimum(lower); + QDoubleSpinBox::setMaximum(upper); + QDoubleSpinBox::setSingleStep(step); + QDoubleSpinBox::setValue(value); m_unit = KgvUnit::U_PT; - m_validator = new KgvUnitDoubleValidator( this, this ); -// QSpinBox::setValidator( m_validator ); - //setAcceptLocalizedNumbers( true ); - setUnit( unit ); - changeValue( value ); - setLineStep( 0.5 ); + m_validator = new KgvUnitDoubleValidator(this, this); + // QSpinBox::setValidator( m_validator ); + // setAcceptLocalizedNumbers( true ); + setUnit(unit); + changeValue(value); + setLineStep(0.5); - connect(this, static_cast(&KgvUnitDoubleSpinBox::valueChanged), - this, &KgvUnitDoubleSpinBox::privateValueChanged); + connect(this, static_cast(&KgvUnitDoubleSpinBox::valueChanged), this, &KgvUnitDoubleSpinBox::privateValueChanged); } -void -KgvUnitDoubleSpinBox::changeValue( double val ) +void KgvUnitDoubleSpinBox::changeValue(double val) { - QDoubleSpinBox::setValue( KgvUnit::toUserValue( val, m_unit ) ); + QDoubleSpinBox::setValue(KgvUnit::toUserValue(val, m_unit)); // TODO: emit valueChanged ONLY if the value was out-of-bounds // This will allow the 'user' dialog to set a dirty bool and ensure // a proper value is getting saved. } -void KgvUnitDoubleSpinBox::privateValueChanged() { - emit valueChangedPt( value () ); +void KgvUnitDoubleSpinBox::privateValueChanged() +{ + emit valueChangedPt(value()); } -void -KgvUnitDoubleSpinBox::setUnit( KgvUnit::Unit unit ) +void KgvUnitDoubleSpinBox::setUnit(KgvUnit::Unit unit) { - double oldvalue = KgvUnit::fromUserValue( QDoubleSpinBox::value(), m_unit ); - QDoubleSpinBox::setMinimum( KgvUnit::toUserValue( m_lowerInPoints, unit ) ); - QDoubleSpinBox::setMaximum( KgvUnit::toUserValue( m_upperInPoints, unit ) ); - QDoubleSpinBox::setSingleStep( KgvUnit::toUserValue( m_stepInPoints, unit ) ); - QDoubleSpinBox::setValue( KgvUnit::ptToUnit( oldvalue, unit ) ); + double oldvalue = KgvUnit::fromUserValue(QDoubleSpinBox::value(), m_unit); + QDoubleSpinBox::setMinimum(KgvUnit::toUserValue(m_lowerInPoints, unit)); + QDoubleSpinBox::setMaximum(KgvUnit::toUserValue(m_upperInPoints, unit)); + QDoubleSpinBox::setSingleStep(KgvUnit::toUserValue(m_stepInPoints, unit)); + QDoubleSpinBox::setValue(KgvUnit::ptToUnit(oldvalue, unit)); m_unit = unit; - setSuffix( KgvUnit::unitName( unit ).prepend( ' ' ) ); + setSuffix(KgvUnit::unitName(unit).prepend(' ')); } -double KgvUnitDoubleSpinBox::value( void ) const +double KgvUnitDoubleSpinBox::value(void) const { - return KgvUnit::fromUserValue( QDoubleSpinBox::value(), m_unit ); + return KgvUnit::fromUserValue(QDoubleSpinBox::value(), m_unit); } -void KgvUnitDoubleSpinBox::setMinValue( double min ) +void KgvUnitDoubleSpinBox::setMinValue(double min) { - m_lowerInPoints = min; - QDoubleSpinBox::setMinimum( KgvUnit::toUserValue( m_lowerInPoints, m_unit ) ); + m_lowerInPoints = min; + QDoubleSpinBox::setMinimum(KgvUnit::toUserValue(m_lowerInPoints, m_unit)); } -void KgvUnitDoubleSpinBox::setMaxValue( double max ) +void KgvUnitDoubleSpinBox::setMaxValue(double max) { - m_upperInPoints = max; - QDoubleSpinBox::setMaximum( KgvUnit::toUserValue( m_upperInPoints, m_unit ) ); + m_upperInPoints = max; + QDoubleSpinBox::setMaximum(KgvUnit::toUserValue(m_upperInPoints, m_unit)); } -void KgvUnitDoubleSpinBox::setLineStep( double step ) +void KgvUnitDoubleSpinBox::setLineStep(double step) { - m_stepInPoints = KgvUnit::toUserValue(step, KgvUnit::U_PT ); - QDoubleSpinBox::setSingleStep( step ); + m_stepInPoints = KgvUnit::toUserValue(step, KgvUnit::U_PT); + QDoubleSpinBox::setSingleStep(step); } -void KgvUnitDoubleSpinBox::setLineStepPt( double step ) +void KgvUnitDoubleSpinBox::setLineStepPt(double step) { - m_stepInPoints = step; - QDoubleSpinBox::setSingleStep( KgvUnit::toUserValue( m_stepInPoints, m_unit ) ); + m_stepInPoints = step; + QDoubleSpinBox::setSingleStep(KgvUnit::toUserValue(m_stepInPoints, m_unit)); } -void KgvUnitDoubleSpinBox::setMinMaxStep( double min, double max, double step ) +void KgvUnitDoubleSpinBox::setMinMaxStep(double min, double max, double step) { - setMinimum( min ); - setMaximum( max ); - setLineStepPt( step ); + setMinimum(min); + setMaximum(max); + setLineStepPt(step); } // ---------------------------------------------------------------- - KgvUnitDoubleLineEdit::KgvUnitDoubleLineEdit(QWidget *parent) - : QLineEdit( parent ), KgvUnitDoubleBase( KgvUnit::U_PT, 2 ), m_value( 0.0 ), m_lower( 0.0 ), m_upper( 9999.99 ), - m_lowerInPoints( 0.0 ), m_upperInPoints( 9999.99 ) + : QLineEdit(parent) + , KgvUnitDoubleBase(KgvUnit::U_PT, 2) + , m_value(0.0) + , m_lower(0.0) + , m_upper(9999.99) + , m_lowerInPoints(0.0) + , m_upperInPoints(9999.99) { - setAlignment( Qt::AlignRight ); - m_validator = new KgvUnitDoubleValidator( this, this ); - setValidator( m_validator ); - setUnit( KgvUnit::U_PT ); - changeValue( KgvUnit::ptToUnit( 0.0, KgvUnit::U_PT ) ); + setAlignment(Qt::AlignRight); + m_validator = new KgvUnitDoubleValidator(this, this); + setValidator(m_validator); + setUnit(KgvUnit::U_PT); + changeValue(KgvUnit::ptToUnit(0.0, KgvUnit::U_PT)); } -KgvUnitDoubleLineEdit::KgvUnitDoubleLineEdit( QWidget *parent, double lower, double upper, double value, KgvUnit::Unit unit, - unsigned int precision) - : QLineEdit( parent ), KgvUnitDoubleBase( unit, precision ), m_value( value ), m_lower( lower ), m_upper( upper ), - m_lowerInPoints( lower ), m_upperInPoints( upper ) +KgvUnitDoubleLineEdit::KgvUnitDoubleLineEdit(QWidget *parent, double lower, double upper, double value, KgvUnit::Unit unit, unsigned int precision) + : QLineEdit(parent) + , KgvUnitDoubleBase(unit, precision) + , m_value(value) + , m_lower(lower) + , m_upper(upper) + , m_lowerInPoints(lower) + , m_upperInPoints(upper) { - setAlignment( Qt::AlignRight ); - m_validator = new KgvUnitDoubleValidator( this, this ); - setValidator( m_validator ); - setUnit( unit ); - changeValue( KgvUnit::ptToUnit( value, unit ) ); + setAlignment(Qt::AlignRight); + m_validator = new KgvUnitDoubleValidator(this, this); + setValidator(m_validator); + setUnit(unit); + changeValue(KgvUnit::ptToUnit(value, unit)); } -void -KgvUnitDoubleLineEdit::changeValue( double value ) +void KgvUnitDoubleLineEdit::changeValue(double value) { - m_value = value < m_lower ? m_lower : ( value > m_upper ? m_upper : value ); - setText( getVisibleText( m_value ) ); + m_value = value < m_lower ? m_lower : (value > m_upper ? m_upper : value); + setText(getVisibleText(m_value)); } -void -KgvUnitDoubleLineEdit::setUnit( KgvUnit::Unit unit ) +void KgvUnitDoubleLineEdit::setUnit(KgvUnit::Unit unit) { KgvUnit::Unit old = m_unit; m_unit = unit; - m_lower = KgvUnit::ptToUnit( m_lowerInPoints, unit ); - m_upper = KgvUnit::ptToUnit( m_upperInPoints, unit ); - changeValue( KgvUnit::ptToUnit( KgvUnit::fromUserValue( m_value, old ), unit ) ); + m_lower = KgvUnit::ptToUnit(m_lowerInPoints, unit); + m_upper = KgvUnit::ptToUnit(m_upperInPoints, unit); + changeValue(KgvUnit::ptToUnit(KgvUnit::fromUserValue(m_value, old), unit)); } -bool -KgvUnitDoubleLineEdit::eventFilter( QObject* o, QEvent* ev ) +bool KgvUnitDoubleLineEdit::eventFilter(QObject *o, QEvent *ev) { #if 0 if( ev->type() == QEvent::FocusOut || ev->type() == QEvent::Leave || ev->type() == QEvent::Hide ) @@ -290,89 +279,89 @@ } else #endif - return QLineEdit::eventFilter( o, ev ); + return QLineEdit::eventFilter(o, ev); } -double KgvUnitDoubleLineEdit::value( void ) const +double KgvUnitDoubleLineEdit::value(void) const { - return KgvUnit::fromUserValue( m_value, m_unit ); + return KgvUnit::fromUserValue(m_value, m_unit); } - // ---------------------------------------------------------------- - KgvUnitDoubleComboBox::KgvUnitDoubleComboBox(QWidget *parent) - : QComboBox( parent ), KgvUnitDoubleBase( KgvUnit::U_PT, 2 ), m_value( 0.0 ), m_lower( 0.0 ), m_upper( 9999.99 ), m_lowerInPoints( 0.0 ), m_upperInPoints( 9999.99 ) -{ - lineEdit()->setAlignment( Qt::AlignRight ); - m_validator = new KgvUnitDoubleValidator( this, this ); - lineEdit()->setValidator( m_validator ); - setUnit( KgvUnit::U_PT ); - changeValue( KgvUnit::ptToUnit( 0.0, KgvUnit::U_PT ) ); - connect(this, static_cast(&KgvUnitDoubleComboBox::activated), - this, &KgvUnitDoubleComboBox::slotActivated); -} - -KgvUnitDoubleComboBox::KgvUnitDoubleComboBox( QWidget *parent, double lower, double upper, double value, KgvUnit::Unit unit, - unsigned int precision) - : QComboBox( parent ), KgvUnitDoubleBase( unit, precision ), m_value( value ), m_lower( lower ), m_upper( upper ), - m_lowerInPoints( lower ), m_upperInPoints( upper ) -{ - lineEdit()->setAlignment( Qt::AlignRight ); - m_validator = new KgvUnitDoubleValidator( this, this ); - lineEdit()->setValidator( m_validator ); - setUnit( unit ); - changeValue( KgvUnit::ptToUnit( value, unit ) ); - connect(this, static_cast(&KgvUnitDoubleComboBox::activated), - this, &KgvUnitDoubleComboBox::slotActivated); -} - -void -KgvUnitDoubleComboBox::changeValue( double value ) + : QComboBox(parent) + , KgvUnitDoubleBase(KgvUnit::U_PT, 2) + , m_value(0.0) + , m_lower(0.0) + , m_upper(9999.99) + , m_lowerInPoints(0.0) + , m_upperInPoints(9999.99) +{ + lineEdit()->setAlignment(Qt::AlignRight); + m_validator = new KgvUnitDoubleValidator(this, this); + lineEdit()->setValidator(m_validator); + setUnit(KgvUnit::U_PT); + changeValue(KgvUnit::ptToUnit(0.0, KgvUnit::U_PT)); + connect(this, static_cast(&KgvUnitDoubleComboBox::activated), this, &KgvUnitDoubleComboBox::slotActivated); +} + +KgvUnitDoubleComboBox::KgvUnitDoubleComboBox(QWidget *parent, double lower, double upper, double value, KgvUnit::Unit unit, unsigned int precision) + : QComboBox(parent) + , KgvUnitDoubleBase(unit, precision) + , m_value(value) + , m_lower(lower) + , m_upper(upper) + , m_lowerInPoints(lower) + , m_upperInPoints(upper) +{ + lineEdit()->setAlignment(Qt::AlignRight); + m_validator = new KgvUnitDoubleValidator(this, this); + lineEdit()->setValidator(m_validator); + setUnit(unit); + changeValue(KgvUnit::ptToUnit(value, unit)); + connect(this, static_cast(&KgvUnitDoubleComboBox::activated), this, &KgvUnitDoubleComboBox::slotActivated); +} + +void KgvUnitDoubleComboBox::changeValue(double value) { QString oldLabel = lineEdit()->text(); - updateValue( value ); - if( lineEdit()->text() != oldLabel ) - emit valueChanged( m_value ); + updateValue(value); + if (lineEdit()->text() != oldLabel) + emit valueChanged(m_value); } -void -KgvUnitDoubleComboBox::updateValue( double value ) +void KgvUnitDoubleComboBox::updateValue(double value) { - m_value = value < m_lower ? m_lower : ( value > m_upper ? m_upper : value ); - lineEdit()->setText( getVisibleText( m_value ) ); + m_value = value < m_lower ? m_lower : (value > m_upper ? m_upper : value); + lineEdit()->setText(getVisibleText(m_value)); } -void -KgvUnitDoubleComboBox::insertItem( double value, int index ) +void KgvUnitDoubleComboBox::insertItem(double value, int index) { - QComboBox::insertItem(index, getVisibleText( value )); + QComboBox::insertItem(index, getVisibleText(value)); } -void -KgvUnitDoubleComboBox::slotActivated( int index ) +void KgvUnitDoubleComboBox::slotActivated(int index) { double oldvalue = m_value; bool ok; - double value = toDouble( itemText( index ), &ok ); - m_value = value < m_lower ? m_lower : ( value > m_upper ? m_upper : value ); - if( m_value != oldvalue ) - emit valueChanged( m_value ); + double value = toDouble(itemText(index), &ok); + m_value = value < m_lower ? m_lower : (value > m_upper ? m_upper : value); + if (m_value != oldvalue) + emit valueChanged(m_value); } -void -KgvUnitDoubleComboBox::setUnit( KgvUnit::Unit unit ) +void KgvUnitDoubleComboBox::setUnit(KgvUnit::Unit unit) { KgvUnit::Unit old = m_unit; m_unit = unit; - m_lower = KgvUnit::ptToUnit( m_lowerInPoints, unit ); - m_upper = KgvUnit::ptToUnit( m_upperInPoints, unit ); - changeValue( KgvUnit::ptToUnit( KgvUnit::fromUserValue( m_value, old ), unit ) ); + m_lower = KgvUnit::ptToUnit(m_lowerInPoints, unit); + m_upper = KgvUnit::ptToUnit(m_upperInPoints, unit); + changeValue(KgvUnit::ptToUnit(KgvUnit::fromUserValue(m_value, old), unit)); } -bool -KgvUnitDoubleComboBox::eventFilter( QObject* o, QEvent* ev ) +bool KgvUnitDoubleComboBox::eventFilter(QObject *o, QEvent *ev) { #if 0 if( ev->type() == QEvent::FocusOut || ev->type() == QEvent::Leave || ev->type() == QEvent::Hide ) @@ -384,97 +373,85 @@ } else #endif - return QComboBox::eventFilter( o, ev ); + return QComboBox::eventFilter(o, ev); } -double KgvUnitDoubleComboBox::value( void ) const +double KgvUnitDoubleComboBox::value(void) const { - return KgvUnit::fromUserValue( m_value, m_unit ); + return KgvUnit::fromUserValue(m_value, m_unit); } - // ---------------------------------------------------------------- - KgvUnitDoubleSpinComboBox::KgvUnitDoubleSpinComboBox(QWidget *parent) - : QWidget( parent ), m_step( 1.0 ) -{ - QGridLayout *layout = new QGridLayout( this ); - //layout->setMargin( 2 ); - QPushButton *up = new QPushButton( "+", this ); - //up->setFlat( true ); - up->setMaximumHeight( 15 ); - up->setMaximumWidth( 15 ); - layout->addWidget( up, 0, 0 ); - connect(up, &QPushButton::clicked, - this, &KgvUnitDoubleSpinComboBox::slotUpClicked); - - QPushButton *down = new QPushButton( "-", this ); - down->setMaximumHeight( 15 ); - down->setMaximumWidth( 15 ); - layout->addWidget( down, 1, 0 ); - connect(down, &QPushButton::clicked, - this, &KgvUnitDoubleSpinComboBox::slotDownClicked); + : QWidget(parent) + , m_step(1.0) +{ + QGridLayout *layout = new QGridLayout(this); + // layout->setMargin( 2 ); + QPushButton *up = new QPushButton("+", this); + // up->setFlat( true ); + up->setMaximumHeight(15); + up->setMaximumWidth(15); + layout->addWidget(up, 0, 0); + connect(up, &QPushButton::clicked, this, &KgvUnitDoubleSpinComboBox::slotUpClicked); + + QPushButton *down = new QPushButton("-", this); + down->setMaximumHeight(15); + down->setMaximumWidth(15); + layout->addWidget(down, 1, 0); + connect(down, &QPushButton::clicked, this, &KgvUnitDoubleSpinComboBox::slotDownClicked); m_combo = new KgvUnitDoubleComboBox(this, KgvUnit::ptToUnit(0.0, KgvUnit::U_PT), KgvUnit::ptToUnit(9999.99, KgvUnit::U_PT), 0.0, KgvUnit::U_PT, 2); - connect(m_combo, &KgvUnitDoubleComboBox::valueChanged, - this, &KgvUnitDoubleSpinComboBox::valueChanged); - layout->addWidget( m_combo, 0, 2, 2, 1 ); -} - -KgvUnitDoubleSpinComboBox::KgvUnitDoubleSpinComboBox( QWidget *parent, double lower, double upper, double step, double value, - KgvUnit::Unit unit, unsigned int precision) - : QWidget( parent ), m_step( step )//, m_lowerInPoints( lower ), m_upperInPoints( upper ) -{ - QGridLayout *layout = new QGridLayout( this ); - //layout->setMargin( 2 ); - QPushButton *up = new QPushButton( "+", this ); - //up->setFlat( true ); - up->setMaximumHeight( 15 ); - up->setMaximumWidth( 15 ); - layout->addWidget( up, 0, 0 ); - connect(up, &QPushButton::clicked, - this, &KgvUnitDoubleSpinComboBox::slotUpClicked); - - QPushButton *down = new QPushButton( "-", this ); - down->setMaximumHeight( 15 ); - down->setMaximumWidth( 15 ); - layout->addWidget( down, 1, 0 ); - connect(down, &QPushButton::clicked, - this, &KgvUnitDoubleSpinComboBox::slotDownClicked); + connect(m_combo, &KgvUnitDoubleComboBox::valueChanged, this, &KgvUnitDoubleSpinComboBox::valueChanged); + layout->addWidget(m_combo, 0, 2, 2, 1); +} + +KgvUnitDoubleSpinComboBox::KgvUnitDoubleSpinComboBox(QWidget *parent, double lower, double upper, double step, double value, KgvUnit::Unit unit, unsigned int precision) + : QWidget(parent) + , m_step(step) //, m_lowerInPoints( lower ), m_upperInPoints( upper ) +{ + QGridLayout *layout = new QGridLayout(this); + // layout->setMargin( 2 ); + QPushButton *up = new QPushButton("+", this); + // up->setFlat( true ); + up->setMaximumHeight(15); + up->setMaximumWidth(15); + layout->addWidget(up, 0, 0); + connect(up, &QPushButton::clicked, this, &KgvUnitDoubleSpinComboBox::slotUpClicked); + + QPushButton *down = new QPushButton("-", this); + down->setMaximumHeight(15); + down->setMaximumWidth(15); + layout->addWidget(down, 1, 0); + connect(down, &QPushButton::clicked, this, &KgvUnitDoubleSpinComboBox::slotDownClicked); m_combo = new KgvUnitDoubleComboBox(this, KgvUnit::ptToUnit(lower, unit), KgvUnit::ptToUnit(upper, unit), value, unit, precision); - connect(m_combo, &KgvUnitDoubleComboBox::valueChanged, - this, &KgvUnitDoubleSpinComboBox::valueChanged); - layout->addWidget( m_combo, 0, 2, 2, 1 ); + connect(m_combo, &KgvUnitDoubleComboBox::valueChanged, this, &KgvUnitDoubleSpinComboBox::valueChanged); + layout->addWidget(m_combo, 0, 2, 2, 1); } -void -KgvUnitDoubleSpinComboBox::slotUpClicked() +void KgvUnitDoubleSpinComboBox::slotUpClicked() { - m_combo->changeValue( m_combo->value() + m_step ); + m_combo->changeValue(m_combo->value() + m_step); } -void -KgvUnitDoubleSpinComboBox::slotDownClicked() +void KgvUnitDoubleSpinComboBox::slotDownClicked() { - m_combo->changeValue( m_combo->value() - m_step ); + m_combo->changeValue(m_combo->value() - m_step); } -void -KgvUnitDoubleSpinComboBox::insertItem( double value, int index ) +void KgvUnitDoubleSpinComboBox::insertItem(double value, int index) { - m_combo->insertItem( value, index ); + m_combo->insertItem(value, index); } -void -KgvUnitDoubleSpinComboBox::updateValue( double value ) +void KgvUnitDoubleSpinComboBox::updateValue(double value) { - m_combo->updateValue( value ); + m_combo->updateValue(value); } -double -KgvUnitDoubleSpinComboBox::value() const +double KgvUnitDoubleSpinComboBox::value() const { return m_combo->value(); } diff --git a/src/part/canvasedge.h b/src/part/canvasedge.h --- a/src/part/canvasedge.h +++ b/src/part/canvasedge.h @@ -24,20 +24,18 @@ License as published by the Free Software Foundation, version 2. */ - #ifndef CANVAS_EDGE_H #define CANVAS_EDGE_H -#include -#include #include -#include -#include #include +#include +#include +#include +#include #include "graphexporter.h" - class QMenu; struct DotRenderOp; @@ -51,68 +49,70 @@ */ namespace KGraphViewer { - class CanvasNode; class CanvasEdge; class GraphEdge; class DotGraphView; class CanvasEdge : public QObject, public QAbstractGraphicsShapeItem { -Q_OBJECT + Q_OBJECT public: - explicit CanvasEdge(DotGraphView* v, GraphEdge*, - qreal scaleX, qreal scaleY, - qreal xMargin, qreal yMargin, qreal gh, - qreal wdhcf, qreal hdvcf, QGraphicsItem* parent = nullptr); + explicit CanvasEdge(DotGraphView *v, GraphEdge *, qreal scaleX, qreal scaleY, qreal xMargin, qreal yMargin, qreal gh, qreal wdhcf, qreal hdvcf, QGraphicsItem *parent = nullptr); + + ~CanvasEdge() override; - ~CanvasEdge() override; - - QRectF boundingRect() const override; + QRectF boundingRect() const override; - QPainterPath shape () const override; + QPainterPath shape() const override; - void paint(QPainter* p, const QStyleOptionGraphicsItem *option, QWidget *widget) override; + void paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget) override; - inline GraphEdge* edge() { return m_edge; } - inline const GraphEdge* edge() const { return m_edge; } + inline GraphEdge *edge() + { + return m_edge; + } + inline const GraphEdge *edge() const + { + return m_edge; + } - inline void setGh(qreal gh) {m_gh = gh;} - - void computeBoundingRect(); + inline void setGh(qreal gh) + { + m_gh = gh; + } + + void computeBoundingRect(); Q_SIGNALS: - void selected(CanvasEdge*, Qt::KeyboardModifiers); - void edgeContextMenuEvent(const QString&, const QPoint&); - void hoverEnter(CanvasEdge*); - void hoverLeave(CanvasEdge*); - + void selected(CanvasEdge *, Qt::KeyboardModifiers); + void edgeContextMenuEvent(const QString &, const QPoint &); + void hoverEnter(CanvasEdge *); + void hoverLeave(CanvasEdge *); + public Q_SLOTS: - void modelChanged(); - void slotRemoveEdge(); + void modelChanged(); + void slotRemoveEdge(); protected: - void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + private: - QPainterPath pathForSpline(int splineNum, const DotRenderOp& dro) const; - qreal distance(const QPointF& point1, const QPointF& point2); - - qreal m_scaleX, m_scaleY; - qreal m_xMargin, m_yMargin, m_gh, m_wdhcf, m_hdvcf; - GraphEdge* m_edge; - QRectF m_boundingRect; - QFont* m_font; - DotGraphView* m_view; - QMenu* m_popup; - mutable QPainterPath m_shape; + QPainterPath pathForSpline(int splineNum, const DotRenderOp &dro) const; + qreal distance(const QPointF &point1, const QPointF &point2); + + qreal m_scaleX, m_scaleY; + qreal m_xMargin, m_yMargin, m_gh, m_wdhcf, m_hdvcf; + GraphEdge *m_edge; + QRectF m_boundingRect; + QFont *m_font; + DotGraphView *m_view; + QMenu *m_popup; + mutable QPainterPath m_shape; }; } #endif - - - diff --git a/src/part/canvasedge.cpp b/src/part/canvasedge.cpp --- a/src/part/canvasedge.cpp +++ b/src/part/canvasedge.cpp @@ -24,21 +24,20 @@ License as published by the Free Software Foundation, version 2. */ - #include "canvasedge.h" -#include "graphedge.h" -#include "graphnode.h" -#include "dotdefaults.h" +#include "FontsCache.h" #include "dot2qtconsts.h" +#include "dotdefaults.h" #include "dotgraphview.h" -#include "FontsCache.h" +#include "graphedge.h" +#include "graphnode.h" #include "kgraphviewerlib_debug.h" #include -#include #include #include +#include #include @@ -50,508 +49,407 @@ namespace KGraphViewer { - -CanvasEdge::CanvasEdge(DotGraphView* view, GraphEdge* e, - qreal scaleX, qreal scaleY, - qreal xMargin, qreal yMargin, qreal gh, - qreal wdhcf, qreal hdvcf, - QGraphicsItem* parent) - : QAbstractGraphicsShapeItem(parent), - m_scaleX(scaleX), m_scaleY(scaleY), - m_xMargin(xMargin), m_yMargin(yMargin), - m_gh(/*gh*/0), m_wdhcf(wdhcf), m_hdvcf(hdvcf), m_edge(e), - m_font(nullptr), m_view(view), m_popup(new QMenu()) +CanvasEdge::CanvasEdge(DotGraphView *view, GraphEdge *e, qreal scaleX, qreal scaleY, qreal xMargin, qreal yMargin, qreal gh, qreal wdhcf, qreal hdvcf, QGraphicsItem *parent) + : QAbstractGraphicsShapeItem(parent) + , m_scaleX(scaleX) + , m_scaleY(scaleY) + , m_xMargin(xMargin) + , m_yMargin(yMargin) + , m_gh(/*gh*/ 0) + , m_wdhcf(wdhcf) + , m_hdvcf(hdvcf) + , m_edge(e) + , m_font(nullptr) + , m_view(view) + , m_popup(new QMenu()) { - Q_UNUSED(gh); - qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << m_gh; - setBoundingRegionGranularity(0.9); - m_font = FontsCache::changeable().fromName(e->fontName()); - - computeBoundingRect(); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "boundingRect computed: " << m_boundingRect; - - QString tipStr = i18n("%1 -> %2\nlabel='%3'", - edge()->fromNode()->id(),edge()->toNode()->id(),e->label()); - setToolTip(tipStr); - - // the message should be given (or possible to be given) by the part user - QAction* removeEdgeAction = new QAction(i18n("Remove selected edge(s)"), this); - m_popup->addAction(removeEdgeAction); - connect(removeEdgeAction, &QAction::triggered, - this, &CanvasEdge::slotRemoveEdge); - - - connect(e, &GraphEdge::changed, - this, &CanvasEdge::modelChanged); - connect(this, &CanvasEdge::selected, - view, &DotGraphView::slotEdgeSelected); - - connect(this, &CanvasEdge::edgeContextMenuEvent, - view, &DotGraphView::slotContextMenuEvent); - - setAcceptHoverEvents ( true ); - - qCDebug(KGRAPHVIEWERLIB_LOG) << "connect slotElementHoverEnter"; - connect(this, &CanvasEdge::hoverEnter, - view, static_cast(&DotGraphView::slotElementHoverEnter)); - connect(this, &CanvasEdge::hoverLeave, - view, static_cast(&DotGraphView::slotElementHoverLeave)); -} + Q_UNUSED(gh); + qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << m_gh; + setBoundingRegionGranularity(0.9); + m_font = FontsCache::changeable().fromName(e->fontName()); + + computeBoundingRect(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "boundingRect computed: " << m_boundingRect; + + QString tipStr = i18n("%1 -> %2\nlabel='%3'", edge()->fromNode()->id(), edge()->toNode()->id(), e->label()); + setToolTip(tipStr); + + // the message should be given (or possible to be given) by the part user + QAction *removeEdgeAction = new QAction(i18n("Remove selected edge(s)"), this); + m_popup->addAction(removeEdgeAction); + connect(removeEdgeAction, &QAction::triggered, this, &CanvasEdge::slotRemoveEdge); + + connect(e, &GraphEdge::changed, this, &CanvasEdge::modelChanged); + connect(this, &CanvasEdge::selected, view, &DotGraphView::slotEdgeSelected); + + connect(this, &CanvasEdge::edgeContextMenuEvent, view, &DotGraphView::slotContextMenuEvent); + + setAcceptHoverEvents(true); + + qCDebug(KGRAPHVIEWERLIB_LOG) << "connect slotElementHoverEnter"; + connect(this, &CanvasEdge::hoverEnter, view, static_cast(&DotGraphView::slotElementHoverEnter)); + connect(this, &CanvasEdge::hoverLeave, view, static_cast(&DotGraphView::slotElementHoverLeave)); +} CanvasEdge::~CanvasEdge() { - delete m_popup; + delete m_popup; } - QRectF CanvasEdge::boundingRect() const { - return m_boundingRect; + return m_boundingRect; } -QPainterPath CanvasEdge::shape () const +QPainterPath CanvasEdge::shape() const { -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id(); - if (!m_shape.isEmpty()) { - return m_shape; - } - - foreach (const DotRenderOp& dro, edge()->renderOperations()) - { - if ( dro.renderop == "B" ) - { - for (int splineNum = 0; splineNum < edge()->colors().count() || (splineNum==0 && edge()->colors().count()==0); splineNum++) - { - m_shape.addPath(pathForSpline(splineNum, dro)); - } + if (!m_shape.isEmpty()) { + return m_shape; + } + + foreach (const DotRenderOp &dro, edge()->renderOperations()) { + if (dro.renderop == "B") { + for (int splineNum = 0; splineNum < edge()->colors().count() || (splineNum == 0 && edge()->colors().count() == 0); splineNum++) { + m_shape.addPath(pathForSpline(splineNum, dro)); + } + } } - } - return m_shape; + return m_shape; } -QPainterPath CanvasEdge::pathForSpline(int splineNum, const DotRenderOp& dro) const +QPainterPath CanvasEdge::pathForSpline(int splineNum, const DotRenderOp &dro) const { - QPolygonF points(dro.integers[0]); - for (int i = 0; i < dro.integers[0]; i++) - { - // computing of diffX and diffY to draw parallel edges - // when asked through the corresponding Graphviz feature - qreal nom = (dro.integers[2*dro.integers[0]]-dro.integers[2]); - qreal denom = (dro.integers[2*dro.integers[0]-1]-dro.integers[1]); - qreal diffX, diffY; - if (nom == 0) - { - diffX = 0; - diffY = 2*(edge()->colors().count()/2 - splineNum); - } - else if (denom ==0) - { - diffX = 2*(edge()->colors().count()/2 - splineNum); - diffY = 0; - } - else - { - double pente = nom/denom; - if (pente < 0) - { - diffX = 2*(edge()->colors().count()/2 - splineNum); - diffY = edge()->colors().count()/2 + splineNum; - } - else - { - diffX = 2*(edge()->colors().count()/2 - splineNum); - diffY = 2*(edge()->colors().count()/2 - splineNum); + QPolygonF points(dro.integers[0]); + for (int i = 0; i < dro.integers[0]; i++) { + // computing of diffX and diffY to draw parallel edges + // when asked through the corresponding Graphviz feature + qreal nom = (dro.integers[2 * dro.integers[0]] - dro.integers[2]); + qreal denom = (dro.integers[2 * dro.integers[0] - 1] - dro.integers[1]); + qreal diffX, diffY; + if (nom == 0) { + diffX = 0; + diffY = 2 * (edge()->colors().count() / 2 - splineNum); + } else if (denom == 0) { + diffX = 2 * (edge()->colors().count() / 2 - splineNum); + diffY = 0; + } else { + double pente = nom / denom; + if (pente < 0) { + diffX = 2 * (edge()->colors().count() / 2 - splineNum); + diffY = edge()->colors().count() / 2 + splineNum; + } else { + diffX = 2 * (edge()->colors().count() / 2 - splineNum); + diffY = 2 * (edge()->colors().count() / 2 - splineNum); + } + } + QPointF p((dro.integers[2 * i + 1] /*%m_wdhcf*/ * m_scaleX) + m_xMargin + diffX, (m_gh - dro.integers[2 * i + 2] /*%m_hdvcf*/) * m_scaleY + m_yMargin + diffY); + points[i] = p; + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << p; } + + QPainterPath path; + path.moveTo(points[0]); + for (int j = 0; j < (points.size() - 1) / 3; j++) { + path.cubicTo(points[3 * j + 1], points[3 * j + 1 + 1], points[3 * j + 2 + 1]); } - QPointF p( - (dro.integers[2*i+1]/*%m_wdhcf*/*m_scaleX) +m_xMargin + diffX, - (m_gh-dro.integers[2*i+2]/*%m_hdvcf*/)*m_scaleY + m_yMargin + diffY - ); - points[i] = p; -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << p; - } - - QPainterPath path; - path.moveTo(points[0]); - for (int j = 0; j < (points.size()-1)/3; j++) - { - path.cubicTo(points[3*j + 1],points[3*j+1 + 1], points[3*j+2 + 1]); - } - return path; + return path; } - -void CanvasEdge::paint(QPainter* p, const QStyleOptionGraphicsItem* option, - QWidget* widget) +void CanvasEdge::paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget) { -// qCDebug(KGRAPHVIEWERLIB_LOG); -Q_UNUSED(option) -Q_UNUSED(widget) - if (m_boundingRect == QRectF()) - { - return; - } - /// computes the scaling of line width - qreal widthScaleFactor = (m_scaleX+m_scaleY)/2; - if (widthScaleFactor < 1) - { - widthScaleFactor = 1; - } - - if (edge()->style()=="invis") - { - return; - } - if (edge()->renderOperations().isEmpty()) - { - if ((edge()->fromNode()->canvasElement()) - && (edge()->toNode()->canvasElement())) - { - p->drawLine( - edge()->fromNode()->canvasElement()->boundingRect().center()+edge()->fromNode()->canvasElement()->pos(), - edge()->toNode()->canvasElement()->boundingRect().center()+edge()->toNode()->canvasElement()->pos()); - } - return; - } - - QColor lineColor = Dot2QtConsts::componentData().qtColor(edge()->color(0)); - QColor backColor; - - QList allPoints; - - const QFont oldFont = p->font(); - const QPen oldPen = p->pen(); - const QBrush oldBrush = p->brush(); - - foreach (const DotRenderOp& dro, edge()->renderOperations()) - { - // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "renderop" << dro.renderop << "; selected:" << edge()->isSelected(); - if (dro.renderop == "c") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); - lineColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; - } - else if (dro.renderop == "C") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); -/* if (m_hovered && m_view->highlighting()) - { - c = c.lighter(); - }*/ - backColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; + // qCDebug(KGRAPHVIEWERLIB_LOG); + Q_UNUSED(option) + Q_UNUSED(widget) + if (m_boundingRect == QRectF()) { + return; } - else if ( dro.renderop == "T" ) - { - const QString& str = dro.str; - - qreal stringWidthGoal = dro.integers[3] * m_scaleX; - int fontSize = edge()->fontSize(); - m_font->setPointSize(fontSize); - QFontMetrics fm(*m_font); - while (fm.width(str) > stringWidthGoal && fontSize > 1) - { - fontSize--; - m_font->setPointSize(fontSize); - fm = QFontMetrics(*m_font); - } - - p->setFont(*m_font); - - p->setPen(Dot2QtConsts::componentData().qtColor(edge()->fontColor())); - - qreal x = (m_scaleX * - ( - (dro.integers[0]) - + (((-dro.integers[2])*(fm.width(dro.str)))/2) - - ( (fm.width(dro.str))/2 ) - ) - ) - + m_xMargin; - qreal y = ((m_gh - (dro.integers[1]))*m_scaleY)+ m_yMargin; - QPointF point(x,y); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawText" << edge()->fontColor() << point; - - p->drawText(point,str); - - p->setFont(oldFont); - p->setPen(oldPen); - } - else if (( dro.renderop == "p" ) || (dro.renderop == "P" )) - { - QPolygonF polygon(dro.integers[0]); - for (int i = 0; i < dro.integers[0]; i++) - { - QPointF point( - (int(dro.integers[2*i+1])/*%m_wdhcf*/)*m_scaleX +m_xMargin, - (int(m_gh-dro.integers[2*i+2])/*%m_hdvcf*/)*m_scaleY + m_yMargin - ); - polygon[i] = point; -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << point; - allPoints.append(point); - } - if (dro.renderop == "P" ) - { - p->setBrush(lineColor); - p->drawPolygon(polygon); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPolygon" << edge()->color(0) << polygon; - p->setBrush(oldBrush); - } - else - { - p->setBrush(Dot2QtConsts::componentData().qtColor("white")); - } - QPen pen(lineColor); - if (edge()->style() == "bold") - { - pen.setStyle(Qt::SolidLine); - pen.setWidth((int)(2 * widthScaleFactor)); - } - else - { - pen.setWidth((int)(1 * widthScaleFactor)); - pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); - } - p->setPen(pen); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPolyline" << edge()->color(0) << polygon; - polygon << polygon[0]; - p->drawPolyline(polygon); - p->setPen(oldPen); - p->setBrush(oldBrush); + /// computes the scaling of line width + qreal widthScaleFactor = (m_scaleX + m_scaleY) / 2; + if (widthScaleFactor < 1) { + widthScaleFactor = 1; } - else if (( dro.renderop == "e" ) || (dro.renderop == "E" )) - { - qreal w = m_scaleX * dro.integers[2] * 2; - qreal h = m_scaleY * dro.integers[3] * 2; - qreal x = (m_xMargin + (dro.integers[0]/*%m_wdhcf*/)*m_scaleX) - w/2; - qreal y = ((m_gh - dro.integers[1]/*%m_hdvcf*/)*m_scaleY + m_yMargin) - h/2; - if (dro.renderop == "E" ) - { - p->setBrush(lineColor); - } - else - { - p->setBrush(Dot2QtConsts::componentData().qtColor("white")); - } - QPen pen(lineColor); - if (edge()->style() == "bold") - { - pen.setStyle(Qt::SolidLine); - pen.setWidth(int(2 * widthScaleFactor)); - } - else - { - pen.setWidth(int(1 * widthScaleFactor)); - pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); - } - p->setPen(pen); - QRectF rect(x,y,w,h); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawEllipse" << edge()->color(0) << rect; - p->drawEllipse(rect); - p->setPen(oldPen); - p->setBrush(oldBrush); + + if (edge()->style() == "invis") { + return; } - else if ( dro.renderop == "B" ) - { - uint lineWidth = 1; - QPen pen; - if (edge()->style() == "bold") - { - pen.setStyle(Qt::SolidLine); - pen.setWidth(int(2 * widthScaleFactor)); - } - else if (edge()->style() != "filled") - { - pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); - } - if (edge()->style().left(12) == "setlinewidth") - { - bool ok; - lineWidth = edge()->style().mid(12, edge()->style().length()-1-12).toInt(&ok); - pen.setWidth(int(lineWidth * widthScaleFactor)); - } - if (edge()->attributes().contains("penwidth")) - { - bool ok; - lineWidth = edge()->attributes()["penwidth"].toInt(&ok); - pen.setWidth(int(lineWidth * widthScaleFactor)); - } - if (edge()->attributes().contains("color")) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "set edge color to " << QColor(edge()->attributes()["color"]).name(); - lineColor = QColor(edge()->attributes()["color"]); - } - for (int splineNum = 0; splineNum < edge()->colors().count() || (splineNum==0 && edge()->colors().count()==0); splineNum++) - { - if (splineNum != 0) - lineColor = Dot2QtConsts::componentData().qtColor(edge()->color(splineNum)); - pen.setColor(lineColor); -// p->setBrush(Dot2QtConsts::componentData().qtColor(edge()->color(0))); - p->setBrush(Qt::NoBrush); - p->setPen(pen); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPath" << edge()->color(splineNum) << points.first() << points.last(); - p->drawPath(pathForSpline(splineNum, dro)); - p->setPen(oldPen); - p->setBrush(oldBrush); - } + if (edge()->renderOperations().isEmpty()) { + if ((edge()->fromNode()->canvasElement()) && (edge()->toNode()->canvasElement())) { + p->drawLine(edge()->fromNode()->canvasElement()->boundingRect().center() + edge()->fromNode()->canvasElement()->pos(), edge()->toNode()->canvasElement()->boundingRect().center() + edge()->toNode()->canvasElement()->pos()); + } + return; } - } - if (edge()->isSelected()) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "draw square"; -// p->drawRect(m_boundingRect); - qreal maxDist = 0; - QPair pointsPair; - foreach(const QPointF& point1, allPoints) - { - foreach(const QPointF& point2, allPoints) - { - if (distance(point1, point2) > maxDist) - { - maxDist = distance(point1, point2); - pointsPair = qMakePair(point1, point2); + + QColor lineColor = Dot2QtConsts::componentData().qtColor(edge()->color(0)); + QColor backColor; + + QList allPoints; + + const QFont oldFont = p->font(); + const QPen oldPen = p->pen(); + const QBrush oldBrush = p->brush(); + + foreach (const DotRenderOp &dro, edge()->renderOperations()) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "renderop" << dro.renderop << "; selected:" << edge()->isSelected(); + if (dro.renderop == "c") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + lineColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; + } else if (dro.renderop == "C") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + /* if (m_hovered && m_view->highlighting()) + { + c = c.lighter(); + }*/ + backColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; + } else if (dro.renderop == "T") { + const QString &str = dro.str; + + qreal stringWidthGoal = dro.integers[3] * m_scaleX; + int fontSize = edge()->fontSize(); + m_font->setPointSize(fontSize); + QFontMetrics fm(*m_font); + while (fm.width(str) > stringWidthGoal && fontSize > 1) { + fontSize--; + m_font->setPointSize(fontSize); + fm = QFontMetrics(*m_font); + } + + p->setFont(*m_font); + + p->setPen(Dot2QtConsts::componentData().qtColor(edge()->fontColor())); + + qreal x = (m_scaleX * ((dro.integers[0]) + (((-dro.integers[2]) * (fm.width(dro.str))) / 2) - ((fm.width(dro.str)) / 2))) + m_xMargin; + qreal y = ((m_gh - (dro.integers[1])) * m_scaleY) + m_yMargin; + QPointF point(x, y); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawText" << edge()->fontColor() << point; + + p->drawText(point, str); + + p->setFont(oldFont); + p->setPen(oldPen); + } else if ((dro.renderop == "p") || (dro.renderop == "P")) { + QPolygonF polygon(dro.integers[0]); + for (int i = 0; i < dro.integers[0]; i++) { + QPointF point((int(dro.integers[2 * i + 1]) /*%m_wdhcf*/) * m_scaleX + m_xMargin, (int(m_gh - dro.integers[2 * i + 2]) /*%m_hdvcf*/) * m_scaleY + m_yMargin); + polygon[i] = point; + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << point; + allPoints.append(point); + } + if (dro.renderop == "P") { + p->setBrush(lineColor); + p->drawPolygon(polygon); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPolygon" << edge()->color(0) << polygon; + p->setBrush(oldBrush); + } else { + p->setBrush(Dot2QtConsts::componentData().qtColor("white")); + } + QPen pen(lineColor); + if (edge()->style() == "bold") { + pen.setStyle(Qt::SolidLine); + pen.setWidth((int)(2 * widthScaleFactor)); + } else { + pen.setWidth((int)(1 * widthScaleFactor)); + pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); + } + p->setPen(pen); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPolyline" << edge()->color(0) << polygon; + polygon << polygon[0]; + p->drawPolyline(polygon); + p->setPen(oldPen); + p->setBrush(oldBrush); + } else if ((dro.renderop == "e") || (dro.renderop == "E")) { + qreal w = m_scaleX * dro.integers[2] * 2; + qreal h = m_scaleY * dro.integers[3] * 2; + qreal x = (m_xMargin + (dro.integers[0] /*%m_wdhcf*/) * m_scaleX) - w / 2; + qreal y = ((m_gh - dro.integers[1] /*%m_hdvcf*/) * m_scaleY + m_yMargin) - h / 2; + if (dro.renderop == "E") { + p->setBrush(lineColor); + } else { + p->setBrush(Dot2QtConsts::componentData().qtColor("white")); + } + QPen pen(lineColor); + if (edge()->style() == "bold") { + pen.setStyle(Qt::SolidLine); + pen.setWidth(int(2 * widthScaleFactor)); + } else { + pen.setWidth(int(1 * widthScaleFactor)); + pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); + } + p->setPen(pen); + QRectF rect(x, y, w, h); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawEllipse" << edge()->color(0) << rect; + p->drawEllipse(rect); + p->setPen(oldPen); + p->setBrush(oldBrush); + } else if (dro.renderop == "B") { + uint lineWidth = 1; + QPen pen; + if (edge()->style() == "bold") { + pen.setStyle(Qt::SolidLine); + pen.setWidth(int(2 * widthScaleFactor)); + } else if (edge()->style() != "filled") { + pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(edge()->style())); + } + if (edge()->style().left(12) == "setlinewidth") { + bool ok; + lineWidth = edge()->style().mid(12, edge()->style().length() - 1 - 12).toInt(&ok); + pen.setWidth(int(lineWidth * widthScaleFactor)); + } + if (edge()->attributes().contains("penwidth")) { + bool ok; + lineWidth = edge()->attributes()["penwidth"].toInt(&ok); + pen.setWidth(int(lineWidth * widthScaleFactor)); + } + if (edge()->attributes().contains("color")) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "set edge color to " << QColor(edge()->attributes()["color"]).name(); + lineColor = QColor(edge()->attributes()["color"]); + } + for (int splineNum = 0; splineNum < edge()->colors().count() || (splineNum == 0 && edge()->colors().count() == 0); splineNum++) { + if (splineNum != 0) + lineColor = Dot2QtConsts::componentData().qtColor(edge()->color(splineNum)); + pen.setColor(lineColor); + // p->setBrush(Dot2QtConsts::componentData().qtColor(edge()->color(0))); + p->setBrush(Qt::NoBrush); + p->setPen(pen); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "drawPath" << edge()->color(splineNum) << points.first() << points.last(); + p->drawPath(pathForSpline(splineNum, dro)); + p->setPen(oldPen); + p->setBrush(oldBrush); + } } - } } - if (maxDist>0) - { - // p->setBrush(Dot2QtConsts::componentData().qtColor(edge()->color(0))); - p->setBrush(Qt::black); - p->setPen(Qt::black); - p->drawRect(QRectF(pointsPair.first-QPointF(3,3),QSizeF(6,6))); - p->drawRect(QRectF(pointsPair.second-QPointF(3,3),QSizeF(6,6))); - p->setBrush(oldBrush); - p->setPen(oldPen); + if (edge()->isSelected()) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "draw square"; + // p->drawRect(m_boundingRect); + qreal maxDist = 0; + QPair pointsPair; + foreach (const QPointF &point1, allPoints) { + foreach (const QPointF &point2, allPoints) { + if (distance(point1, point2) > maxDist) { + maxDist = distance(point1, point2); + pointsPair = qMakePair(point1, point2); + } + } + } + if (maxDist > 0) { + // p->setBrush(Dot2QtConsts::componentData().qtColor(edge()->color(0))); + p->setBrush(Qt::black); + p->setPen(Qt::black); + p->drawRect(QRectF(pointsPair.first - QPointF(3, 3), QSizeF(6, 6))); + p->drawRect(QRectF(pointsPair.second - QPointF(3, 3), QSizeF(6, 6))); + p->setBrush(oldBrush); + p->setPen(oldPen); + } } - } } void CanvasEdge::modelChanged() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id(); - prepareGeometryChange(); - computeBoundingRect(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id(); + prepareGeometryChange(); + computeBoundingRect(); } void CanvasEdge::computeBoundingRect() { -// qCDebug(KGRAPHVIEWERLIB_LOG); - //invalidate bounding region cache - m_shape = QPainterPath(); - if (edge()->renderOperations().isEmpty()) - { - if ((edge()->fromNode()->canvasElement() == nullptr) - || (edge()->toNode()->canvasElement() == nullptr) - || edge()->style()=="invis") - { - m_boundingRect = QRectF(); - } - else - { - QRectF br( - edge()->fromNode()->canvasElement()->boundingRect().center()+edge()->fromNode()->canvasElement()->pos(), - edge()->toNode()->canvasElement()->boundingRect().center()+edge()->toNode()->canvasElement()->pos()); -// qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() <renderOperations()) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << dro.renderop << ", "; - if ( (dro.renderop != "B") && (dro.renderop != "p") && (dro.renderop != "P") ) continue; - uint previousSize = points.size(); - points.resize(previousSize+dro.integers[0]); - for (int i = 0; i < dro.integers[0]; i++) - { - QPointF p( - ((dro.integers[2*i+1]/*%m_wdhcf*/)*m_scaleX) +m_xMargin, - ((m_gh-dro.integers[2*i+2]/*%m_hdvcf*/)*m_scaleY) + m_yMargin - ); - points[previousSize+i] = p; - } - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << points.size() << "points"; - if (points.size() == 0) return; - - int len = points.count(); - QPolygonF a = points, b = points; - a.translate(-1, -1); - b.translate(1, 1); - a.resize(2*len); - for (int i=0;irenderOperations().isEmpty()) { + if ((edge()->fromNode()->canvasElement() == nullptr) || (edge()->toNode()->canvasElement() == nullptr) || edge()->style() == "invis") { + m_boundingRect = QRectF(); + } else { + QRectF br(edge()->fromNode()->canvasElement()->boundingRect().center() + edge()->fromNode()->canvasElement()->pos(), edge()->toNode()->canvasElement()->boundingRect().center() + edge()->toNode()->canvasElement()->pos()); + // qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() <renderOperations()) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << dro.renderop << ", "; + if ((dro.renderop != "B") && (dro.renderop != "p") && (dro.renderop != "P")) + continue; + uint previousSize = points.size(); + points.resize(previousSize + dro.integers[0]); + for (int i = 0; i < dro.integers[0]; i++) { + QPointF p(((dro.integers[2 * i + 1] /*%m_wdhcf*/) * m_scaleX) + m_xMargin, ((m_gh - dro.integers[2 * i + 2] /*%m_hdvcf*/) * m_scaleY) + m_yMargin); + points[previousSize + i] = p; + } + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << points.size() << "points"; + if (points.size() == 0) + return; + + int len = points.count(); + QPolygonF a = points, b = points; + a.translate(-1, -1); + b.translate(1, 1); + a.resize(2 * len); + for (int i = 0; i < len; i++) { + a[len + i] = b[i]; + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << a.size() << "points"; - m_boundingRect = a.boundingRect(); - } - qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "New bounding rect is:" << m_boundingRect; + m_boundingRect = a.boundingRect(); + } + qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->fromNode()->id() << "->" << edge()->toNode()->id() << "New bounding rect is:" << m_boundingRect; } -void CanvasEdge::mousePressEvent(QGraphicsSceneMouseEvent * event) +void CanvasEdge::mousePressEvent(QGraphicsSceneMouseEvent *event) { - qCDebug(KGRAPHVIEWERLIB_LOG) << event; - if (m_view->isReadOnly()) - { - return; - } - if (event->button() == Qt::LeftButton) - { - edge()->setSelected(!edge()->isSelected()); - if (edge()->isSelected()) - { - emit(selected(this,event->modifiers())); + qCDebug(KGRAPHVIEWERLIB_LOG) << event; + if (m_view->isReadOnly()) { + return; } - update(); - } - else if (event->button() == Qt::RightButton) - { - if (!edge()->isSelected()) - { - edge()->setSelected(true); - emit(selected(this,event->modifiers())); - update(); + if (event->button() == Qt::LeftButton) { + edge()->setSelected(!edge()->isSelected()); + if (edge()->isSelected()) { + emit(selected(this, event->modifiers())); + } + update(); + } else if (event->button() == Qt::RightButton) { + if (!edge()->isSelected()) { + edge()->setSelected(true); + emit(selected(this, event->modifiers())); + update(); + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting edgeContextMenuEvent(" << m_edge->id() << "," << event->screenPos() << ")"; + emit(edgeContextMenuEvent(m_edge->id(), event->screenPos())); + // opens the selected edge contextual menu and if necessary select the edge + /* qCDebug(KGRAPHVIEWERLIB_LOG) << "opens the contextual menu"; + m_popup->exec(event->screenPos());*/ } - qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting edgeContextMenuEvent("<id()<<","<screenPos()<<")"; - emit(edgeContextMenuEvent(m_edge->id(), event->screenPos() )); -// opens the selected edge contextual menu and if necessary select the edge -/* qCDebug(KGRAPHVIEWERLIB_LOG) << "opens the contextual menu"; - m_popup->exec(event->screenPos());*/ - } } -qreal CanvasEdge::distance(const QPointF& point1, const QPointF& point2) +qreal CanvasEdge::distance(const QPointF &point1, const QPointF &point2) { - return sqrt(pow(point1.x()-point2.x(),2)+pow(point1.y()-point2.y(),2)); + return sqrt(pow(point1.x() - point2.x(), 2) + pow(point1.y() - point2.y(), 2)); } void CanvasEdge::slotRemoveEdge() { - m_view->removeSelectedElements(); + m_view->removeSelectedElements(); } -void CanvasEdge::hoverEnterEvent( QGraphicsSceneHoverEvent * event ) +void CanvasEdge::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event) - qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->id(); - emit hoverEnter(this); + Q_UNUSED(event) + qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->id(); + emit hoverEnter(this); } -void CanvasEdge::hoverLeaveEvent( QGraphicsSceneHoverEvent * event ) +void CanvasEdge::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event) - qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->id(); - emit hoverLeave(this); + Q_UNUSED(event) + qCDebug(KGRAPHVIEWERLIB_LOG) << edge()->id(); + emit hoverLeave(this); } } diff --git a/src/part/canvaselement.h b/src/part/canvaselement.h --- a/src/part/canvaselement.h +++ b/src/part/canvaselement.h @@ -24,81 +24,78 @@ #define CANVAS_ELEMENT_H #include -#include #include +#include #include "dotgrammar.h" class QMenu; class QGraphicsScene; - namespace KGraphViewer { class GraphElement; class DotGraphView; -class CanvasElement: public QObject, public QAbstractGraphicsShapeItem +class CanvasElement : public QObject, public QAbstractGraphicsShapeItem { -Q_OBJECT + Q_OBJECT public: - CanvasElement( - DotGraphView* v, - GraphElement* s, - QGraphicsScene* c, - QGraphicsItem* parent = nullptr); - - ~CanvasElement() override; + CanvasElement(DotGraphView *v, GraphElement *s, QGraphicsScene *c, QGraphicsItem *parent = nullptr); + + ~CanvasElement() override; + + GraphElement *element() + { + return m_element; + } - GraphElement* element() { return m_element; } + void paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; - void paint(QPainter* p, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + QRectF boundingRect() const override; - QRectF boundingRect() const override; + void computeBoundingRect(); - void computeBoundingRect(); - - void initialize(qreal scaleX, qreal scaleY, - qreal xMargin, qreal yMargin, qreal gh); + void initialize(qreal scaleX, qreal scaleY, qreal xMargin, qreal yMargin, qreal gh); - inline void setGh(qreal gh) {m_gh = gh;} + inline void setGh(qreal gh) + { + m_gh = gh; + } protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - - qreal m_scaleX, m_scaleY; - qreal m_xMargin, m_yMargin, m_gh; - GraphElement* m_element; - DotGraphView* m_view; - QFont* m_font; - QPen m_pen; - QBrush m_brush; - QRectF m_boundingRect; - QMenu* m_popup; - - bool m_hovered; - - quint32 m_lastRenderOpRev; - typedef QHash > FontSizeCache; - FontSizeCache m_fontSizeCache; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + + qreal m_scaleX, m_scaleY; + qreal m_xMargin, m_yMargin, m_gh; + GraphElement *m_element; + DotGraphView *m_view; + QFont *m_font; + QPen m_pen; + QBrush m_brush; + QRectF m_boundingRect; + QMenu *m_popup; + + bool m_hovered; + + quint32 m_lastRenderOpRev; + typedef QHash> FontSizeCache; + FontSizeCache m_fontSizeCache; Q_SIGNALS: - void selected(CanvasElement*, Qt::KeyboardModifiers); - void elementContextMenuEvent(const QString&, const QPoint&); - void hoverEnter(CanvasElement*); - void hoverLeave(CanvasElement*); - + void selected(CanvasElement *, Qt::KeyboardModifiers); + void elementContextMenuEvent(const QString &, const QPoint &); + void hoverEnter(CanvasElement *); + void hoverLeave(CanvasElement *); + public Q_SLOTS: - void modelChanged(); - void slotRemoveElement(); + void modelChanged(); + void slotRemoveElement(); }; } #endif // CANVAS_ELEMENT_H - - - diff --git a/src/part/canvaselement.cpp b/src/part/canvaselement.cpp --- a/src/part/canvaselement.cpp +++ b/src/part/canvaselement.cpp @@ -16,26 +16,25 @@ 02110-1301, USA */ - #include "canvaselement.h" +#include "FontsCache.h" +#include "dot2qtconsts.h" +#include "dotdefaults.h" #include "dotgraphview.h" #include "graphelement.h" -#include "dotdefaults.h" -#include "dot2qtconsts.h" -#include "FontsCache.h" #include "kgraphviewerlib_debug.h" -#include -#include #include +#include +#include -#include #include #include #include +#include -#include #include +#include #include // comment out to get extended debug output during rendering @@ -47,574 +46,482 @@ namespace KGraphViewer { - - -CanvasElement::CanvasElement( - DotGraphView* v, - GraphElement* gelement, - QGraphicsScene* c, - QGraphicsItem* parent - ) - : QObject(), QAbstractGraphicsShapeItem(parent), - m_scaleX(0), m_scaleY(0), - m_xMargin(0), m_yMargin(0), m_gh(0), - m_element(gelement), m_view(v), - m_font(nullptr), - m_pen(Dot2QtConsts::componentData().qtColor(gelement->fontColor())), - m_popup(new QMenu()), - m_hovered(false), - m_lastRenderOpRev(0) +CanvasElement::CanvasElement(DotGraphView *v, GraphElement *gelement, QGraphicsScene *c, QGraphicsItem *parent) + : QObject() + , QAbstractGraphicsShapeItem(parent) + , m_scaleX(0) + , m_scaleY(0) + , m_xMargin(0) + , m_yMargin(0) + , m_gh(0) + , m_element(gelement) + , m_view(v) + , m_font(nullptr) + , m_pen(Dot2QtConsts::componentData().qtColor(gelement->fontColor())) + , m_popup(new QMenu()) + , m_hovered(false) + , m_lastRenderOpRev(0) { -// qCDebug(KGRAPHVIEWERLIB_LOG); - m_font = FontsCache::changeable().fromName(gelement->fontName()); - -/* qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating CanvasElement for "<id(); - qCDebug(KGRAPHVIEWERLIB_LOG) << " data: " << wdhcf << "," << hdvcf << "," << gh << "," - << scaleX << "," << scaleY << "," << xMargin << "," << yMargin << endl;*/ - - if (element()->style() == "bold") - { - m_pen.setStyle(Qt::SolidLine); - m_pen.setWidth(int(2*((m_scaleX+m_scaleY)/2))); - } - else if (element()->style() != "filled") - { - m_pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(m_element->style())); - m_pen.setWidth(int((m_scaleX+m_scaleY)/2)); - if (element()->style().left(12) == "setlinewidth") - { - bool ok; - uint lineWidth = element()->style().mid(13, m_element->style().length()-1-13).toInt(&ok); - m_pen.setWidth(lineWidth * int((m_scaleX+m_scaleY)/2)); + // qCDebug(KGRAPHVIEWERLIB_LOG); + m_font = FontsCache::changeable().fromName(gelement->fontName()); + + /* qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating CanvasElement for "<id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << " data: " << wdhcf << "," << hdvcf << "," << gh << "," + << scaleX << "," << scaleY << "," << xMargin << "," << yMargin << endl;*/ + + if (element()->style() == "bold") { + m_pen.setStyle(Qt::SolidLine); + m_pen.setWidth(int(2 * ((m_scaleX + m_scaleY) / 2))); + } else if (element()->style() != "filled") { + m_pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(m_element->style())); + m_pen.setWidth(int((m_scaleX + m_scaleY) / 2)); + if (element()->style().left(12) == "setlinewidth") { + bool ok; + uint lineWidth = element()->style().mid(13, m_element->style().length() - 1 - 13).toInt(&ok); + m_pen.setWidth(lineWidth * int((m_scaleX + m_scaleY) / 2)); + } + } + if (m_element->style() == "filled") { + m_brush = Dot2QtConsts::componentData().qtColor(element()->backColor()); + // QCanvasPolygon::drawShape(p); + } else { + m_brush = c->backgroundBrush(); } - } - if (m_element->style() == "filled") - { - m_brush = Dot2QtConsts::componentData().qtColor(element()->backColor()); -// QCanvasPolygon::drawShape(p); - } - else - { - m_brush = c->backgroundBrush(); - } - - // the message should be given (or possible to be given) by the part user - QAction* removeElementAction = new QAction(i18n("Remove selected element(s)"), this); - m_popup->addAction(removeElementAction); - connect(removeElementAction, &QAction::triggered, - this, &CanvasElement::slotRemoveElement); - - connect(this, &CanvasElement::selected, - v, &DotGraphView::slotElementSelected); - - connect(this, &CanvasElement::elementContextMenuEvent, - v, &DotGraphView::slotContextMenuEvent); - - setAcceptHoverEvents ( true ); - - connect(this, &CanvasElement::hoverEnter, - v, static_cast(&DotGraphView::slotElementHoverEnter)); - connect(this, &CanvasElement::hoverLeave, - v, static_cast(&DotGraphView::slotElementHoverLeave)); - + + // the message should be given (or possible to be given) by the part user + QAction *removeElementAction = new QAction(i18n("Remove selected element(s)"), this); + m_popup->addAction(removeElementAction); + connect(removeElementAction, &QAction::triggered, this, &CanvasElement::slotRemoveElement); + + connect(this, &CanvasElement::selected, v, &DotGraphView::slotElementSelected); + + connect(this, &CanvasElement::elementContextMenuEvent, v, &DotGraphView::slotContextMenuEvent); + + setAcceptHoverEvents(true); + + connect(this, &CanvasElement::hoverEnter, v, static_cast(&DotGraphView::slotElementHoverEnter)); + connect(this, &CanvasElement::hoverLeave, v, static_cast(&DotGraphView::slotElementHoverLeave)); } CanvasElement::~CanvasElement() { - delete m_popup; + delete m_popup; } void CanvasElement::modelChanged() { - qCDebug(KGRAPHVIEWERLIB_LOG) ;//<< id(); - m_pen = QPen(Dot2QtConsts::componentData().qtColor(m_element->fontColor())); - m_font = FontsCache::changeable().fromName(m_element->fontName()); - prepareGeometryChange(); - computeBoundingRect(); + qCDebug(KGRAPHVIEWERLIB_LOG); //<< id(); + m_pen = QPen(Dot2QtConsts::componentData().qtColor(m_element->fontColor())); + m_font = FontsCache::changeable().fromName(m_element->fontName()); + prepareGeometryChange(); + computeBoundingRect(); } -void CanvasElement::initialize(qreal scaleX, qreal scaleY, - qreal xMargin, qreal yMargin, qreal gh) +void CanvasElement::initialize(qreal scaleX, qreal scaleY, qreal xMargin, qreal yMargin, qreal gh) { - Q_UNUSED(gh); -// qCDebug(KGRAPHVIEWERLIB_LOG); - setFlag(QGraphicsItem::ItemIsMovable, true); - setFlag(QGraphicsItem::ItemIsSelectable, true); + Q_UNUSED(gh); + // qCDebug(KGRAPHVIEWERLIB_LOG); + setFlag(QGraphicsItem::ItemIsMovable, true); + setFlag(QGraphicsItem::ItemIsSelectable, true); - m_scaleX = scaleX; m_scaleY = scaleY; - m_xMargin = xMargin; m_yMargin = yMargin; -// m_gh = gh; + m_scaleX = scaleX; + m_scaleY = scaleY; + m_xMargin = xMargin; + m_yMargin = yMargin; + // m_gh = gh; - setZValue(m_element->z()); + setZValue(m_element->z()); - computeBoundingRect(); + computeBoundingRect(); } -QRectF CanvasElement::boundingRect () const +QRectF CanvasElement::boundingRect() const { - return m_boundingRect; + return m_boundingRect; } void CanvasElement::computeBoundingRect() { -// qCDebug(KGRAPHVIEWERLIB_LOG) << element(); - qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << zValue(); - - qreal adjust = 0.5; - QRectF rect; - if (element()->renderOperations().isEmpty()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "no render operation"; - rect = QRectF(0,0,(m_view->defaultNewElementPixmap().size().width())*m_scaleX,(m_view->defaultNewElementPixmap().size().height())*m_scaleY); - m_boundingRect = rect; - } - else - { - DotRenderOpVec::const_iterator it, it_end; - it = element()->renderOperations().constBegin(); it_end = element()->renderOperations().constEnd(); - for (; it != it_end; it++) - { + // qCDebug(KGRAPHVIEWERLIB_LOG) << element(); + qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << zValue(); + + qreal adjust = 0.5; + QRectF rect; + if (element()->renderOperations().isEmpty()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "no render operation"; + rect = QRectF(0, 0, (m_view->defaultNewElementPixmap().size().width()) * m_scaleX, (m_view->defaultNewElementPixmap().size().height()) * m_scaleY); + m_boundingRect = rect; + } else { + DotRenderOpVec::const_iterator it, it_end; + it = element()->renderOperations().constBegin(); + it_end = element()->renderOperations().constEnd(); + for (; it != it_end; it++) { #if RENDER_DEBUG - QString msg; - QTextStream dd(&msg); - dd << element()->id() << " an op: " << (*it).renderop << " "; - foreach (int i, (*it).integers) - { - dd << i << " "; - } - dd << (*it).str; - qCDebug(KGRAPHVIEWERLIB_LOG) << msg; + QString msg; + QTextStream dd(&msg); + dd << element()->id() << " an op: " << (*it).renderop << " "; + foreach (int i, (*it).integers) { + dd << i << " "; + } + dd << (*it).str; + qCDebug(KGRAPHVIEWERLIB_LOG) << msg; #endif - if ((*it).renderop == "e" || (*it).renderop == "E") - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "integers[0]=" << (*it).integers[0] << "; - qreal w = m_scaleX * (*it).integers[2] * 2; - qreal h = m_scaleY * (*it).integers[3] * 2; - qreal x = m_xMargin + (((*it).integers[0])*m_scaleX) - w/2; - qreal y = ((m_gh - (*it).integers[1])*m_scaleY) + m_yMargin - h/2; - m_boundingRect = QRectF(x - adjust,y - adjust, w + adjust, h + adjust); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << element()->id() << "' set rect for ellipse to " << rect; - } - else if ((*it).renderop == "p" || (*it).renderop == "P") - { - QPolygonF polygon((*it).integers[0]); - for (int i = 0; i < (*it).integers[0]; i++) - { - qreal x,y; - x = (*it).integers[2*i+1]; - y = (*it).integers[2*i+2]; - { - - } - QPointF p( - x*m_scaleX +m_xMargin, - (m_gh-y)*m_scaleY + m_yMargin - ); - polygon[i] = p; + if ((*it).renderop == "e" || (*it).renderop == "E") { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "integers[0]=" << (*it).integers[0] << "; + qreal w = m_scaleX * (*it).integers[2] * 2; + qreal h = m_scaleY * (*it).integers[3] * 2; + qreal x = m_xMargin + (((*it).integers[0]) * m_scaleX) - w / 2; + qreal y = ((m_gh - (*it).integers[1]) * m_scaleY) + m_yMargin - h / 2; + m_boundingRect = QRectF(x - adjust, y - adjust, w + adjust, h + adjust); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << element()->id() << "' set rect for ellipse to " << rect; + } else if ((*it).renderop == "p" || (*it).renderop == "P") { + QPolygonF polygon((*it).integers[0]); + for (int i = 0; i < (*it).integers[0]; i++) { + qreal x, y; + x = (*it).integers[2 * i + 1]; + y = (*it).integers[2 * i + 2]; + { + } + QPointF p(x * m_scaleX + m_xMargin, (m_gh - y) * m_scaleY + m_yMargin); + polygon[i] = p; + } + m_boundingRect = polygon.boundingRect(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << element()->id() << "' set rect for polygon to " << rect; + } } - m_boundingRect = polygon.boundingRect(); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << element()->id() << "' set rect for polygon to " << rect; - } } - } - setPos(0,0); + setPos(0, 0); } -///TODO: optimize more! -void CanvasElement::paint(QPainter* p, const QStyleOptionGraphicsItem *option, -QWidget *widget) +/// TODO: optimize more! +void CanvasElement::paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if (m_lastRenderOpRev != element()->renderOperationsRevision()) { - m_fontSizeCache.clear(); - } - - Q_UNUSED(option) - Q_UNUSED(widget) - /// computes the scaling of line width - qreal widthScaleFactor = (m_scaleX+m_scaleY)/2; - if (widthScaleFactor < 1) - { - widthScaleFactor = 1; - } + if (m_lastRenderOpRev != element()->renderOperationsRevision()) { + m_fontSizeCache.clear(); + } + + Q_UNUSED(option) + Q_UNUSED(widget) + /// computes the scaling of line width + qreal widthScaleFactor = (m_scaleX + m_scaleY) / 2; + if (widthScaleFactor < 1) { + widthScaleFactor = 1; + } #if RENDER_DEBUG - QString msg; - QTextStream dd(&msg); - foreach (const DotRenderOp &op, element()->renderOperations()) - { - dd << element()->id() << " an op: " << op.renderop << " "; - foreach (int i, op.integers) - { - dd << i << " "; + QString msg; + QTextStream dd(&msg); + foreach (const DotRenderOp &op, element()->renderOperations()) { + dd << element()->id() << " an op: " << op.renderop << " "; + foreach (int i, op.integers) { + dd << i << " "; + } + dd << op.str << endl; } - dd << op.str << endl; - } - qCDebug(KGRAPHVIEWERLIB_LOG) << msg; + qCDebug(KGRAPHVIEWERLIB_LOG) << msg; #endif - if (element()->renderOperations().isEmpty() && m_view->isReadWrite()) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << element()->id() << ": no render operation. This should not happen."; - return; - } - - QListIterator it(element()->renderOperations()); -// it.toBack(); - - QColor lineColor = Dot2QtConsts::componentData().qtColor(element()->lineColor()); - QColor backColor = Dot2QtConsts::componentData().qtColor(element()->backColor()); - if (m_hovered && m_view->highlighting()) - { - backColor = backColor.lighter(); - } - - const QPen oldPen = p->pen(); - const QBrush oldBrush = p->brush(); - const QFont oldFont = p->font(); - - while (it.hasNext()) - { - const DotRenderOp& dro = it.next(); - if (dro.renderop == "c") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); - lineColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; + if (element()->renderOperations().isEmpty() && m_view->isReadWrite()) { + qCWarning(KGRAPHVIEWERLIB_LOG) << element()->id() << ": no render operation. This should not happen."; + return; } - else if (dro.renderop == "C") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); - if (m_hovered && m_view->highlighting()) - { - c = c.lighter(); - } - backColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; - } - else if (dro.renderop == "e" || dro.renderop == "E") - { - QPen pen = oldPen; - qreal w = m_scaleX * dro.integers[2] * 2; - qreal h = m_scaleY * dro.integers[3] * 2; - qreal x = m_xMargin + (dro.integers[0]*m_scaleX) - w/2; - qreal y = ((m_gh - dro.integers[1])*m_scaleY) + m_yMargin - h/2; - QRectF rect(x,y,w,h); - pen.setColor(lineColor); - if (element()->attributes().contains("penwidth")) - { - bool ok; - int lineWidth = element()->attributes()["penwidth"].toInt(&ok); - pen.setWidth(int(lineWidth * widthScaleFactor)); - } - - p->setBrush(backColor); - p->setPen(pen); - -// qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawEllipse" << lineColor << backColor << rect; -// rect = QRectF(0,0,100,100); - p->drawEllipse(rect); + + QListIterator it(element()->renderOperations()); + // it.toBack(); + + QColor lineColor = Dot2QtConsts::componentData().qtColor(element()->lineColor()); + QColor backColor = Dot2QtConsts::componentData().qtColor(element()->backColor()); + if (m_hovered && m_view->highlighting()) { + backColor = backColor.lighter(); } - else if(dro.renderop == "p" || dro.renderop == "P") - { -// std::cerr << "Drawing polygon for node '"<id()<<"': "; - QPolygonF points(dro.integers[0]); - for (int i = 0; i < dro.integers[0]; i++) - { - qreal x,y; - x = dro.integers[2*i+1]; - y = dro.integers[2*i+2]; - QPointF p( - (x*m_scaleX) + m_xMargin, - ((m_gh-y)*m_scaleY) + m_yMargin - ); -/* qCDebug(KGRAPHVIEWERLIB_LOG) << " point: (" << dro.integers[2*i+1] << "," - << dro.integers[2*i+2] << ") " */ - points[i] = p; - } - - QPen pen = oldPen; - pen.setColor(lineColor); - if (element()->style() == "bold") - { - pen.setStyle(Qt::SolidLine); - pen.setWidth(2); - } - if (element()->attributes().contains("penwidth")) - { - bool ok; - int lineWidth = element()->attributes()["penwidth"].toInt(&ok); - pen.setWidth(int(lineWidth * widthScaleFactor)); - } - else if (element()->style() != "filled") - { - pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(element()->style())); - } - if (element()->style().left(12) == "setlinewidth") - { - bool ok; - uint lineWidth = element()->style().mid(12, element()->style().length()-1-12).toInt(&ok); - pen.setWidth(lineWidth); - } - p->setPen(pen); - p->setBrush(backColor); -/* if (element()->style() == "filled") - { - p->setBrush(Dot2QtConsts::componentData().qtColor(element()->backColor())); - // QCanvasPolygon::paint(p); - } - else - { - p->setBrush(canvas()->backgroundColor()); - }*/ -// qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawPolygon" << points; - p->drawPolygon(points); - if (!element()->shapeFile().isEmpty()) - { - QPixmap pix(element()->shapeFile()); - if (!pix.isNull()) - { - p->drawPixmap(int(points.boundingRect().left()), int(points.boundingRect().top()), pix); + + const QPen oldPen = p->pen(); + const QBrush oldBrush = p->brush(); + const QFont oldFont = p->font(); + + while (it.hasNext()) { + const DotRenderOp &dro = it.next(); + if (dro.renderop == "c") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + lineColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; + } else if (dro.renderop == "C") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + if (m_hovered && m_view->highlighting()) { + c = c.lighter(); + } + backColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; + } else if (dro.renderop == "e" || dro.renderop == "E") { + QPen pen = oldPen; + qreal w = m_scaleX * dro.integers[2] * 2; + qreal h = m_scaleY * dro.integers[3] * 2; + qreal x = m_xMargin + (dro.integers[0] * m_scaleX) - w / 2; + qreal y = ((m_gh - dro.integers[1]) * m_scaleY) + m_yMargin - h / 2; + QRectF rect(x, y, w, h); + pen.setColor(lineColor); + if (element()->attributes().contains("penwidth")) { + bool ok; + int lineWidth = element()->attributes()["penwidth"].toInt(&ok); + pen.setWidth(int(lineWidth * widthScaleFactor)); + } + + p->setBrush(backColor); + p->setPen(pen); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawEllipse" << lineColor << backColor << rect; + // rect = QRectF(0,0,100,100); + p->drawEllipse(rect); + } else if (dro.renderop == "p" || dro.renderop == "P") { + // std::cerr << "Drawing polygon for node '"<id()<<"': "; + QPolygonF points(dro.integers[0]); + for (int i = 0; i < dro.integers[0]; i++) { + qreal x, y; + x = dro.integers[2 * i + 1]; + y = dro.integers[2 * i + 2]; + QPointF p((x * m_scaleX) + m_xMargin, ((m_gh - y) * m_scaleY) + m_yMargin); + /* qCDebug(KGRAPHVIEWERLIB_LOG) << " point: (" << dro.integers[2*i+1] << "," + << dro.integers[2*i+2] << ") " */ + points[i] = p; + } + + QPen pen = oldPen; + pen.setColor(lineColor); + if (element()->style() == "bold") { + pen.setStyle(Qt::SolidLine); + pen.setWidth(2); + } + if (element()->attributes().contains("penwidth")) { + bool ok; + int lineWidth = element()->attributes()["penwidth"].toInt(&ok); + pen.setWidth(int(lineWidth * widthScaleFactor)); + } else if (element()->style() != "filled") { + pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(element()->style())); + } + if (element()->style().left(12) == "setlinewidth") { + bool ok; + uint lineWidth = element()->style().mid(12, element()->style().length() - 1 - 12).toInt(&ok); + pen.setWidth(lineWidth); + } + p->setPen(pen); + p->setBrush(backColor); + /* if (element()->style() == "filled") + { + p->setBrush(Dot2QtConsts::componentData().qtColor(element()->backColor())); + // QCanvasPolygon::paint(p); + } + else + { + p->setBrush(canvas()->backgroundColor()); + }*/ + // qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawPolygon" << points; + p->drawPolygon(points); + if (!element()->shapeFile().isEmpty()) { + QPixmap pix(element()->shapeFile()); + if (!pix.isNull()) { + p->drawPixmap(int(points.boundingRect().left()), int(points.boundingRect().top()), pix); + } + } } - } } - } - - p->setBrush(oldBrush); - p->setPen(oldPen); - - it.toFront(); - while (it.hasNext()) - { - const DotRenderOp& dro = it.next(); - if (dro.renderop == "c") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); - lineColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; + p->setBrush(oldBrush); + p->setPen(oldPen); + + it.toFront(); + while (it.hasNext()) { + const DotRenderOp &dro = it.next(); + if (dro.renderop == "c") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + lineColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "c" << dro.str.mid(0,7) << lineColor; + } else if (dro.renderop == "C") { + QColor c(dro.str.mid(0, 7)); + bool ok; + c.setAlpha(255 - dro.str.mid(8).toInt(&ok, 16)); + if (m_hovered && m_view->highlighting()) { + c = c.lighter(); + } + backColor = c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; + } else if (dro.renderop == "L") { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Label"; + QPolygonF points(dro.integers[0]); + for (int i = 0; i < dro.integers[0]; i++) { + qreal x, y; + x = dro.integers[2 * i + 1]; + y = dro.integers[2 * i + 2]; + QPointF p((x * m_scaleX) + m_xMargin, ((m_gh - y) * m_scaleY) + m_yMargin); + points[i] = p; + } + QPen pen(lineColor); + if (element()->style() == "bold") { + pen.setStyle(Qt::SolidLine); + pen.setWidth(2); + } else if (element()->style() != "filled") { + pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(element()->style())); + } + p->setPen(pen); + // qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawPolyline" << points; + p->drawPolyline(points); + } } - else if (dro.renderop == "C") - { - QColor c(dro.str.mid(0,7)); - bool ok; - c.setAlpha(255-dro.str.mid(8).toInt(&ok,16)); - if (m_hovered && m_view->highlighting()) - { - c = c.lighter(); - } - backColor = c; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "C" << dro.str.mid(0,7) << backColor; + p->setPen(oldPen); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Drawing" << element()->id() << "labels"; + QString color = lineColor.name(); + it.toFront(); + uint num_T = 0; + while (it.hasNext()) { + const DotRenderOp &dro = it.next(); + if (dro.renderop == "c" || dro.renderop == "C") { + color = dro.str.mid(0, 7); + // qCDebug(KGRAPHVIEWERLIB_LOG) << dro.renderop << color; + } else if (dro.renderop == "F") { + element()->setFontName(dro.str); + element()->setFontSize(dro.integers[0]); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "F" << element()->fontName() << element()->fontColor() << element()->fontSize(); + } else if (dro.renderop == "T") { + ++num_T; + // we suppose here that the color has been set just before + element()->setFontColor(color); + // draw a label + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Drawing a label " << dro.integers[0] + // << " " << dro.integers[1] << " " << dro.integers[2] + // << " " << dro.integers[3] << " " << dro.str + // << " (" << element()->fontName() << ", " << element()->fontSize() + // << ", " << element()->fontColor() << ")"; + + int fontWidth = 0; + bool cacheValid = false; + // qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << " initial fontSize " << fontSize; + if (m_lastRenderOpRev == element()->renderOperationsRevision()) { + FontSizeCache::iterator cacheIt = m_fontSizeCache.find(num_T); + if (cacheIt != m_fontSizeCache.end()) { + m_font->setPointSize(cacheIt->first); + fontWidth = cacheIt->second; + cacheValid = true; + } + } + if (!cacheValid) { + int stringWidthGoal = int(dro.integers[3] * m_scaleX); + int fontSize = element()->fontSize(); + m_font->setPointSize(fontSize); + + QFontMetrics fm(*m_font); + fontWidth = fm.width(dro.str); + while (fontWidth > stringWidthGoal && fontSize > 1) { + // use floor'ed extrapolated font size + fontSize = double(stringWidthGoal) / fontWidth * fontSize; + m_font->setPointSize(fontSize); + fm = QFontMetrics(*m_font); + fontWidth = fm.width(dro.str); + } + m_fontSizeCache[num_T] = qMakePair(fontSize, fontWidth); + } + + p->setFont(*m_font); + QPen pen(m_pen); + pen.setColor(element()->fontColor()); + p->setPen(pen); + qreal x = (m_scaleX * ((dro.integers[0]) + (((-dro.integers[2]) * (fontWidth)) / 2) - ((fontWidth) / 2))) + m_xMargin; + qreal y = ((m_gh - (dro.integers[1])) * m_scaleY) + m_yMargin; + QPointF point(x, y); + // qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawText" << point << " " << fontSize; + p->drawText(point, dro.str); + } } - else if ( dro.renderop == "L" ) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Label"; - QPolygonF points(dro.integers[0]); - for (int i = 0; i < dro.integers[0]; i++) - { - qreal x,y; - x = dro.integers[2*i+1]; - y = dro.integers[2*i+2]; - QPointF p( - (x*m_scaleX) +m_xMargin, - ((m_gh-y)*m_scaleY) + m_yMargin - ); - points[i] = p; - } - QPen pen(lineColor); - if (element()->style() == "bold") - { - pen.setStyle(Qt::SolidLine); - pen.setWidth(2); - } - else if (element()->style() != "filled") - { - pen.setStyle(Dot2QtConsts::componentData().qtPenStyle(element()->style())); - } - p->setPen(pen); -// qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawPolyline" << points; - p->drawPolyline(points); + + if (element()->isSelected()) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "element is selected: draw selection marks"; + p->setBrush(Qt::black); + p->setPen(Qt::black); + p->drawRect(QRectF(m_boundingRect.topLeft(), QSizeF(6, 6))); + p->drawRect(QRectF(m_boundingRect.topRight() - QPointF(6, 0), QSizeF(6, 6))); + p->drawRect(QRectF(m_boundingRect.bottomLeft() - QPointF(0, 6), QSizeF(6, 6))); + p->drawRect(QRectF(m_boundingRect.bottomRight() - QPointF(6, 6), QSizeF(6, 6))); } - } - p->setPen(oldPen); - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Drawing" << element()->id() << "labels"; - QString color = lineColor.name(); - it.toFront(); - uint num_T = 0; - while (it.hasNext()) - { - const DotRenderOp& dro = it.next(); - if (dro.renderop == "c" || dro.renderop == "C") - { - color = dro.str.mid(0,7); -// qCDebug(KGRAPHVIEWERLIB_LOG) << dro.renderop << color; + + p->setPen(oldPen); + p->setBrush(oldBrush); + p->setFont(oldFont); + + m_lastRenderOpRev = element()->renderOperationsRevision(); +} + +void CanvasElement::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << m_element->id() << boundingRect(); + if (m_view->isReadOnly()) { + return; } - else if (dro.renderop == "F") - { - element()->setFontName(dro.str); - element()->setFontSize(dro.integers[0]); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "F" << element()->fontName() << element()->fontColor() << element()->fontSize(); + if (m_view->editingMode() == DotGraphView::AddNewEdge) { + m_view->createNewEdgeDraftFrom(this); + return; + } else if (m_view->editingMode() == DotGraphView::DrawNewEdge) { + m_view->finishNewEdgeTo(this); + return; } - else if ( dro.renderop == "T" ) - { - ++num_T; - // we suppose here that the color has been set just before - element()->setFontColor(color); - // draw a label -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Drawing a label " << dro.integers[0] -// << " " << dro.integers[1] << " " << dro.integers[2] -// << " " << dro.integers[3] << " " << dro.str -// << " (" << element()->fontName() << ", " << element()->fontSize() -// << ", " << element()->fontColor() << ")"; - - int fontWidth = 0; - bool cacheValid = false; -// qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << " initial fontSize " << fontSize; - if (m_lastRenderOpRev == element()->renderOperationsRevision()) { - FontSizeCache::iterator cacheIt = m_fontSizeCache.find(num_T); - if (cacheIt != m_fontSizeCache.end()) { - m_font->setPointSize(cacheIt->first); - fontWidth = cacheIt->second; - cacheValid = true; + if (event->button() == Qt::LeftButton) { + m_element->setSelected(!m_element->isSelected()); + if (m_element->isSelected()) { + emit(selected(this, event->modifiers())); } - } - if (!cacheValid) { - int stringWidthGoal = int(dro.integers[3] * m_scaleX); - int fontSize = element()->fontSize(); - m_font->setPointSize(fontSize); - - QFontMetrics fm(*m_font); - fontWidth = fm.width(dro.str); - while (fontWidth > stringWidthGoal && fontSize > 1) - { - // use floor'ed extrapolated font size - fontSize = double(stringWidthGoal) / fontWidth * fontSize; - m_font->setPointSize(fontSize); - fm = QFontMetrics(*m_font); - fontWidth = fm.width(dro.str); + update(); + } else if (event->button() == Qt::RightButton) { + // opens the selected edge contextual menu and if necessary select the edge + if (!m_element->isSelected()) { + m_element->setSelected(true); + emit(selected(this, event->modifiers())); + update(); } - m_fontSizeCache[num_T] = qMakePair(fontSize, fontWidth); - } - - p->setFont(*m_font); - QPen pen(m_pen); - pen.setColor(element()->fontColor()); - p->setPen(pen); - qreal x = (m_scaleX * - ( - (dro.integers[0]) - + (((-dro.integers[2])*(fontWidth))/2) - - ( (fontWidth)/2 ) - ) - ) - + m_xMargin; - qreal y = ((m_gh - (dro.integers[1]))*m_scaleY)+ m_yMargin; - QPointF point(x,y); -// qCDebug(KGRAPHVIEWERLIB_LOG) << element()->id() << "drawText" << point << " " << fontSize; - p->drawText(point, dro.str); - } - } - - if (element()->isSelected()) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "element is selected: draw selection marks"; - p->setBrush(Qt::black); - p->setPen(Qt::black); - p->drawRect(QRectF(m_boundingRect.topLeft(),QSizeF(6,6))); - p->drawRect(QRectF(m_boundingRect.topRight()-QPointF(6,0),QSizeF(6,6))); - p->drawRect(QRectF(m_boundingRect.bottomLeft()-QPointF(0,6),QSizeF(6,6))); - p->drawRect(QRectF(m_boundingRect.bottomRight()-QPointF(6,6),QSizeF(6,6))); - } - - p->setPen(oldPen); - p->setBrush(oldBrush); - p->setFont(oldFont); - - m_lastRenderOpRev = element()->renderOperationsRevision(); -} -void CanvasElement::mousePressEvent(QGraphicsSceneMouseEvent* event) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << m_element->id() << boundingRect(); - if (m_view->isReadOnly()) - { - return; - } - if (m_view->editingMode() == DotGraphView::AddNewEdge) - { - m_view->createNewEdgeDraftFrom(this); - return; - } - else if (m_view->editingMode() == DotGraphView::DrawNewEdge) - { - m_view->finishNewEdgeTo(this); - return; - } - if (event->button() == Qt::LeftButton) - { - m_element->setSelected(!m_element->isSelected()); - if (m_element->isSelected()) - { - emit(selected(this,event->modifiers())); - } - update(); - } - else if (event->button() == Qt::RightButton) - { - // opens the selected edge contextual menu and if necessary select the edge - if (!m_element->isSelected()) - { - m_element->setSelected(true); - emit(selected(this,event->modifiers())); - update(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "opens the contextual menu"; + // m_popup->exec(event->screenPos()); + emit(elementContextMenuEvent(m_element->id(), event->screenPos())); } - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "opens the contextual menu"; -// m_popup->exec(event->screenPos()); - emit(elementContextMenuEvent(m_element->id(), event->screenPos() )); - } } -void CanvasElement::mouseMoveEvent(QGraphicsSceneMouseEvent* event) +void CanvasElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - Q_UNUSED(event) -// qCDebug(KGRAPHVIEWERLIB_LOG) ; + Q_UNUSED(event) + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } -void CanvasElement::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) +void CanvasElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - Q_UNUSED(event) -// qCDebug(KGRAPHVIEWERLIB_LOG) ; + Q_UNUSED(event) + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } void CanvasElement::slotRemoveElement() { - m_view->removeSelectedElements(); + m_view->removeSelectedElements(); } -void CanvasElement::hoverEnterEvent( QGraphicsSceneHoverEvent * event ) +void CanvasElement::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event) -// qCDebug(KGRAPHVIEWERLIB_LOG); - m_hovered = true; - update(); - emit hoverEnter(this); + Q_UNUSED(event) + // qCDebug(KGRAPHVIEWERLIB_LOG); + m_hovered = true; + update(); + emit hoverEnter(this); } -void CanvasElement::hoverLeaveEvent( QGraphicsSceneHoverEvent * event ) +void CanvasElement::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { - Q_UNUSED(event) -// qCDebug(KGRAPHVIEWERLIB_LOG); - m_hovered = false; - update(); - emit hoverLeave(this); + Q_UNUSED(event) + // qCDebug(KGRAPHVIEWERLIB_LOG); + m_hovered = false; + update(); + emit hoverLeave(this); } } diff --git a/src/part/canvasnode.h b/src/part/canvasnode.h --- a/src/part/canvasnode.h +++ b/src/part/canvasnode.h @@ -35,51 +35,46 @@ namespace KGraphViewer { - class GraphNode; class CanvasNode : public CanvasElement { - Q_OBJECT + Q_OBJECT public: - CanvasNode(DotGraphView* v, - GraphNode* s, - QGraphicsScene* c, - QGraphicsItem* parent = nullptr); + CanvasNode(DotGraphView *v, GraphNode *s, QGraphicsScene *c, QGraphicsItem *parent = nullptr); - ~CanvasNode() override {} + ~CanvasNode() override + { + } }; // class CanvasHtmlNode: public KHTMLPart, public CanvasNode // { // Q_OBJECT // public: // CanvasHtmlNode( -// DotGraphView* v, +// DotGraphView* v, // GraphNode* n, // const DotRenderOp& dro, // const DotRenderOpVec& dros, // QGraphicsScene* c, // double scaleX, double scaleY, int xMargin, int yMargin, int gh, // int wdhcf, int hdvcf); // virtual ~CanvasHtmlNode(); -// +// // QRect rect() {return view()->contentsRect();} -// +// // protected: // // virtual void paint(QPainter&); -// +// // public Q_SLOTS: // void move(int x, int y); // void zoomed(double factor); -// +// // private: // double m_zoomFactor; // int m_xMovedTo, m_yMovedTo; // }; } #endif - - - diff --git a/src/part/canvasnode.cpp b/src/part/canvasnode.cpp --- a/src/part/canvasnode.cpp +++ b/src/part/canvasnode.cpp @@ -24,71 +24,65 @@ License as published by the Free Software Foundation, version 2. */ - /* * Callgraph View */ #include "canvasnode.h" +#include "FontsCache.h" +#include "dot2qtconsts.h" +#include "dotdefaults.h" #include "dotgraphview.h" #include "graphnode.h" -#include "dotdefaults.h" -#include "dot2qtconsts.h" -#include "FontsCache.h" #include "kgraphviewerlib_debug.h" -#include -#include #include +#include +#include +#include #include #include #include -#include -#include #include -#include +#include +#include #include namespace KGraphViewer { - -CanvasNode::CanvasNode(DotGraphView* v, - GraphNode* s, - QGraphicsScene* c, - QGraphicsItem* parent) -: CanvasElement(v,(GraphElement*)s, c, parent) +CanvasNode::CanvasNode(DotGraphView *v, GraphNode *s, QGraphicsScene *c, QGraphicsItem *parent) + : CanvasElement(v, (GraphElement *)s, c, parent) { - qCDebug(KGRAPHVIEWERLIB_LOG) << s->id(); - connect(s, &GraphNode::changed, - this, &CanvasNode::modelChanged); - - QString tipStr; - QString id = s->id(); - QString label = s->label(); - tipStr = i18n("id='%1'\nlabel='%2'",id,label); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "CanvasEllipseNode setToolTip " << tipStr; - setToolTip(tipStr); + qCDebug(KGRAPHVIEWERLIB_LOG) << s->id(); + connect(s, &GraphNode::changed, this, &CanvasNode::modelChanged); + + QString tipStr; + QString id = s->id(); + QString label = s->label(); + tipStr = i18n("id='%1'\nlabel='%2'", id, label); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "CanvasEllipseNode setToolTip " << tipStr; + setToolTip(tipStr); } // CanvasHtmlNode::CanvasHtmlNode( -// DotGraphView* v, +// DotGraphView* v, // GraphNode* n, // const DotRenderOp& dro, // const DotRenderOpVec& dros, // QGraphicsScene* c, -// double scaleX, double scaleY, +// double scaleX, double scaleY, // int xMargin, int yMargin, int gh, // int wdhcf, int hdvcf // ) // : KHTMLPart(v->viewport()), CanvasNode(v, n) // { // m_renderOperations = dros; // // qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating "<id()<<" CanvasHtmlNode for" << n // // << " with label '" << n->label() << "'"; -// +// // QString myHTMLCode = n->label(); // myHTMLCode = myHTMLCode.mid(1, myHTMLCode.length() - 2); // // qCDebug(KGRAPHVIEWERLIB_LOG) << "HTML = " << myHTMLCode; @@ -116,25 +110,25 @@ // CanvasHtmlNode::connect(v, SIGNAL(contentsMoving(int,int)), this, SLOT(move(int,int))); // CanvasHtmlNode::connect(v, SIGNAL(zoomed(double)), this, SLOT(zoomed(double))); // } -// -// CanvasHtmlNode::~CanvasHtmlNode() +// +// CanvasHtmlNode::~CanvasHtmlNode() // { // KHTMLPart::hide(); // } -// +// // // void CanvasHtmlNode::paint(QPainter& p) // // { // // view()->drawContents(&p); // // } -// +// // void CanvasHtmlNode::move(int x, int y) // { // // qCDebug(KGRAPHVIEWERLIB_LOG) << "CanvasHtmlNode::move("<move(int((node()->x())*m_scaleX*m_zoomFactor - m_xMovedTo), int((m_gh-node()->y())*m_scaleY*m_zoomFactor) - m_yMovedTo); // // view()->move(int(x*m_scaleX), int((m_gh-y)*m_scaleY)); // } -// +// // void CanvasHtmlNode::zoomed(double factor) // { // m_zoomFactor = factor; diff --git a/src/part/canvassubgraph.h b/src/part/canvassubgraph.h --- a/src/part/canvassubgraph.h +++ b/src/part/canvassubgraph.h @@ -29,27 +29,21 @@ namespace KGraphViewer { - class GraphSubgraph; class DotGraphView; -class CanvasSubgraph: public CanvasElement +class CanvasSubgraph : public CanvasElement { - Q_OBJECT + Q_OBJECT public: - CanvasSubgraph( - DotGraphView* v, - GraphSubgraph* s, - QGraphicsScene* c, - QGraphicsItem* parent = nullptr); - ~CanvasSubgraph() override {} + CanvasSubgraph(DotGraphView *v, GraphSubgraph *s, QGraphicsScene *c, QGraphicsItem *parent = nullptr); + ~CanvasSubgraph() override + { + } protected: }; } #endif - - - diff --git a/src/part/canvassubgraph.cpp b/src/part/canvassubgraph.cpp --- a/src/part/canvassubgraph.cpp +++ b/src/part/canvassubgraph.cpp @@ -16,19 +16,12 @@ 02110-1301, USA */ - #include "canvassubgraph.h" namespace KGraphViewer { - - -CanvasSubgraph::CanvasSubgraph( - DotGraphView* v, - GraphSubgraph* gsubgraph, - QGraphicsScene* c, - QGraphicsItem* parent - ) : CanvasElement(v,(GraphElement*)gsubgraph,c,parent) +CanvasSubgraph::CanvasSubgraph(DotGraphView *v, GraphSubgraph *gsubgraph, QGraphicsScene *c, QGraphicsItem *parent) + : CanvasElement(v, (GraphElement *)gsubgraph, c, parent) { } diff --git a/src/part/dot2qtconsts.h b/src/part/dot2qtconsts.h --- a/src/part/dot2qtconsts.h +++ b/src/part/dot2qtconsts.h @@ -20,34 +20,36 @@ #ifndef DOT2QTCONSTS_H #define DOT2QTCONSTS_H +#include #include #include -#include /** @author Gael de Chalendar */ class Dot2QtConsts { public: - static const Dot2QtConsts& componentData() {return m_componentData;} - - QColor qtColor(const QString& dotColor) const; - Qt::PenStyle qtPenStyle(const QString& dotLineStyle) const; - QFont qtFont(const QString& dotFont) const; + static const Dot2QtConsts &componentData() + { + return m_componentData; + } + + QColor qtColor(const QString &dotColor) const; + Qt::PenStyle qtPenStyle(const QString &dotLineStyle) const; + QFont qtFont(const QString &dotFont) const; private: Dot2QtConsts(); ~Dot2QtConsts(); - static const Dot2QtConsts m_componentData; - - QMap< QString, Qt::PenStyle > m_penStyles; - QMap< QString, QString > m_colors; - QMap< QString, QColor > m_qcolors; - QMap< QString, QFont > m_psFonts; - + static const Dot2QtConsts m_componentData; + + QMap m_penStyles; + QMap m_colors; + QMap m_qcolors; + QMap m_psFonts; }; #endif diff --git a/src/part/dot2qtconsts.cpp b/src/part/dot2qtconsts.cpp --- a/src/part/dot2qtconsts.cpp +++ b/src/part/dot2qtconsts.cpp @@ -18,923 +18,888 @@ 02110-1301, USA ***************************************************************************/ #include "dot2qtconsts.h" -#include "dotgrammar.h" #include "canvasnode.h" +#include "dotgrammar.h" #include "kgraphviewerlib_debug.h" -#include #include +#include const Dot2QtConsts Dot2QtConsts::m_componentData; static const struct { - const char * input; - const char * roman; - const char * italic; - const char * bold; - const char * boldItalic; - const char * light; - const char * lightItalic; -} postscriptFontNames[] = { - { "arial", "Arial", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "avantgarde", "AvantGarde-Book", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "charter", "CharterBT-Roman", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "garamond", "Garamond-Regular", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "gillsans", "GillSans", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "helvetica", - "Helvetica", "Helvetica-Oblique", - "Helvetica-Bold", "Helvetica-BoldOblique", - "Helvetica-Outline", "Helvetica-OutlineOblique" }, - { "palatino", - "Palatino", "Palatino-Italic", - "Palatino-Bold", "Palatino-BoldItalic", - "Palatino", "Palatino-Italic" }, - { "times", - "Times-Roman", "Times-Italic", - "Times-Bold", "Times-BoldItalic", - "Times-Outline", "Times-Italic" }, - { "new century schoolbook", "NewCenturySchlbk-Roman", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "symbol", "Symbol", "Symbol", "Symbol", "Symbol", "Symbol", "Symbol" }, - { "terminal", "Courier", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "times new roman", "TimesNewRoman", nullptr, nullptr, nullptr, nullptr, nullptr }, - { "utopia", "Utopia-Regular", nullptr, nullptr, nullptr, nullptr, nullptr }, - { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } -}; - + const char *input; + const char *roman; + const char *italic; + const char *bold; + const char *boldItalic; + const char *light; + const char *lightItalic; +} postscriptFontNames[] = {{"arial", "Arial", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"avantgarde", "AvantGarde-Book", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"charter", "CharterBT-Roman", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"garamond", "Garamond-Regular", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"gillsans", "GillSans", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"helvetica", "Helvetica", "Helvetica-Oblique", "Helvetica-Bold", "Helvetica-BoldOblique", "Helvetica-Outline", "Helvetica-OutlineOblique"}, + {"palatino", "Palatino", "Palatino-Italic", "Palatino-Bold", "Palatino-BoldItalic", "Palatino", "Palatino-Italic"}, + {"times", "Times-Roman", "Times-Italic", "Times-Bold", "Times-BoldItalic", "Times-Outline", "Times-Italic"}, + {"new century schoolbook", "NewCenturySchlbk-Roman", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"symbol", "Symbol", "Symbol", "Symbol", "Symbol", "Symbol", "Symbol"}, + {"terminal", "Courier", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"times new roman", "TimesNewRoman", nullptr, nullptr, nullptr, nullptr, nullptr}, + {"utopia", "Utopia-Regular", nullptr, nullptr, nullptr, nullptr, nullptr}, + {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; + static const struct { - const char * name; + const char *name; unsigned int r; unsigned int g; unsigned int b; -} color_lib[] = { - { "snow", 255, 250, 250 }, - { "ghost white", 248, 248, 255 }, - { "ghostwhite", 248, 248, 255 }, - { "white smoke", 245, 245, 245 }, - { "whitesmoke", 245, 245, 245 }, - { "gainsboro", 220, 220, 220 }, - { "floral white", 255, 250, 240 }, - { "floralwhite", 255, 250, 240 }, - { "old lace", 253, 245, 230 }, - { "oldlace", 253, 245, 230 }, - { "linen", 250, 240, 230 }, - { "antique white", 250, 235, 215 }, - { "antiquewhite", 250, 235, 215 }, - { "papaya whip", 255, 239, 213 }, - { "papayawhip", 255, 239, 213 }, - { "blanched almond", 255, 235, 205 }, - { "blanchedalmond", 255, 235, 205 }, - { "bisque", 255, 228, 196 }, - { "peach puff", 255, 218, 185 }, - { "peachpuff", 255, 218, 185 }, - { "navajo white", 255, 222, 173 }, - { "navajowhite", 255, 222, 173 }, - { "moccasin", 255, 228, 181 }, - { "cornsilk", 255, 248, 220 }, - { "ivory", 255, 255, 240 }, - { "lemon chiffon", 255, 250, 205 }, - { "lemonchiffon", 255, 250, 205 }, - { "seashell", 255, 245, 238 }, - { "honeydew", 240, 255, 240 }, - { "mint cream", 245, 255, 250 }, - { "mintcream", 245, 255, 250 }, - { "azure", 240, 255, 255 }, - { "alice blue", 240, 248, 255 }, - { "aliceblue", 240, 248, 255 }, - { "lavender", 230, 230, 250 }, - { "lavender blush", 255, 240, 245 }, - { "lavenderblush", 255, 240, 245 }, - { "misty rose", 255, 228, 225 }, - { "mistyrose", 255, 228, 225 }, - { "white", 255, 255, 255 }, - { "black", 0, 0, 0 }, - { "dark slate gray", 47, 79, 79 }, - { "darkslategray", 47, 79, 79 }, - { "dark slate grey", 47, 79, 79 }, - { "darkslategrey", 47, 79, 79 }, - { "dim gray", 105, 105, 105 }, - { "dimgray", 105, 105, 105 }, - { "dim grey", 105, 105, 105 }, - { "dimgrey", 105, 105, 105 }, - { "slate gray", 112, 128, 144 }, - { "slategray", 112, 128, 144 }, - { "slate grey", 112, 128, 144 }, - { "slategrey", 112, 128, 144 }, - { "light slate gray", 119, 136, 153 }, - { "lightslategray", 119, 136, 153 }, - { "light slate grey", 119, 136, 153 }, - { "lightslategrey", 119, 136, 153 }, - { "gray", 190, 190, 190 }, - { "grey", 190, 190, 190 }, - { "light grey", 211, 211, 211 }, - { "lightgrey", 211, 211, 211 }, - { "light gray", 211, 211, 211 }, - { "lightgray", 211, 211, 211 }, - { "midnight blue", 25, 25, 112 }, - { "midnightblue", 25, 25, 112 }, - { "navy", 0, 0, 128 }, - { "navy blue", 0, 0, 128 }, - { "navyblue", 0, 0, 128 }, - { "cornflower blue", 100, 149, 237 }, - { "cornflowerblue", 100, 149, 237 }, - { "dark slate blue", 72, 61, 139 }, - { "darkslateblue", 72, 61, 139 }, - { "slate blue", 106, 90, 205 }, - { "slateblue", 106, 90, 205 }, - { "medium slate blue", 123, 104, 238 }, - { "mediumslateblue", 123, 104, 238 }, - { "light slate blue", 132, 112, 255 }, - { "lightslateblue", 132, 112, 255 }, - { "medium blue", 0, 0, 205 }, - { "mediumblue", 0, 0, 205 }, - { "royal blue", 65, 105, 225 }, - { "royalblue", 65, 105, 225 }, - { "blue", 0, 0, 255 }, - { "dodger blue", 30, 144, 255 }, - { "dodgerblue", 30, 144, 255 }, - { "deep sky blue", 0, 191, 255 }, - { "deepskyblue", 0, 191, 255 }, - { "sky blue", 135, 206, 235 }, - { "skyblue", 135, 206, 235 }, - { "light sky blue", 135, 206, 250 }, - { "lightskyblue", 135, 206, 250 }, - { "steel blue", 70, 130, 180 }, - { "steelblue", 70, 130, 180 }, - { "light steel blue", 176, 196, 222 }, - { "lightsteelblue", 176, 196, 222 }, - { "light blue", 173, 216, 230 }, - { "lightblue", 173, 216, 230 }, - { "powder blue", 176, 224, 230 }, - { "powderblue", 176, 224, 230 }, - { "pale turquoise", 175, 238, 238 }, - { "paleturquoise", 175, 238, 238 }, - { "dark turquoise", 0, 206, 209 }, - { "darkturquoise", 0, 206, 209 }, - { "medium turquoise", 72, 209, 204 }, - { "mediumturquoise", 72, 209, 204 }, - { "turquoise", 64, 224, 208 }, - { "cyan", 0, 255, 255 }, - { "light cyan", 224, 255, 255 }, - { "lightcyan", 224, 255, 255 }, - { "cadet blue", 95, 158, 160 }, - { "cadetblue", 95, 158, 160 }, - { "medium aquamarine", 102, 205, 170 }, - { "mediumaquamarine", 102, 205, 170 }, - { "aquamarine", 127, 255, 212 }, - { "dark green", 0, 100, 0 }, - { "darkgreen", 0, 100, 0 }, - { "dark olive green", 85, 107, 47 }, - { "darkolivegreen", 85, 107, 47 }, - { "dark sea green", 143, 188, 143 }, - { "darkseagreen", 143, 188, 143 }, - { "sea green", 46, 139, 87 }, - { "seagreen", 46, 139, 87 }, - { "medium sea green", 60, 179, 113 }, - { "mediumseagreen", 60, 179, 113 }, - { "light sea green", 32, 178, 170 }, - { "lightseagreen", 32, 178, 170 }, - { "pale green", 152, 251, 152 }, - { "palegreen", 152, 251, 152 }, - { "spring green", 0, 255, 127 }, - { "springgreen", 0, 255, 127 }, - { "lawn green", 124, 252, 0 }, - { "lawngreen", 124, 252, 0 }, - { "green", 0, 255, 0 }, - { "chartreuse", 127, 255, 0 }, - { "medium spring green", 0, 250, 154 }, - { "mediumspringgreen", 0, 250, 154 }, - { "green yellow", 173, 255, 47 }, - { "greenyellow", 173, 255, 47 }, - { "lime green", 50, 205, 50 }, - { "limegreen", 50, 205, 50 }, - { "yellow green", 154, 205, 50 }, - { "yellowgreen", 154, 205, 50 }, - { "forest green", 34, 139, 34 }, - { "forestgreen", 34, 139, 34 }, - { "olive drab", 107, 142, 35 }, - { "olivedrab", 107, 142, 35 }, - { "dark khaki", 189, 183, 107 }, - { "darkkhaki", 189, 183, 107 }, - { "khaki", 240, 230, 140 }, - { "pale goldenrod", 238, 232, 170 }, - { "palegoldenrod", 238, 232, 170 }, - { "light goldenrod yellow", 250, 250, 210 }, - { "lightgoldenrodyellow", 250, 250, 210 }, - { "light yellow", 255, 255, 224 }, - { "lightyellow", 255, 255, 224 }, - { "yellow", 255, 255, 0 }, - { "gold", 255, 215, 0 }, - { "light goldenrod", 238, 221, 130 }, - { "lightgoldenrod", 238, 221, 130 }, - { "goldenrod", 218, 165, 32 }, - { "dark goldenrod", 184, 134, 11 }, - { "darkgoldenrod", 184, 134, 11 }, - { "rosy brown", 188, 143, 143 }, - { "rosybrown", 188, 143, 143 }, - { "indian red", 205, 92, 92 }, - { "indianred", 205, 92, 92 }, - { "saddle brown", 139, 69, 19 }, - { "saddlebrown", 139, 69, 19 }, - { "sienna", 160, 82, 45 }, - { "peru", 205, 133, 63 }, - { "burlywood", 222, 184, 135 }, - { "beige", 245, 245, 220 }, - { "wheat", 245, 222, 179 }, - { "sandy brown", 244, 164, 96 }, - { "sandybrown", 244, 164, 96 }, - { "tan", 210, 180, 140 }, - { "chocolate", 210, 105, 30 }, - { "firebrick", 178, 34, 34 }, - { "brown", 165, 42, 42 }, - { "dark salmon", 233, 150, 122 }, - { "darksalmon", 233, 150, 122 }, - { "salmon", 250, 128, 114 }, - { "light salmon", 255, 160, 122 }, - { "lightsalmon", 255, 160, 122 }, - { "orange", 255, 165, 0 }, - { "dark orange", 255, 140, 0 }, - { "darkorange", 255, 140, 0 }, - { "coral", 255, 127, 80 }, - { "light coral", 240, 128, 128 }, - { "lightcoral", 240, 128, 128 }, - { "tomato", 255, 99, 71 }, - { "orange red", 255, 69, 0 }, - { "orangered", 255, 69, 0 }, - { "red", 255, 0, 0 }, - { "hot pink", 255, 105, 180 }, - { "hotpink", 255, 105, 180 }, - { "deep pink", 255, 20, 147 }, - { "deeppink", 255, 20, 147 }, - { "pink", 255, 192, 203 }, - { "light pink", 255, 182, 193 }, - { "lightpink", 255, 182, 193 }, - { "pale violet red", 219, 112, 147 }, - { "palevioletred", 219, 112, 147 }, - { "maroon", 176, 48, 96 }, - { "medium violet red", 199, 21, 133 }, - { "mediumvioletred", 199, 21, 133 }, - { "violet red", 208, 32, 144 }, - { "violetred", 208, 32, 144 }, - { "magenta", 255, 0, 255 }, - { "violet", 238, 130, 238 }, - { "plum", 221, 160, 221 }, - { "orchid", 218, 112, 214 }, - { "medium orchid", 186, 85, 211 }, - { "mediumorchid", 186, 85, 211 }, - { "dark orchid", 153, 50, 204 }, - { "darkorchid", 153, 50, 204 }, - { "dark violet", 148, 0, 211 }, - { "darkviolet", 148, 0, 211 }, - { "blue violet", 138, 43, 226 }, - { "blueviolet", 138, 43, 226 }, - { "purple", 160, 32, 240 }, - { "medium purple", 147, 112, 219 }, - { "mediumpurple", 147, 112, 219 }, - { "thistle", 216, 191, 216 }, - { "snow1", 255, 250, 250 }, - { "snow2", 238, 233, 233 }, - { "snow3", 205, 201, 201 }, - { "snow4", 139, 137, 137 }, - { "seashell1", 255, 245, 238 }, - { "seashell2", 238, 229, 222 }, - { "seashell3", 205, 197, 191 }, - { "seashell4", 139, 134, 130 }, - { "antiquewhite1", 255, 239, 219 }, - { "antiquewhite2", 238, 223, 204 }, - { "antiquewhite3", 205, 192, 176 }, - { "antiquewhite4", 139, 131, 120 }, - { "bisque1", 255, 228, 196 }, - { "bisque2", 238, 213, 183 }, - { "bisque3", 205, 183, 158 }, - { "bisque4", 139, 125, 107 }, - { "peachpuff1", 255, 218, 185 }, - { "peachpuff2", 238, 203, 173 }, - { "peachpuff3", 205, 175, 149 }, - { "peachpuff4", 139, 119, 101 }, - { "navajowhite1", 255, 222, 173 }, - { "navajowhite2", 238, 207, 161 }, - { "navajowhite3", 205, 179, 139 }, - { "navajowhite4", 139, 121, 94 }, - { "lemonchiffon1", 255, 250, 205 }, - { "lemonchiffon2", 238, 233, 191 }, - { "lemonchiffon3", 205, 201, 165 }, - { "lemonchiffon4", 139, 137, 112 }, - { "cornsilk1", 255, 248, 220 }, - { "cornsilk2", 238, 232, 205 }, - { "cornsilk3", 205, 200, 177 }, - { "cornsilk4", 139, 136, 120 }, - { "ivory1", 255, 255, 240 }, - { "ivory2", 238, 238, 224 }, - { "ivory3", 205, 205, 193 }, - { "ivory4", 139, 139, 131 }, - { "honeydew1", 240, 255, 240 }, - { "honeydew2", 224, 238, 224 }, - { "honeydew3", 193, 205, 193 }, - { "honeydew4", 131, 139, 131 }, - { "lavenderblush1", 255, 240, 245 }, - { "lavenderblush2", 238, 224, 229 }, - { "lavenderblush3", 205, 193, 197 }, - { "lavenderblush4", 139, 131, 134 }, - { "mistyrose1", 255, 228, 225 }, - { "mistyrose2", 238, 213, 210 }, - { "mistyrose3", 205, 183, 181 }, - { "mistyrose4", 139, 125, 123 }, - { "azure1", 240, 255, 255 }, - { "azure2", 224, 238, 238 }, - { "azure3", 193, 205, 205 }, - { "azure4", 131, 139, 139 }, - { "slateblue1", 131, 111, 255 }, - { "slateblue2", 122, 103, 238 }, - { "slateblue3", 105, 89, 205 }, - { "slateblue4", 71, 60, 139 }, - { "royalblue1", 72, 118, 255 }, - { "royalblue2", 67, 110, 238 }, - { "royalblue3", 58, 95, 205 }, - { "royalblue4", 39, 64, 139 }, - { "blue1", 0, 0, 255 }, - { "blue2", 0, 0, 238 }, - { "blue3", 0, 0, 205 }, - { "blue4", 0, 0, 139 }, - { "dodgerblue1", 30, 144, 255 }, - { "dodgerblue2", 28, 134, 238 }, - { "dodgerblue3", 24, 116, 205 }, - { "dodgerblue4", 16, 78, 139 }, - { "steelblue1", 99, 184, 255 }, - { "steelblue2", 92, 172, 238 }, - { "steelblue3", 79, 148, 205 }, - { "steelblue4", 54, 100, 139 }, - { "deepskyblue1", 0, 191, 255 }, - { "deepskyblue2", 0, 178, 238 }, - { "deepskyblue3", 0, 154, 205 }, - { "deepskyblue4", 0, 104, 139 }, - { "skyblue1", 135, 206, 255 }, - { "skyblue2", 126, 192, 238 }, - { "skyblue3", 108, 166, 205 }, - { "skyblue4", 74, 112, 139 }, - { "lightskyblue1", 176, 226, 255 }, - { "lightskyblue2", 164, 211, 238 }, - { "lightskyblue3", 141, 182, 205 }, - { "lightskyblue4", 96, 123, 139 }, - { "slategray1", 198, 226, 255 }, - { "slategray2", 185, 211, 238 }, - { "slategray3", 159, 182, 205 }, - { "slategray4", 108, 123, 139 }, - { "lightsteelblue1", 202, 225, 255 }, - { "lightsteelblue2", 188, 210, 238 }, - { "lightsteelblue3", 162, 181, 205 }, - { "lightsteelblue4", 110, 123, 139 }, - { "lightblue1", 191, 239, 255 }, - { "lightblue2", 178, 223, 238 }, - { "lightblue3", 154, 192, 205 }, - { "lightblue4", 104, 131, 139 }, - { "lightcyan1", 224, 255, 255 }, - { "lightcyan2", 209, 238, 238 }, - { "lightcyan3", 180, 205, 205 }, - { "lightcyan4", 122, 139, 139 }, - { "paleturquoise1", 187, 255, 255 }, - { "paleturquoise2", 174, 238, 238 }, - { "paleturquoise3", 150, 205, 205 }, - { "paleturquoise4", 102, 139, 139 }, - { "cadetblue1", 152, 245, 255 }, - { "cadetblue2", 142, 229, 238 }, - { "cadetblue3", 122, 197, 205 }, - { "cadetblue4", 83, 134, 139 }, - { "turquoise1", 0, 245, 255 }, - { "turquoise2", 0, 229, 238 }, - { "turquoise3", 0, 197, 205 }, - { "turquoise4", 0, 134, 139 }, - { "cyan1", 0, 255, 255 }, - { "cyan2", 0, 238, 238 }, - { "cyan3", 0, 205, 205 }, - { "cyan4", 0, 139, 139 }, - { "darkslategray1", 151, 255, 255 }, - { "darkslategray2", 141, 238, 238 }, - { "darkslategray3", 121, 205, 205 }, - { "darkslategray4", 82, 139, 139 }, - { "aquamarine1", 127, 255, 212 }, - { "aquamarine2", 118, 238, 198 }, - { "aquamarine3", 102, 205, 170 }, - { "aquamarine4", 69, 139, 116 }, - { "darkseagreen1", 193, 255, 193 }, - { "darkseagreen2", 180, 238, 180 }, - { "darkseagreen3", 155, 205, 155 }, - { "darkseagreen4", 105, 139, 105 }, - { "seagreen1", 84, 255, 159 }, - { "seagreen2", 78, 238, 148 }, - { "seagreen3", 67, 205, 128 }, - { "seagreen4", 46, 139, 87 }, - { "palegreen1", 154, 255, 154 }, - { "palegreen2", 144, 238, 144 }, - { "palegreen3", 124, 205, 124 }, - { "palegreen4", 84, 139, 84 }, - { "springgreen1", 0, 255, 127 }, - { "springgreen2", 0, 238, 118 }, - { "springgreen3", 0, 205, 102 }, - { "springgreen4", 0, 139, 69 }, - { "green1", 0, 255, 0 }, - { "green2", 0, 238, 0 }, - { "green3", 0, 205, 0 }, - { "green4", 0, 139, 0 }, - { "chartreuse1", 127, 255, 0 }, - { "chartreuse2", 118, 238, 0 }, - { "chartreuse3", 102, 205, 0 }, - { "chartreuse4", 69, 139, 0 }, - { "olivedrab1", 192, 255, 62 }, - { "olivedrab2", 179, 238, 58 }, - { "olivedrab3", 154, 205, 50 }, - { "olivedrab4", 105, 139, 34 }, - { "darkolivegreen1", 202, 255, 112 }, - { "darkolivegreen2", 188, 238, 104 }, - { "darkolivegreen3", 162, 205, 90 }, - { "darkolivegreen4", 110, 139, 61 }, - { "khaki1", 255, 246, 143 }, - { "khaki2", 238, 230, 133 }, - { "khaki3", 205, 198, 115 }, - { "khaki4", 139, 134, 78 }, - { "lightgoldenrod1", 255, 236, 139 }, - { "lightgoldenrod2", 238, 220, 130 }, - { "lightgoldenrod3", 205, 190, 112 }, - { "lightgoldenrod4", 139, 129, 76 }, - { "lightyellow1", 255, 255, 224 }, - { "lightyellow2", 238, 238, 209 }, - { "lightyellow3", 205, 205, 180 }, - { "lightyellow4", 139, 139, 122 }, - { "yellow1", 255, 255, 0 }, - { "yellow2", 238, 238, 0 }, - { "yellow3", 205, 205, 0 }, - { "yellow4", 139, 139, 0 }, - { "gold1", 255, 215, 0 }, - { "gold2", 238, 201, 0 }, - { "gold3", 205, 173, 0 }, - { "gold4", 139, 117, 0 }, - { "goldenrod1", 255, 193, 37 }, - { "goldenrod2", 238, 180, 34 }, - { "goldenrod3", 205, 155, 29 }, - { "goldenrod4", 139, 105, 20 }, - { "darkgoldenrod1", 255, 185, 15 }, - { "darkgoldenrod2", 238, 173, 14 }, - { "darkgoldenrod3", 205, 149, 12 }, - { "darkgoldenrod4", 139, 101, 8 }, - { "rosybrown1", 255, 193, 193 }, - { "rosybrown2", 238, 180, 180 }, - { "rosybrown3", 205, 155, 155 }, - { "rosybrown4", 139, 105, 105 }, - { "indianred1", 255, 106, 106 }, - { "indianred2", 238, 99, 99 }, - { "indianred3", 205, 85, 85 }, - { "indianred4", 139, 58, 58 }, - { "sienna1", 255, 130, 71 }, - { "sienna2", 238, 121, 66 }, - { "sienna3", 205, 104, 57 }, - { "sienna4", 139, 71, 38 }, - { "burlywood1", 255, 211, 155 }, - { "burlywood2", 238, 197, 145 }, - { "burlywood3", 205, 170, 125 }, - { "burlywood4", 139, 115, 85 }, - { "wheat1", 255, 231, 186 }, - { "wheat2", 238, 216, 174 }, - { "wheat3", 205, 186, 150 }, - { "wheat4", 139, 126, 102 }, - { "tan1", 255, 165, 79 }, - { "tan2", 238, 154, 73 }, - { "tan3", 205, 133, 63 }, - { "tan4", 139, 90, 43 }, - { "chocolate1", 255, 127, 36 }, - { "chocolate2", 238, 118, 33 }, - { "chocolate3", 205, 102, 29 }, - { "chocolate4", 139, 69, 19 }, - { "firebrick1", 255, 48, 48 }, - { "firebrick2", 238, 44, 44 }, - { "firebrick3", 205, 38, 38 }, - { "firebrick4", 139, 26, 26 }, - { "brown1", 255, 64, 64 }, - { "brown2", 238, 59, 59 }, - { "brown3", 205, 51, 51 }, - { "brown4", 139, 35, 35 }, - { "salmon1", 255, 140, 105 }, - { "salmon2", 238, 130, 98 }, - { "salmon3", 205, 112, 84 }, - { "salmon4", 139, 76, 57 }, - { "lightsalmon1", 255, 160, 122 }, - { "lightsalmon2", 238, 149, 114 }, - { "lightsalmon3", 205, 129, 98 }, - { "lightsalmon4", 139, 87, 66 }, - { "orange1", 255, 165, 0 }, - { "orange2", 238, 154, 0 }, - { "orange3", 205, 133, 0 }, - { "orange4", 139, 90, 0 }, - { "darkorange1", 255, 127, 0 }, - { "darkorange2", 238, 118, 0 }, - { "darkorange3", 205, 102, 0 }, - { "darkorange4", 139, 69, 0 }, - { "coral1", 255, 114, 86 }, - { "coral2", 238, 106, 80 }, - { "coral3", 205, 91, 69 }, - { "coral4", 139, 62, 47 }, - { "tomato1", 255, 99, 71 }, - { "tomato2", 238, 92, 66 }, - { "tomato3", 205, 79, 57 }, - { "tomato4", 139, 54, 38 }, - { "orangered1", 255, 69, 0 }, - { "orangered2", 238, 64, 0 }, - { "orangered3", 205, 55, 0 }, - { "orangered4", 139, 37, 0 }, - { "red1", 255, 0, 0 }, - { "red2", 238, 0, 0 }, - { "red3", 205, 0, 0 }, - { "red4", 139, 0, 0 }, - { "deeppink1", 255, 20, 147 }, - { "deeppink2", 238, 18, 137 }, - { "deeppink3", 205, 16, 118 }, - { "deeppink4", 139, 10, 80 }, - { "hotpink1", 255, 110, 180 }, - { "hotpink2", 238, 106, 167 }, - { "hotpink3", 205, 96, 144 }, - { "hotpink4", 139, 58, 98 }, - { "pink1", 255, 181, 197 }, - { "pink2", 238, 169, 184 }, - { "pink3", 205, 145, 158 }, - { "pink4", 139, 99, 108 }, - { "lightpink1", 255, 174, 185 }, - { "lightpink2", 238, 162, 173 }, - { "lightpink3", 205, 140, 149 }, - { "lightpink4", 139, 95, 101 }, - { "palevioletred1", 255, 130, 171 }, - { "palevioletred2", 238, 121, 159 }, - { "palevioletred3", 205, 104, 137 }, - { "palevioletred4", 139, 71, 93 }, - { "maroon1", 255, 52, 179 }, - { "maroon2", 238, 48, 167 }, - { "maroon3", 205, 41, 144 }, - { "maroon4", 139, 28, 98 }, - { "violetred1", 255, 62, 150 }, - { "violetred2", 238, 58, 140 }, - { "violetred3", 205, 50, 120 }, - { "violetred4", 139, 34, 82 }, - { "magenta1", 255, 0, 255 }, - { "magenta2", 238, 0, 238 }, - { "magenta3", 205, 0, 205 }, - { "magenta4", 139, 0, 139 }, - { "orchid1", 255, 131, 250 }, - { "orchid2", 238, 122, 233 }, - { "orchid3", 205, 105, 201 }, - { "orchid4", 139, 71, 137 }, - { "plum1", 255, 187, 255 }, - { "plum2", 238, 174, 238 }, - { "plum3", 205, 150, 205 }, - { "plum4", 139, 102, 139 }, - { "mediumorchid1", 224, 102, 255 }, - { "mediumorchid2", 209, 95, 238 }, - { "mediumorchid3", 180, 82, 205 }, - { "mediumorchid4", 122, 55, 139 }, - { "darkorchid1", 191, 62, 255 }, - { "darkorchid2", 178, 58, 238 }, - { "darkorchid3", 154, 50, 205 }, - { "darkorchid4", 104, 34, 139 }, - { "purple1", 155, 48, 255 }, - { "purple2", 145, 44, 238 }, - { "purple3", 125, 38, 205 }, - { "purple4", 85, 26, 139 }, - { "mediumpurple1", 171, 130, 255 }, - { "mediumpurple2", 159, 121, 238 }, - { "mediumpurple3", 137, 104, 205 }, - { "mediumpurple4", 93, 71, 139 }, - { "thistle1", 255, 225, 255 }, - { "thistle2", 238, 210, 238 }, - { "thistle3", 205, 181, 205 }, - { "thistle4", 139, 123, 139 }, - { "gray0", 0, 0, 0 }, - { "grey0", 0, 0, 0 }, - { "gray1", 3, 3, 3 }, - { "grey1", 3, 3, 3 }, - { "gray2", 5, 5, 5 }, - { "grey2", 5, 5, 5 }, - { "gray3", 8, 8, 8 }, - { "grey3", 8, 8, 8 }, - { "gray4", 10, 10, 10 }, - { "grey4", 10, 10, 10 }, - { "gray5", 13, 13, 13 }, - { "grey5", 13, 13, 13 }, - { "gray6", 15, 15, 15 }, - { "grey6", 15, 15, 15 }, - { "gray7", 18, 18, 18 }, - { "grey7", 18, 18, 18 }, - { "gray8", 20, 20, 20 }, - { "grey8", 20, 20, 20 }, - { "gray9", 23, 23, 23 }, - { "grey9", 23, 23, 23 }, - { "gray10", 26, 26, 26 }, - { "grey10", 26, 26, 26 }, - { "gray11", 28, 28, 28 }, - { "grey11", 28, 28, 28 }, - { "gray12", 31, 31, 31 }, - { "grey12", 31, 31, 31 }, - { "gray13", 33, 33, 33 }, - { "grey13", 33, 33, 33 }, - { "gray14", 36, 36, 36 }, - { "grey14", 36, 36, 36 }, - { "gray15", 38, 38, 38 }, - { "grey15", 38, 38, 38 }, - { "gray16", 41, 41, 41 }, - { "grey16", 41, 41, 41 }, - { "gray17", 43, 43, 43 }, - { "grey17", 43, 43, 43 }, - { "gray18", 46, 46, 46 }, - { "grey18", 46, 46, 46 }, - { "gray19", 48, 48, 48 }, - { "grey19", 48, 48, 48 }, - { "gray20", 51, 51, 51 }, - { "grey20", 51, 51, 51 }, - { "gray21", 54, 54, 54 }, - { "grey21", 54, 54, 54 }, - { "gray22", 56, 56, 56 }, - { "grey22", 56, 56, 56 }, - { "gray23", 59, 59, 59 }, - { "grey23", 59, 59, 59 }, - { "gray24", 61, 61, 61 }, - { "grey24", 61, 61, 61 }, - { "gray25", 64, 64, 64 }, - { "grey25", 64, 64, 64 }, - { "gray26", 66, 66, 66 }, - { "grey26", 66, 66, 66 }, - { "gray27", 69, 69, 69 }, - { "grey27", 69, 69, 69 }, - { "gray28", 71, 71, 71 }, - { "grey28", 71, 71, 71 }, - { "gray29", 74, 74, 74 }, - { "grey29", 74, 74, 74 }, - { "gray30", 77, 77, 77 }, - { "grey30", 77, 77, 77 }, - { "gray31", 79, 79, 79 }, - { "grey31", 79, 79, 79 }, - { "gray32", 82, 82, 82 }, - { "grey32", 82, 82, 82 }, - { "gray33", 84, 84, 84 }, - { "grey33", 84, 84, 84 }, - { "gray34", 87, 87, 87 }, - { "grey34", 87, 87, 87 }, - { "gray35", 89, 89, 89 }, - { "grey35", 89, 89, 89 }, - { "gray36", 92, 92, 92 }, - { "grey36", 92, 92, 92 }, - { "gray37", 94, 94, 94 }, - { "grey37", 94, 94, 94 }, - { "gray38", 97, 97, 97 }, - { "grey38", 97, 97, 97 }, - { "gray39", 99, 99, 99 }, - { "grey39", 99, 99, 99 }, - { "gray40", 102, 102, 102 }, - { "grey40", 102, 102, 102 }, - { "gray41", 105, 105, 105 }, - { "grey41", 105, 105, 105 }, - { "gray42", 107, 107, 107 }, - { "grey42", 107, 107, 107 }, - { "gray43", 110, 110, 110 }, - { "grey43", 110, 110, 110 }, - { "gray44", 112, 112, 112 }, - { "grey44", 112, 112, 112 }, - { "gray45", 115, 115, 115 }, - { "grey45", 115, 115, 115 }, - { "gray46", 117, 117, 117 }, - { "grey46", 117, 117, 117 }, - { "gray47", 120, 120, 120 }, - { "grey47", 120, 120, 120 }, - { "gray48", 122, 122, 122 }, - { "grey48", 122, 122, 122 }, - { "gray49", 125, 125, 125 }, - { "grey49", 125, 125, 125 }, - { "gray50", 127, 127, 127 }, - { "grey50", 127, 127, 127 }, - { "gray51", 130, 130, 130 }, - { "grey51", 130, 130, 130 }, - { "gray52", 133, 133, 133 }, - { "grey52", 133, 133, 133 }, - { "gray53", 135, 135, 135 }, - { "grey53", 135, 135, 135 }, - { "gray54", 138, 138, 138 }, - { "grey54", 138, 138, 138 }, - { "gray55", 140, 140, 140 }, - { "grey55", 140, 140, 140 }, - { "gray56", 143, 143, 143 }, - { "grey56", 143, 143, 143 }, - { "gray57", 145, 145, 145 }, - { "grey57", 145, 145, 145 }, - { "gray58", 148, 148, 148 }, - { "grey58", 148, 148, 148 }, - { "gray59", 150, 150, 150 }, - { "grey59", 150, 150, 150 }, - { "gray60", 153, 153, 153 }, - { "grey60", 153, 153, 153 }, - { "gray61", 156, 156, 156 }, - { "grey61", 156, 156, 156 }, - { "gray62", 158, 158, 158 }, - { "grey62", 158, 158, 158 }, - { "gray63", 161, 161, 161 }, - { "grey63", 161, 161, 161 }, - { "gray64", 163, 163, 163 }, - { "grey64", 163, 163, 163 }, - { "gray65", 166, 166, 166 }, - { "grey65", 166, 166, 166 }, - { "gray66", 168, 168, 168 }, - { "grey66", 168, 168, 168 }, - { "gray67", 171, 171, 171 }, - { "grey67", 171, 171, 171 }, - { "gray68", 173, 173, 173 }, - { "grey68", 173, 173, 173 }, - { "gray69", 176, 176, 176 }, - { "grey69", 176, 176, 176 }, - { "gray70", 179, 179, 179 }, - { "grey70", 179, 179, 179 }, - { "gray71", 181, 181, 181 }, - { "grey71", 181, 181, 181 }, - { "gray72", 184, 184, 184 }, - { "grey72", 184, 184, 184 }, - { "gray73", 186, 186, 186 }, - { "grey73", 186, 186, 186 }, - { "gray74", 189, 189, 189 }, - { "grey74", 189, 189, 189 }, - { "gray75", 191, 191, 191 }, - { "grey75", 191, 191, 191 }, - { "gray76", 194, 194, 194 }, - { "grey76", 194, 194, 194 }, - { "gray77", 196, 196, 196 }, - { "grey77", 196, 196, 196 }, - { "gray78", 199, 199, 199 }, - { "grey78", 199, 199, 199 }, - { "gray79", 201, 201, 201 }, - { "grey79", 201, 201, 201 }, - { "gray80", 204, 204, 204 }, - { "grey80", 204, 204, 204 }, - { "gray81", 207, 207, 207 }, - { "grey81", 207, 207, 207 }, - { "gray82", 209, 209, 209 }, - { "grey82", 209, 209, 209 }, - { "gray83", 212, 212, 212 }, - { "grey83", 212, 212, 212 }, - { "gray84", 214, 214, 214 }, - { "grey84", 214, 214, 214 }, - { "gray85", 217, 217, 217 }, - { "grey85", 217, 217, 217 }, - { "gray86", 219, 219, 219 }, - { "grey86", 219, 219, 219 }, - { "gray87", 222, 222, 222 }, - { "grey87", 222, 222, 222 }, - { "gray88", 224, 224, 224 }, - { "grey88", 224, 224, 224 }, - { "gray89", 227, 227, 227 }, - { "grey89", 227, 227, 227 }, - { "gray90", 229, 229, 229 }, - { "grey90", 229, 229, 229 }, - { "gray91", 232, 232, 232 }, - { "grey91", 232, 232, 232 }, - { "gray92", 235, 235, 235 }, - { "grey92", 235, 235, 235 }, - { "gray93", 237, 237, 237 }, - { "grey93", 237, 237, 237 }, - { "gray94", 240, 240, 240 }, - { "grey94", 240, 240, 240 }, - { "gray95", 242, 242, 242 }, - { "grey95", 242, 242, 242 }, - { "gray96", 245, 245, 245 }, - { "grey96", 245, 245, 245 }, - { "gray97", 247, 247, 247 }, - { "grey97", 247, 247, 247 }, - { "gray98", 250, 250, 250 }, - { "grey98", 250, 250, 250 }, - { "gray99", 252, 252, 252 }, - { "grey99", 252, 252, 252 }, - { "gray100", 255, 255, 255 }, - { "grey100", 255, 255, 255 }, - { nullptr, 0, 0, 0 } -}; +} color_lib[] = {{"snow", 255, 250, 250}, + {"ghost white", 248, 248, 255}, + {"ghostwhite", 248, 248, 255}, + {"white smoke", 245, 245, 245}, + {"whitesmoke", 245, 245, 245}, + {"gainsboro", 220, 220, 220}, + {"floral white", 255, 250, 240}, + {"floralwhite", 255, 250, 240}, + {"old lace", 253, 245, 230}, + {"oldlace", 253, 245, 230}, + {"linen", 250, 240, 230}, + {"antique white", 250, 235, 215}, + {"antiquewhite", 250, 235, 215}, + {"papaya whip", 255, 239, 213}, + {"papayawhip", 255, 239, 213}, + {"blanched almond", 255, 235, 205}, + {"blanchedalmond", 255, 235, 205}, + {"bisque", 255, 228, 196}, + {"peach puff", 255, 218, 185}, + {"peachpuff", 255, 218, 185}, + {"navajo white", 255, 222, 173}, + {"navajowhite", 255, 222, 173}, + {"moccasin", 255, 228, 181}, + {"cornsilk", 255, 248, 220}, + {"ivory", 255, 255, 240}, + {"lemon chiffon", 255, 250, 205}, + {"lemonchiffon", 255, 250, 205}, + {"seashell", 255, 245, 238}, + {"honeydew", 240, 255, 240}, + {"mint cream", 245, 255, 250}, + {"mintcream", 245, 255, 250}, + {"azure", 240, 255, 255}, + {"alice blue", 240, 248, 255}, + {"aliceblue", 240, 248, 255}, + {"lavender", 230, 230, 250}, + {"lavender blush", 255, 240, 245}, + {"lavenderblush", 255, 240, 245}, + {"misty rose", 255, 228, 225}, + {"mistyrose", 255, 228, 225}, + {"white", 255, 255, 255}, + {"black", 0, 0, 0}, + {"dark slate gray", 47, 79, 79}, + {"darkslategray", 47, 79, 79}, + {"dark slate grey", 47, 79, 79}, + {"darkslategrey", 47, 79, 79}, + {"dim gray", 105, 105, 105}, + {"dimgray", 105, 105, 105}, + {"dim grey", 105, 105, 105}, + {"dimgrey", 105, 105, 105}, + {"slate gray", 112, 128, 144}, + {"slategray", 112, 128, 144}, + {"slate grey", 112, 128, 144}, + {"slategrey", 112, 128, 144}, + {"light slate gray", 119, 136, 153}, + {"lightslategray", 119, 136, 153}, + {"light slate grey", 119, 136, 153}, + {"lightslategrey", 119, 136, 153}, + {"gray", 190, 190, 190}, + {"grey", 190, 190, 190}, + {"light grey", 211, 211, 211}, + {"lightgrey", 211, 211, 211}, + {"light gray", 211, 211, 211}, + {"lightgray", 211, 211, 211}, + {"midnight blue", 25, 25, 112}, + {"midnightblue", 25, 25, 112}, + {"navy", 0, 0, 128}, + {"navy blue", 0, 0, 128}, + {"navyblue", 0, 0, 128}, + {"cornflower blue", 100, 149, 237}, + {"cornflowerblue", 100, 149, 237}, + {"dark slate blue", 72, 61, 139}, + {"darkslateblue", 72, 61, 139}, + {"slate blue", 106, 90, 205}, + {"slateblue", 106, 90, 205}, + {"medium slate blue", 123, 104, 238}, + {"mediumslateblue", 123, 104, 238}, + {"light slate blue", 132, 112, 255}, + {"lightslateblue", 132, 112, 255}, + {"medium blue", 0, 0, 205}, + {"mediumblue", 0, 0, 205}, + {"royal blue", 65, 105, 225}, + {"royalblue", 65, 105, 225}, + {"blue", 0, 0, 255}, + {"dodger blue", 30, 144, 255}, + {"dodgerblue", 30, 144, 255}, + {"deep sky blue", 0, 191, 255}, + {"deepskyblue", 0, 191, 255}, + {"sky blue", 135, 206, 235}, + {"skyblue", 135, 206, 235}, + {"light sky blue", 135, 206, 250}, + {"lightskyblue", 135, 206, 250}, + {"steel blue", 70, 130, 180}, + {"steelblue", 70, 130, 180}, + {"light steel blue", 176, 196, 222}, + {"lightsteelblue", 176, 196, 222}, + {"light blue", 173, 216, 230}, + {"lightblue", 173, 216, 230}, + {"powder blue", 176, 224, 230}, + {"powderblue", 176, 224, 230}, + {"pale turquoise", 175, 238, 238}, + {"paleturquoise", 175, 238, 238}, + {"dark turquoise", 0, 206, 209}, + {"darkturquoise", 0, 206, 209}, + {"medium turquoise", 72, 209, 204}, + {"mediumturquoise", 72, 209, 204}, + {"turquoise", 64, 224, 208}, + {"cyan", 0, 255, 255}, + {"light cyan", 224, 255, 255}, + {"lightcyan", 224, 255, 255}, + {"cadet blue", 95, 158, 160}, + {"cadetblue", 95, 158, 160}, + {"medium aquamarine", 102, 205, 170}, + {"mediumaquamarine", 102, 205, 170}, + {"aquamarine", 127, 255, 212}, + {"dark green", 0, 100, 0}, + {"darkgreen", 0, 100, 0}, + {"dark olive green", 85, 107, 47}, + {"darkolivegreen", 85, 107, 47}, + {"dark sea green", 143, 188, 143}, + {"darkseagreen", 143, 188, 143}, + {"sea green", 46, 139, 87}, + {"seagreen", 46, 139, 87}, + {"medium sea green", 60, 179, 113}, + {"mediumseagreen", 60, 179, 113}, + {"light sea green", 32, 178, 170}, + {"lightseagreen", 32, 178, 170}, + {"pale green", 152, 251, 152}, + {"palegreen", 152, 251, 152}, + {"spring green", 0, 255, 127}, + {"springgreen", 0, 255, 127}, + {"lawn green", 124, 252, 0}, + {"lawngreen", 124, 252, 0}, + {"green", 0, 255, 0}, + {"chartreuse", 127, 255, 0}, + {"medium spring green", 0, 250, 154}, + {"mediumspringgreen", 0, 250, 154}, + {"green yellow", 173, 255, 47}, + {"greenyellow", 173, 255, 47}, + {"lime green", 50, 205, 50}, + {"limegreen", 50, 205, 50}, + {"yellow green", 154, 205, 50}, + {"yellowgreen", 154, 205, 50}, + {"forest green", 34, 139, 34}, + {"forestgreen", 34, 139, 34}, + {"olive drab", 107, 142, 35}, + {"olivedrab", 107, 142, 35}, + {"dark khaki", 189, 183, 107}, + {"darkkhaki", 189, 183, 107}, + {"khaki", 240, 230, 140}, + {"pale goldenrod", 238, 232, 170}, + {"palegoldenrod", 238, 232, 170}, + {"light goldenrod yellow", 250, 250, 210}, + {"lightgoldenrodyellow", 250, 250, 210}, + {"light yellow", 255, 255, 224}, + {"lightyellow", 255, 255, 224}, + {"yellow", 255, 255, 0}, + {"gold", 255, 215, 0}, + {"light goldenrod", 238, 221, 130}, + {"lightgoldenrod", 238, 221, 130}, + {"goldenrod", 218, 165, 32}, + {"dark goldenrod", 184, 134, 11}, + {"darkgoldenrod", 184, 134, 11}, + {"rosy brown", 188, 143, 143}, + {"rosybrown", 188, 143, 143}, + {"indian red", 205, 92, 92}, + {"indianred", 205, 92, 92}, + {"saddle brown", 139, 69, 19}, + {"saddlebrown", 139, 69, 19}, + {"sienna", 160, 82, 45}, + {"peru", 205, 133, 63}, + {"burlywood", 222, 184, 135}, + {"beige", 245, 245, 220}, + {"wheat", 245, 222, 179}, + {"sandy brown", 244, 164, 96}, + {"sandybrown", 244, 164, 96}, + {"tan", 210, 180, 140}, + {"chocolate", 210, 105, 30}, + {"firebrick", 178, 34, 34}, + {"brown", 165, 42, 42}, + {"dark salmon", 233, 150, 122}, + {"darksalmon", 233, 150, 122}, + {"salmon", 250, 128, 114}, + {"light salmon", 255, 160, 122}, + {"lightsalmon", 255, 160, 122}, + {"orange", 255, 165, 0}, + {"dark orange", 255, 140, 0}, + {"darkorange", 255, 140, 0}, + {"coral", 255, 127, 80}, + {"light coral", 240, 128, 128}, + {"lightcoral", 240, 128, 128}, + {"tomato", 255, 99, 71}, + {"orange red", 255, 69, 0}, + {"orangered", 255, 69, 0}, + {"red", 255, 0, 0}, + {"hot pink", 255, 105, 180}, + {"hotpink", 255, 105, 180}, + {"deep pink", 255, 20, 147}, + {"deeppink", 255, 20, 147}, + {"pink", 255, 192, 203}, + {"light pink", 255, 182, 193}, + {"lightpink", 255, 182, 193}, + {"pale violet red", 219, 112, 147}, + {"palevioletred", 219, 112, 147}, + {"maroon", 176, 48, 96}, + {"medium violet red", 199, 21, 133}, + {"mediumvioletred", 199, 21, 133}, + {"violet red", 208, 32, 144}, + {"violetred", 208, 32, 144}, + {"magenta", 255, 0, 255}, + {"violet", 238, 130, 238}, + {"plum", 221, 160, 221}, + {"orchid", 218, 112, 214}, + {"medium orchid", 186, 85, 211}, + {"mediumorchid", 186, 85, 211}, + {"dark orchid", 153, 50, 204}, + {"darkorchid", 153, 50, 204}, + {"dark violet", 148, 0, 211}, + {"darkviolet", 148, 0, 211}, + {"blue violet", 138, 43, 226}, + {"blueviolet", 138, 43, 226}, + {"purple", 160, 32, 240}, + {"medium purple", 147, 112, 219}, + {"mediumpurple", 147, 112, 219}, + {"thistle", 216, 191, 216}, + {"snow1", 255, 250, 250}, + {"snow2", 238, 233, 233}, + {"snow3", 205, 201, 201}, + {"snow4", 139, 137, 137}, + {"seashell1", 255, 245, 238}, + {"seashell2", 238, 229, 222}, + {"seashell3", 205, 197, 191}, + {"seashell4", 139, 134, 130}, + {"antiquewhite1", 255, 239, 219}, + {"antiquewhite2", 238, 223, 204}, + {"antiquewhite3", 205, 192, 176}, + {"antiquewhite4", 139, 131, 120}, + {"bisque1", 255, 228, 196}, + {"bisque2", 238, 213, 183}, + {"bisque3", 205, 183, 158}, + {"bisque4", 139, 125, 107}, + {"peachpuff1", 255, 218, 185}, + {"peachpuff2", 238, 203, 173}, + {"peachpuff3", 205, 175, 149}, + {"peachpuff4", 139, 119, 101}, + {"navajowhite1", 255, 222, 173}, + {"navajowhite2", 238, 207, 161}, + {"navajowhite3", 205, 179, 139}, + {"navajowhite4", 139, 121, 94}, + {"lemonchiffon1", 255, 250, 205}, + {"lemonchiffon2", 238, 233, 191}, + {"lemonchiffon3", 205, 201, 165}, + {"lemonchiffon4", 139, 137, 112}, + {"cornsilk1", 255, 248, 220}, + {"cornsilk2", 238, 232, 205}, + {"cornsilk3", 205, 200, 177}, + {"cornsilk4", 139, 136, 120}, + {"ivory1", 255, 255, 240}, + {"ivory2", 238, 238, 224}, + {"ivory3", 205, 205, 193}, + {"ivory4", 139, 139, 131}, + {"honeydew1", 240, 255, 240}, + {"honeydew2", 224, 238, 224}, + {"honeydew3", 193, 205, 193}, + {"honeydew4", 131, 139, 131}, + {"lavenderblush1", 255, 240, 245}, + {"lavenderblush2", 238, 224, 229}, + {"lavenderblush3", 205, 193, 197}, + {"lavenderblush4", 139, 131, 134}, + {"mistyrose1", 255, 228, 225}, + {"mistyrose2", 238, 213, 210}, + {"mistyrose3", 205, 183, 181}, + {"mistyrose4", 139, 125, 123}, + {"azure1", 240, 255, 255}, + {"azure2", 224, 238, 238}, + {"azure3", 193, 205, 205}, + {"azure4", 131, 139, 139}, + {"slateblue1", 131, 111, 255}, + {"slateblue2", 122, 103, 238}, + {"slateblue3", 105, 89, 205}, + {"slateblue4", 71, 60, 139}, + {"royalblue1", 72, 118, 255}, + {"royalblue2", 67, 110, 238}, + {"royalblue3", 58, 95, 205}, + {"royalblue4", 39, 64, 139}, + {"blue1", 0, 0, 255}, + {"blue2", 0, 0, 238}, + {"blue3", 0, 0, 205}, + {"blue4", 0, 0, 139}, + {"dodgerblue1", 30, 144, 255}, + {"dodgerblue2", 28, 134, 238}, + {"dodgerblue3", 24, 116, 205}, + {"dodgerblue4", 16, 78, 139}, + {"steelblue1", 99, 184, 255}, + {"steelblue2", 92, 172, 238}, + {"steelblue3", 79, 148, 205}, + {"steelblue4", 54, 100, 139}, + {"deepskyblue1", 0, 191, 255}, + {"deepskyblue2", 0, 178, 238}, + {"deepskyblue3", 0, 154, 205}, + {"deepskyblue4", 0, 104, 139}, + {"skyblue1", 135, 206, 255}, + {"skyblue2", 126, 192, 238}, + {"skyblue3", 108, 166, 205}, + {"skyblue4", 74, 112, 139}, + {"lightskyblue1", 176, 226, 255}, + {"lightskyblue2", 164, 211, 238}, + {"lightskyblue3", 141, 182, 205}, + {"lightskyblue4", 96, 123, 139}, + {"slategray1", 198, 226, 255}, + {"slategray2", 185, 211, 238}, + {"slategray3", 159, 182, 205}, + {"slategray4", 108, 123, 139}, + {"lightsteelblue1", 202, 225, 255}, + {"lightsteelblue2", 188, 210, 238}, + {"lightsteelblue3", 162, 181, 205}, + {"lightsteelblue4", 110, 123, 139}, + {"lightblue1", 191, 239, 255}, + {"lightblue2", 178, 223, 238}, + {"lightblue3", 154, 192, 205}, + {"lightblue4", 104, 131, 139}, + {"lightcyan1", 224, 255, 255}, + {"lightcyan2", 209, 238, 238}, + {"lightcyan3", 180, 205, 205}, + {"lightcyan4", 122, 139, 139}, + {"paleturquoise1", 187, 255, 255}, + {"paleturquoise2", 174, 238, 238}, + {"paleturquoise3", 150, 205, 205}, + {"paleturquoise4", 102, 139, 139}, + {"cadetblue1", 152, 245, 255}, + {"cadetblue2", 142, 229, 238}, + {"cadetblue3", 122, 197, 205}, + {"cadetblue4", 83, 134, 139}, + {"turquoise1", 0, 245, 255}, + {"turquoise2", 0, 229, 238}, + {"turquoise3", 0, 197, 205}, + {"turquoise4", 0, 134, 139}, + {"cyan1", 0, 255, 255}, + {"cyan2", 0, 238, 238}, + {"cyan3", 0, 205, 205}, + {"cyan4", 0, 139, 139}, + {"darkslategray1", 151, 255, 255}, + {"darkslategray2", 141, 238, 238}, + {"darkslategray3", 121, 205, 205}, + {"darkslategray4", 82, 139, 139}, + {"aquamarine1", 127, 255, 212}, + {"aquamarine2", 118, 238, 198}, + {"aquamarine3", 102, 205, 170}, + {"aquamarine4", 69, 139, 116}, + {"darkseagreen1", 193, 255, 193}, + {"darkseagreen2", 180, 238, 180}, + {"darkseagreen3", 155, 205, 155}, + {"darkseagreen4", 105, 139, 105}, + {"seagreen1", 84, 255, 159}, + {"seagreen2", 78, 238, 148}, + {"seagreen3", 67, 205, 128}, + {"seagreen4", 46, 139, 87}, + {"palegreen1", 154, 255, 154}, + {"palegreen2", 144, 238, 144}, + {"palegreen3", 124, 205, 124}, + {"palegreen4", 84, 139, 84}, + {"springgreen1", 0, 255, 127}, + {"springgreen2", 0, 238, 118}, + {"springgreen3", 0, 205, 102}, + {"springgreen4", 0, 139, 69}, + {"green1", 0, 255, 0}, + {"green2", 0, 238, 0}, + {"green3", 0, 205, 0}, + {"green4", 0, 139, 0}, + {"chartreuse1", 127, 255, 0}, + {"chartreuse2", 118, 238, 0}, + {"chartreuse3", 102, 205, 0}, + {"chartreuse4", 69, 139, 0}, + {"olivedrab1", 192, 255, 62}, + {"olivedrab2", 179, 238, 58}, + {"olivedrab3", 154, 205, 50}, + {"olivedrab4", 105, 139, 34}, + {"darkolivegreen1", 202, 255, 112}, + {"darkolivegreen2", 188, 238, 104}, + {"darkolivegreen3", 162, 205, 90}, + {"darkolivegreen4", 110, 139, 61}, + {"khaki1", 255, 246, 143}, + {"khaki2", 238, 230, 133}, + {"khaki3", 205, 198, 115}, + {"khaki4", 139, 134, 78}, + {"lightgoldenrod1", 255, 236, 139}, + {"lightgoldenrod2", 238, 220, 130}, + {"lightgoldenrod3", 205, 190, 112}, + {"lightgoldenrod4", 139, 129, 76}, + {"lightyellow1", 255, 255, 224}, + {"lightyellow2", 238, 238, 209}, + {"lightyellow3", 205, 205, 180}, + {"lightyellow4", 139, 139, 122}, + {"yellow1", 255, 255, 0}, + {"yellow2", 238, 238, 0}, + {"yellow3", 205, 205, 0}, + {"yellow4", 139, 139, 0}, + {"gold1", 255, 215, 0}, + {"gold2", 238, 201, 0}, + {"gold3", 205, 173, 0}, + {"gold4", 139, 117, 0}, + {"goldenrod1", 255, 193, 37}, + {"goldenrod2", 238, 180, 34}, + {"goldenrod3", 205, 155, 29}, + {"goldenrod4", 139, 105, 20}, + {"darkgoldenrod1", 255, 185, 15}, + {"darkgoldenrod2", 238, 173, 14}, + {"darkgoldenrod3", 205, 149, 12}, + {"darkgoldenrod4", 139, 101, 8}, + {"rosybrown1", 255, 193, 193}, + {"rosybrown2", 238, 180, 180}, + {"rosybrown3", 205, 155, 155}, + {"rosybrown4", 139, 105, 105}, + {"indianred1", 255, 106, 106}, + {"indianred2", 238, 99, 99}, + {"indianred3", 205, 85, 85}, + {"indianred4", 139, 58, 58}, + {"sienna1", 255, 130, 71}, + {"sienna2", 238, 121, 66}, + {"sienna3", 205, 104, 57}, + {"sienna4", 139, 71, 38}, + {"burlywood1", 255, 211, 155}, + {"burlywood2", 238, 197, 145}, + {"burlywood3", 205, 170, 125}, + {"burlywood4", 139, 115, 85}, + {"wheat1", 255, 231, 186}, + {"wheat2", 238, 216, 174}, + {"wheat3", 205, 186, 150}, + {"wheat4", 139, 126, 102}, + {"tan1", 255, 165, 79}, + {"tan2", 238, 154, 73}, + {"tan3", 205, 133, 63}, + {"tan4", 139, 90, 43}, + {"chocolate1", 255, 127, 36}, + {"chocolate2", 238, 118, 33}, + {"chocolate3", 205, 102, 29}, + {"chocolate4", 139, 69, 19}, + {"firebrick1", 255, 48, 48}, + {"firebrick2", 238, 44, 44}, + {"firebrick3", 205, 38, 38}, + {"firebrick4", 139, 26, 26}, + {"brown1", 255, 64, 64}, + {"brown2", 238, 59, 59}, + {"brown3", 205, 51, 51}, + {"brown4", 139, 35, 35}, + {"salmon1", 255, 140, 105}, + {"salmon2", 238, 130, 98}, + {"salmon3", 205, 112, 84}, + {"salmon4", 139, 76, 57}, + {"lightsalmon1", 255, 160, 122}, + {"lightsalmon2", 238, 149, 114}, + {"lightsalmon3", 205, 129, 98}, + {"lightsalmon4", 139, 87, 66}, + {"orange1", 255, 165, 0}, + {"orange2", 238, 154, 0}, + {"orange3", 205, 133, 0}, + {"orange4", 139, 90, 0}, + {"darkorange1", 255, 127, 0}, + {"darkorange2", 238, 118, 0}, + {"darkorange3", 205, 102, 0}, + {"darkorange4", 139, 69, 0}, + {"coral1", 255, 114, 86}, + {"coral2", 238, 106, 80}, + {"coral3", 205, 91, 69}, + {"coral4", 139, 62, 47}, + {"tomato1", 255, 99, 71}, + {"tomato2", 238, 92, 66}, + {"tomato3", 205, 79, 57}, + {"tomato4", 139, 54, 38}, + {"orangered1", 255, 69, 0}, + {"orangered2", 238, 64, 0}, + {"orangered3", 205, 55, 0}, + {"orangered4", 139, 37, 0}, + {"red1", 255, 0, 0}, + {"red2", 238, 0, 0}, + {"red3", 205, 0, 0}, + {"red4", 139, 0, 0}, + {"deeppink1", 255, 20, 147}, + {"deeppink2", 238, 18, 137}, + {"deeppink3", 205, 16, 118}, + {"deeppink4", 139, 10, 80}, + {"hotpink1", 255, 110, 180}, + {"hotpink2", 238, 106, 167}, + {"hotpink3", 205, 96, 144}, + {"hotpink4", 139, 58, 98}, + {"pink1", 255, 181, 197}, + {"pink2", 238, 169, 184}, + {"pink3", 205, 145, 158}, + {"pink4", 139, 99, 108}, + {"lightpink1", 255, 174, 185}, + {"lightpink2", 238, 162, 173}, + {"lightpink3", 205, 140, 149}, + {"lightpink4", 139, 95, 101}, + {"palevioletred1", 255, 130, 171}, + {"palevioletred2", 238, 121, 159}, + {"palevioletred3", 205, 104, 137}, + {"palevioletred4", 139, 71, 93}, + {"maroon1", 255, 52, 179}, + {"maroon2", 238, 48, 167}, + {"maroon3", 205, 41, 144}, + {"maroon4", 139, 28, 98}, + {"violetred1", 255, 62, 150}, + {"violetred2", 238, 58, 140}, + {"violetred3", 205, 50, 120}, + {"violetred4", 139, 34, 82}, + {"magenta1", 255, 0, 255}, + {"magenta2", 238, 0, 238}, + {"magenta3", 205, 0, 205}, + {"magenta4", 139, 0, 139}, + {"orchid1", 255, 131, 250}, + {"orchid2", 238, 122, 233}, + {"orchid3", 205, 105, 201}, + {"orchid4", 139, 71, 137}, + {"plum1", 255, 187, 255}, + {"plum2", 238, 174, 238}, + {"plum3", 205, 150, 205}, + {"plum4", 139, 102, 139}, + {"mediumorchid1", 224, 102, 255}, + {"mediumorchid2", 209, 95, 238}, + {"mediumorchid3", 180, 82, 205}, + {"mediumorchid4", 122, 55, 139}, + {"darkorchid1", 191, 62, 255}, + {"darkorchid2", 178, 58, 238}, + {"darkorchid3", 154, 50, 205}, + {"darkorchid4", 104, 34, 139}, + {"purple1", 155, 48, 255}, + {"purple2", 145, 44, 238}, + {"purple3", 125, 38, 205}, + {"purple4", 85, 26, 139}, + {"mediumpurple1", 171, 130, 255}, + {"mediumpurple2", 159, 121, 238}, + {"mediumpurple3", 137, 104, 205}, + {"mediumpurple4", 93, 71, 139}, + {"thistle1", 255, 225, 255}, + {"thistle2", 238, 210, 238}, + {"thistle3", 205, 181, 205}, + {"thistle4", 139, 123, 139}, + {"gray0", 0, 0, 0}, + {"grey0", 0, 0, 0}, + {"gray1", 3, 3, 3}, + {"grey1", 3, 3, 3}, + {"gray2", 5, 5, 5}, + {"grey2", 5, 5, 5}, + {"gray3", 8, 8, 8}, + {"grey3", 8, 8, 8}, + {"gray4", 10, 10, 10}, + {"grey4", 10, 10, 10}, + {"gray5", 13, 13, 13}, + {"grey5", 13, 13, 13}, + {"gray6", 15, 15, 15}, + {"grey6", 15, 15, 15}, + {"gray7", 18, 18, 18}, + {"grey7", 18, 18, 18}, + {"gray8", 20, 20, 20}, + {"grey8", 20, 20, 20}, + {"gray9", 23, 23, 23}, + {"grey9", 23, 23, 23}, + {"gray10", 26, 26, 26}, + {"grey10", 26, 26, 26}, + {"gray11", 28, 28, 28}, + {"grey11", 28, 28, 28}, + {"gray12", 31, 31, 31}, + {"grey12", 31, 31, 31}, + {"gray13", 33, 33, 33}, + {"grey13", 33, 33, 33}, + {"gray14", 36, 36, 36}, + {"grey14", 36, 36, 36}, + {"gray15", 38, 38, 38}, + {"grey15", 38, 38, 38}, + {"gray16", 41, 41, 41}, + {"grey16", 41, 41, 41}, + {"gray17", 43, 43, 43}, + {"grey17", 43, 43, 43}, + {"gray18", 46, 46, 46}, + {"grey18", 46, 46, 46}, + {"gray19", 48, 48, 48}, + {"grey19", 48, 48, 48}, + {"gray20", 51, 51, 51}, + {"grey20", 51, 51, 51}, + {"gray21", 54, 54, 54}, + {"grey21", 54, 54, 54}, + {"gray22", 56, 56, 56}, + {"grey22", 56, 56, 56}, + {"gray23", 59, 59, 59}, + {"grey23", 59, 59, 59}, + {"gray24", 61, 61, 61}, + {"grey24", 61, 61, 61}, + {"gray25", 64, 64, 64}, + {"grey25", 64, 64, 64}, + {"gray26", 66, 66, 66}, + {"grey26", 66, 66, 66}, + {"gray27", 69, 69, 69}, + {"grey27", 69, 69, 69}, + {"gray28", 71, 71, 71}, + {"grey28", 71, 71, 71}, + {"gray29", 74, 74, 74}, + {"grey29", 74, 74, 74}, + {"gray30", 77, 77, 77}, + {"grey30", 77, 77, 77}, + {"gray31", 79, 79, 79}, + {"grey31", 79, 79, 79}, + {"gray32", 82, 82, 82}, + {"grey32", 82, 82, 82}, + {"gray33", 84, 84, 84}, + {"grey33", 84, 84, 84}, + {"gray34", 87, 87, 87}, + {"grey34", 87, 87, 87}, + {"gray35", 89, 89, 89}, + {"grey35", 89, 89, 89}, + {"gray36", 92, 92, 92}, + {"grey36", 92, 92, 92}, + {"gray37", 94, 94, 94}, + {"grey37", 94, 94, 94}, + {"gray38", 97, 97, 97}, + {"grey38", 97, 97, 97}, + {"gray39", 99, 99, 99}, + {"grey39", 99, 99, 99}, + {"gray40", 102, 102, 102}, + {"grey40", 102, 102, 102}, + {"gray41", 105, 105, 105}, + {"grey41", 105, 105, 105}, + {"gray42", 107, 107, 107}, + {"grey42", 107, 107, 107}, + {"gray43", 110, 110, 110}, + {"grey43", 110, 110, 110}, + {"gray44", 112, 112, 112}, + {"grey44", 112, 112, 112}, + {"gray45", 115, 115, 115}, + {"grey45", 115, 115, 115}, + {"gray46", 117, 117, 117}, + {"grey46", 117, 117, 117}, + {"gray47", 120, 120, 120}, + {"grey47", 120, 120, 120}, + {"gray48", 122, 122, 122}, + {"grey48", 122, 122, 122}, + {"gray49", 125, 125, 125}, + {"grey49", 125, 125, 125}, + {"gray50", 127, 127, 127}, + {"grey50", 127, 127, 127}, + {"gray51", 130, 130, 130}, + {"grey51", 130, 130, 130}, + {"gray52", 133, 133, 133}, + {"grey52", 133, 133, 133}, + {"gray53", 135, 135, 135}, + {"grey53", 135, 135, 135}, + {"gray54", 138, 138, 138}, + {"grey54", 138, 138, 138}, + {"gray55", 140, 140, 140}, + {"grey55", 140, 140, 140}, + {"gray56", 143, 143, 143}, + {"grey56", 143, 143, 143}, + {"gray57", 145, 145, 145}, + {"grey57", 145, 145, 145}, + {"gray58", 148, 148, 148}, + {"grey58", 148, 148, 148}, + {"gray59", 150, 150, 150}, + {"grey59", 150, 150, 150}, + {"gray60", 153, 153, 153}, + {"grey60", 153, 153, 153}, + {"gray61", 156, 156, 156}, + {"grey61", 156, 156, 156}, + {"gray62", 158, 158, 158}, + {"grey62", 158, 158, 158}, + {"gray63", 161, 161, 161}, + {"grey63", 161, 161, 161}, + {"gray64", 163, 163, 163}, + {"grey64", 163, 163, 163}, + {"gray65", 166, 166, 166}, + {"grey65", 166, 166, 166}, + {"gray66", 168, 168, 168}, + {"grey66", 168, 168, 168}, + {"gray67", 171, 171, 171}, + {"grey67", 171, 171, 171}, + {"gray68", 173, 173, 173}, + {"grey68", 173, 173, 173}, + {"gray69", 176, 176, 176}, + {"grey69", 176, 176, 176}, + {"gray70", 179, 179, 179}, + {"grey70", 179, 179, 179}, + {"gray71", 181, 181, 181}, + {"grey71", 181, 181, 181}, + {"gray72", 184, 184, 184}, + {"grey72", 184, 184, 184}, + {"gray73", 186, 186, 186}, + {"grey73", 186, 186, 186}, + {"gray74", 189, 189, 189}, + {"grey74", 189, 189, 189}, + {"gray75", 191, 191, 191}, + {"grey75", 191, 191, 191}, + {"gray76", 194, 194, 194}, + {"grey76", 194, 194, 194}, + {"gray77", 196, 196, 196}, + {"grey77", 196, 196, 196}, + {"gray78", 199, 199, 199}, + {"grey78", 199, 199, 199}, + {"gray79", 201, 201, 201}, + {"grey79", 201, 201, 201}, + {"gray80", 204, 204, 204}, + {"grey80", 204, 204, 204}, + {"gray81", 207, 207, 207}, + {"grey81", 207, 207, 207}, + {"gray82", 209, 209, 209}, + {"grey82", 209, 209, 209}, + {"gray83", 212, 212, 212}, + {"grey83", 212, 212, 212}, + {"gray84", 214, 214, 214}, + {"grey84", 214, 214, 214}, + {"gray85", 217, 217, 217}, + {"grey85", 217, 217, 217}, + {"gray86", 219, 219, 219}, + {"grey86", 219, 219, 219}, + {"gray87", 222, 222, 222}, + {"grey87", 222, 222, 222}, + {"gray88", 224, 224, 224}, + {"grey88", 224, 224, 224}, + {"gray89", 227, 227, 227}, + {"grey89", 227, 227, 227}, + {"gray90", 229, 229, 229}, + {"grey90", 229, 229, 229}, + {"gray91", 232, 232, 232}, + {"grey91", 232, 232, 232}, + {"gray92", 235, 235, 235}, + {"grey92", 235, 235, 235}, + {"gray93", 237, 237, 237}, + {"grey93", 237, 237, 237}, + {"gray94", 240, 240, 240}, + {"grey94", 240, 240, 240}, + {"gray95", 242, 242, 242}, + {"grey95", 242, 242, 242}, + {"gray96", 245, 245, 245}, + {"grey96", 245, 245, 245}, + {"gray97", 247, 247, 247}, + {"grey97", 247, 247, 247}, + {"gray98", 250, 250, 250}, + {"grey98", 250, 250, 250}, + {"gray99", 252, 252, 252}, + {"grey99", 252, 252, 252}, + {"gray100", 255, 255, 255}, + {"grey100", 255, 255, 255}, + {nullptr, 0, 0, 0}}; Dot2QtConsts::Dot2QtConsts() { - m_penStyles["solid"] = Qt::SolidLine; - m_penStyles["dashed"] = Qt::DashLine; - m_penStyles["dotted"] = Qt::DotLine; - m_penStyles["invis"] = Qt::NoPen; + m_penStyles["solid"] = Qt::SolidLine; + m_penStyles["dashed"] = Qt::DashLine; + m_penStyles["dotted"] = Qt::DotLine; + m_penStyles["invis"] = Qt::NoPen; - m_colors["crimson"] = "#DC143C"; - m_colors["hot_pink"] = "#FF69B4"; - m_colors["light_yellow"] = "#FFFFE0"; - m_colors["slate_blue"] = "#6A5ACD"; + m_colors["crimson"] = "#DC143C"; + m_colors["hot_pink"] = "#FF69B4"; + m_colors["light_yellow"] = "#FFFFE0"; + m_colors["slate_blue"] = "#6A5ACD"; - uint i = 0; - while (postscriptFontNames[i].input) - { - QFont font(postscriptFontNames[i].input); - m_psFonts[postscriptFontNames[i].roman] = font; - if (postscriptFontNames[i].italic) - { - QFont italic = font; italic.setItalic(true); - m_psFonts[postscriptFontNames[i].italic] = italic; - } - if (postscriptFontNames[i].bold) - { - QFont bold = font; bold.setBold(true); - m_psFonts[postscriptFontNames[i].bold] = bold; - } - if (postscriptFontNames[i].boldItalic) - { - QFont boldItalic = font; - boldItalic.setItalic(true); - boldItalic.setBold(true); - m_psFonts[postscriptFontNames[i].boldItalic] = boldItalic; - } - if (postscriptFontNames[i].light) - { - QFont light = font; light.setWeight(QFont::Light); - m_psFonts[postscriptFontNames[i].light] = light; - } - if (postscriptFontNames[i].lightItalic) - { - QFont lightItalic = font; - lightItalic.setWeight(QFont::Light); - lightItalic.setItalic(true); - m_psFonts[postscriptFontNames[i].lightItalic] = lightItalic; + uint i = 0; + while (postscriptFontNames[i].input) { + QFont font(postscriptFontNames[i].input); + m_psFonts[postscriptFontNames[i].roman] = font; + if (postscriptFontNames[i].italic) { + QFont italic = font; + italic.setItalic(true); + m_psFonts[postscriptFontNames[i].italic] = italic; + } + if (postscriptFontNames[i].bold) { + QFont bold = font; + bold.setBold(true); + m_psFonts[postscriptFontNames[i].bold] = bold; + } + if (postscriptFontNames[i].boldItalic) { + QFont boldItalic = font; + boldItalic.setItalic(true); + boldItalic.setBold(true); + m_psFonts[postscriptFontNames[i].boldItalic] = boldItalic; + } + if (postscriptFontNames[i].light) { + QFont light = font; + light.setWeight(QFont::Light); + m_psFonts[postscriptFontNames[i].light] = light; + } + if (postscriptFontNames[i].lightItalic) { + QFont lightItalic = font; + lightItalic.setWeight(QFont::Light); + lightItalic.setItalic(true); + m_psFonts[postscriptFontNames[i].lightItalic] = lightItalic; + } + i++; } - i++; - } - uint j = 0; - while (color_lib[j].name) - { -// () << "Adding color " << color_lib[j].name; - m_qcolors[color_lib[j].name] = QColor(color_lib[j].r,color_lib[j].g,color_lib[j].b); - j++; - } + uint j = 0; + while (color_lib[j].name) { + // () << "Adding color " << color_lib[j].name; + m_qcolors[color_lib[j].name] = QColor(color_lib[j].r, color_lib[j].g, color_lib[j].b); + j++; + } } - Dot2QtConsts::~Dot2QtConsts() -{} - +{ +} -QColor Dot2QtConsts::qtColor(const QString& dotColor) const +QColor Dot2QtConsts::qtColor(const QString &dotColor) const { -// () << "Dot2QtConsts::qtColor"; - QColor color; - if (parse_numeric_color(qPrintable(dotColor), color)) - { - return color; - } - else - { - if (m_qcolors.find(dotColor) != m_qcolors.end()) - { - return (*m_qcolors.find(dotColor)); - } - QColor res(dotColor); - if (res.isValid()) - { - return res; - } - else - { - if (m_colors.find(dotColor) != m_colors.end()) - { - res = QColor((*m_colors.find(dotColor))); - if (res.isValid()) - { - return res; - } - else - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown stored DOT color '" << dotColor << "'. returning Qt black"; + // () << "Dot2QtConsts::qtColor"; + QColor color; + if (parse_numeric_color(qPrintable(dotColor), color)) { + return color; + } else { + if (m_qcolors.find(dotColor) != m_qcolors.end()) { + return (*m_qcolors.find(dotColor)); + } + QColor res(dotColor); + if (res.isValid()) { + return res; + } else { + if (m_colors.find(dotColor) != m_colors.end()) { + res = QColor((*m_colors.find(dotColor))); + if (res.isValid()) { + return res; + } else { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown stored DOT color '" << dotColor << "'. returning Qt black"; + return Qt::black; + } + } else { + // qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT color '" << dotColor << "'. returning Qt black"; return Qt::black; } } - else - { -// qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT color '" << dotColor << "'. returning Qt black"; - return Qt::black; - } } - } } -Qt::PenStyle Dot2QtConsts::qtPenStyle(const QString& dotLineStyle) const +Qt::PenStyle Dot2QtConsts::qtPenStyle(const QString &dotLineStyle) const { - if (m_penStyles.find(dotLineStyle) != m_penStyles.end()) - return (*(m_penStyles.find(dotLineStyle))); - else - { - if (!dotLineStyle.left(12).isEmpty() - && dotLineStyle.left(12) != "setlinewidth") - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT line style '" << dotLineStyle << "'. returning Qt solid line"; - return Qt::SolidLine; - } + if (m_penStyles.find(dotLineStyle) != m_penStyles.end()) + return (*(m_penStyles.find(dotLineStyle))); + else { + if (!dotLineStyle.left(12).isEmpty() && dotLineStyle.left(12) != "setlinewidth") + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT line style '" << dotLineStyle << "'. returning Qt solid line"; + return Qt::SolidLine; + } } -QFont Dot2QtConsts::qtFont(const QString& dotFont) const +QFont Dot2QtConsts::qtFont(const QString &dotFont) const { - if (m_psFonts.find(dotFont) != m_psFonts.end()) - return (*(m_psFonts.find(dotFont))); - else - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT font '" << dotFont << "'. returning Qt default."; - return QFont(QFont::substitute(dotFont)); - } + if (m_psFonts.find(dotFont) != m_psFonts.end()) + return (*(m_psFonts.find(dotFont))); + else { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unknown DOT font '" << dotFont << "'. returning Qt default."; + return QFont(QFont::substitute(dotFont)); + } } - diff --git a/src/part/dotdefaults.h b/src/part/dotdefaults.h --- a/src/part/dotdefaults.h +++ b/src/part/dotdefaults.h @@ -32,4 +32,3 @@ #define DOT_DEFAULT_NODE_BACKCOLOR "lightgrey" #define DOT_DEFAULT_BACKCOLOR "white" #endif - diff --git a/src/part/dotgrammar.h b/src/part/dotgrammar.h --- a/src/part/dotgrammar.h +++ b/src/part/dotgrammar.h @@ -25,85 +25,70 @@ #include "dotrenderop.h" -#include #include #include #include +#include -#include #include #include +#include #include -#include #include -#include +#include #include +#include -bool parse(const std::string& str); - -void gotid(char const* first, char const* last); -void dump(char const* first, char const* last); -void strict(char const* first, char const* last); -void undigraph(char const* first, char const* last); -void digraph(char const* first, char const* last); -void graphid(char const* first, char const* last); -void attrid(char const* first, char const* last); -void subgraphid(char const* first, char const* last); -void valid(char const* first, char const* last); -void addattr(char const* first, char const* last); +bool parse(const std::string &str); + +void gotid(char const *first, char const *last); +void dump(char const *first, char const *last); +void strict(char const *first, char const *last); +void undigraph(char const *first, char const *last); +void digraph(char const *first, char const *last); +void graphid(char const *first, char const *last); +void attrid(char const *first, char const *last); +void subgraphid(char const *first, char const *last); +void valid(char const *first, char const *last); +void addattr(char const *first, char const *last); void pushAttrListC(char const c); void popAttrListC(char const c); -void pushAttrList(char const* first, char const* last); -void popAttrList(char const* first, char const* last); +void pushAttrList(char const *first, char const *last); +void popAttrList(char const *first, char const *last); void createsubgraph(char const); -void createnode(char const* first, char const* last); -void setgraphattributes(char const* first, char const* last); -void setsubgraphattributes(char const* first, char const* last); -void setnodeattributes(char const* first, char const* last); -void setattributedlist(char const* first, char const* last); -void checkedgeop(char const* first, char const* last); -void edgebound(char const* first, char const* last); -void createedges(char const* first, char const* last); +void createnode(char const *first, char const *last); +void setgraphattributes(char const *first, char const *last); +void setsubgraphattributes(char const *first, char const *last); +void setnodeattributes(char const *first, char const *last); +void setattributedlist(char const *first, char const *last); +void checkedgeop(char const *first, char const *last); +void edgebound(char const *first, char const *last); +void createedges(char const *first, char const *last); void incrz(char const); void decrz(char const); -void finalactions(char const* first, char const* last); +void finalactions(char const *first, char const *last); -bool parse_point(char const* str, QPoint& p); -bool parse_real(char const* str, double& d); -bool parse_integers(char const* str, std::vector& v); -bool parse_spline(char const* str, QVector< QPair< float, float > >& points); +bool parse_point(char const *str, QPoint &p); +bool parse_real(char const *str, double &d); +bool parse_integers(char const *str, std::vector &v); +bool parse_spline(char const *str, QVector> &points); void init_op(); -void valid_op(char const* first, char const* last); -bool parse_renderop(const std::string& str, DotRenderOpVec& arenderopvec); -bool parse_numeric_color(char const* str, QColor& c); - -struct DotGrammar : public boost::spirit::classic::grammar -{ - template - struct definition - { - definition(DotGrammar const& self); - - boost::spirit::classic::rule graph, ID, tag, stmt_list, stmt, attr_stmt, - attr_list, a_list, edge_stmt, edgeop, - edgeRHS, node_stmt, node_id, - port, subgraph, compass_pt; - - boost::spirit::classic::rule const& start() const - { - return graph; - } - }; - -}; - - +void valid_op(char const *first, char const *last); +bool parse_renderop(const std::string &str, DotRenderOpVec &arenderopvec); +bool parse_numeric_color(char const *str, QColor &c); +struct DotGrammar : public boost::spirit::classic::grammar { + template struct definition { + definition(DotGrammar const &self); + boost::spirit::classic::rule graph, ID, tag, stmt_list, stmt, attr_stmt, attr_list, a_list, edge_stmt, edgeop, edgeRHS, node_stmt, node_id, port, subgraph, compass_pt; + boost::spirit::classic::rule const &start() const + { + return graph; + } + }; +}; #endif - - - diff --git a/src/part/dotgrammar.cpp b/src/part/dotgrammar.cpp --- a/src/part/dotgrammar.cpp +++ b/src/part/dotgrammar.cpp @@ -17,26 +17,27 @@ */ #include "dotgrammar.h" -#include "dotgraph.h" +#include "DotGraphParsingHelper.h" #include "dotdefaults.h" -#include "graphnode.h" +#include "dotgraph.h" #include "graphedge.h" -#include "DotGraphParsingHelper.h" +#include "graphnode.h" #include "kgraphviewerlib_debug.h" #include #include - + #include #include -#include +#include namespace boost { - void throw_exception(std::exception const &) {} +void throw_exception(std::exception const &) +{ +} } - using namespace std; using namespace boost; @@ -47,7 +48,7 @@ #define KGV_MAX_ITEMS_TO_LOAD std::numeric_limits::max() #define BOOST_SPIRIT_DEBUG 1 -DotGraphParsingHelper* phelper = nullptr; +DotGraphParsingHelper *phelper = nullptr; std::string therenderop; std::string thestr; @@ -58,486 +59,392 @@ // (for basic usage instead of std_p) const boost::spirit::classic::distinct_parser<> keyword_p("0-9a-zA-Z_"); -template -DotGrammar::definition::definition(DotGrammar const& /*self*/) -{ - graph = (!(keyword_p("strict")[&strict]) >> (keyword_p("graph")[&undigraph] | keyword_p("digraph")[&digraph]) - >> !ID[&graphid] >> ch_p('{') >> !stmt_list >> ch_p('}'))[&finalactions]; - ID = ( - ( ( (anychar_p - punct_p) | '_' ) >> *( (anychar_p - punct_p) | '_' ) ) - | real_p - | ( '"' >> *( (ch_p('\\') >> '"') | (anychar_p - '"') ) >> '"' ) - | ( ch_p('<') >> *( (anychar_p - '<' - '>') | tag ) >> '>' ) - ); - tag = ('<' >> *( anychar_p - '>') >> '>'); - stmt_list = stmt >> !(ch_p(';')) >> !( stmt_list ) ; - stmt = ( - attr_stmt - | subgraph - | edge_stmt - | node_stmt - | ( ID >> '=' >> ID ) - ); - - attr_stmt = ( - (keyword_p("graph")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist])[&setgraphattributes] - | (keyword_p("node")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist]) - | (keyword_p("edge")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist]) - ) ; - - attr_list = ch_p('[') >> !( a_list ) >> ch_p(']'); - a_list = ((ID[&attrid] >> !( '=' >> ID[&valid] ))[&addattr] >> !(',' >> a_list )); - edge_stmt = ( (node_id[&edgebound] | subgraph) >> edgeRHS >> !( attr_list[assign_a(phelper->attributed,"edge")] ) )[&pushAttrList][&setattributedlist][&createedges][&popAttrList]; - edgeRHS = edgeop[&checkedgeop] >> (node_id[&edgebound] | subgraph) >> !( edgeRHS ); - edgeop = str_p("->") | str_p("--"); - node_stmt = ( node_id[&createnode] >> !( attr_list ) )[assign_a(phelper->attributed,"node")][&pushAttrList][&setattributedlist][&setnodeattributes][&popAttrList]; - node_id = (ID >> !( port )); - port = ( ch_p(':') >> ID >> !( ':' >> compass_pt ) ) - | ( ':' >> compass_pt ); - subgraph = ( !( keyword_p("subgraph") >> !( ID[&subgraphid] ) ) >> ch_p('{')[&createsubgraph][&incrz][&pushAttrListC] >> stmt_list >> ch_p('}') [&decrz][&popAttrListC]) - | ( keyword_p("subgraph") >> ID[&subgraphid]); - compass_pt = (keyword_p("n") | keyword_p("ne") | keyword_p("e") - | keyword_p("se") | keyword_p("s") | keyword_p("sw") - | keyword_p("w") | keyword_p("nw") ); -} - +template DotGrammar::definition::definition(DotGrammar const & /*self*/) +{ + graph = (!(keyword_p("strict")[&strict]) >> (keyword_p("graph")[&undigraph] | keyword_p("digraph")[&digraph]) >> !ID[&graphid] >> ch_p('{') >> !stmt_list >> ch_p('}'))[&finalactions]; + ID = ((((anychar_p - punct_p) | '_') >> *((anychar_p - punct_p) | '_')) | real_p | ('"' >> *((ch_p('\\') >> '"') | (anychar_p - '"')) >> '"') | (ch_p('<') >> *((anychar_p - '<' - '>') | tag) >> '>')); + tag = ('<' >> *(anychar_p - '>') >> '>'); + stmt_list = stmt >> !(ch_p(';')) >> !(stmt_list); + stmt = (attr_stmt | subgraph | edge_stmt | node_stmt | (ID >> '=' >> ID)); + attr_stmt = ((keyword_p("graph")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist])[&setgraphattributes] | (keyword_p("node")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist]) | + (keyword_p("edge")[assign_a(phelper->attributed)] >> attr_list[&setattributedlist])); + attr_list = ch_p('[') >> !(a_list) >> ch_p(']'); + a_list = ((ID[&attrid] >> !('=' >> ID[&valid]))[&addattr] >> !(',' >> a_list)); + edge_stmt = ((node_id[&edgebound] | subgraph) >> edgeRHS >> !(attr_list[assign_a(phelper->attributed, "edge")]))[&pushAttrList][&setattributedlist][&createedges][&popAttrList]; + edgeRHS = edgeop[&checkedgeop] >> (node_id[&edgebound] | subgraph) >> !(edgeRHS); + edgeop = str_p("->") | str_p("--"); + node_stmt = (node_id[&createnode] >> !(attr_list))[assign_a(phelper->attributed, "node")][&pushAttrList][&setattributedlist][&setnodeattributes][&popAttrList]; + node_id = (ID >> !(port)); + port = (ch_p(':') >> ID >> !(':' >> compass_pt)) | (':' >> compass_pt); + subgraph = (!(keyword_p("subgraph") >> !(ID[&subgraphid])) >> ch_p('{')[&createsubgraph][&incrz][&pushAttrListC] >> stmt_list >> ch_p('}')[&decrz][&popAttrListC]) | (keyword_p("subgraph") >> ID[&subgraphid]); + compass_pt = (keyword_p("n") | keyword_p("ne") | keyword_p("e") | keyword_p("se") | keyword_p("s") | keyword_p("sw") | keyword_p("w") | keyword_p("nw")); +} void incrz(char const /*first*/) { - if (phelper) - { - phelper->z++; - if (phelper->z > phelper->maxZ) - { - phelper->maxZ = phelper->z; + if (phelper) { + phelper->z++; + if (phelper->z > phelper->maxZ) { + phelper->maxZ = phelper->z; + } } - } } void anychar(char const c) { Q_UNUSED(c); -// qCDebug(KGRAPHVIEWERLIB_LOG) << c; + // qCDebug(KGRAPHVIEWERLIB_LOG) << c; } void decrz(char const /*first*/) { - if (phelper) - { - phelper->z--; - phelper->gs = nullptr; - } + if (phelper) { + phelper->z--; + phelper->gs = nullptr; + } } -void dump(char const* first, char const* last) +void dump(char const *first, char const *last) { - std::string str(first, last); - qCWarning(KGRAPHVIEWERLIB_LOG) << ">>>> " << QString::fromStdString(str) << " <<<<" << endl; + std::string str(first, last); + qCWarning(KGRAPHVIEWERLIB_LOG) << ">>>> " << QString::fromStdString(str) << " <<<<" << endl; } -void strict(char const* /*first*/, char const* /*last*/) +void strict(char const * /*first*/, char const * /*last*/) { - if (phelper) phelper->graph->strict(true); + if (phelper) + phelper->graph->strict(true); } -void gotid(char const* first, char const* last) +void gotid(char const *first, char const *last) { - std::string id(first,last); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Got ID = '"<attrid)<<"'"; + std::string id(first, last); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Got ID = '"<attrid)<<"'"; } -void undigraph(char const* /*first*/, char const* /*last*/) +void undigraph(char const * /*first*/, char const * /*last*/) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting graph as undirected"; - if (phelper) phelper->graph->directed(false); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting graph as undirected"; + if (phelper) + phelper->graph->directed(false); } -void digraph(char const* /*first*/, char const* /*last*/) +void digraph(char const * /*first*/, char const * /*last*/) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting graph as directed"; - if (phelper) phelper->graph->directed(true); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting graph as directed"; + if (phelper) + phelper->graph->directed(true); } -void graphid(char const* first, char const* last) +void graphid(char const *first, char const *last) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(std::string(first,last)); - if (phelper) phelper->graph->setId(QString::fromStdString(std::string(first,last))); + // qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(std::string(first,last)); + if (phelper) + phelper->graph->setId(QString::fromStdString(std::string(first, last))); } -void attrid(char const* first, char const* last) +void attrid(char const *first, char const *last) { - if (phelper) - { - std::string id(first,last); - if (id.size()>0 && id[0] == '"') id = id.substr(1); - if (id.size()>0 && id[id.size()-1] == '"') id = id.substr(0,id.size()-1); - phelper->attrid = id; - phelper->valid = ""; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Got attr ID = '"<attrid)<<"'"; - } + if (phelper) { + std::string id(first, last); + if (id.size() > 0 && id[0] == '"') + id = id.substr(1); + if (id.size() > 0 && id[id.size() - 1] == '"') + id = id.substr(0, id.size() - 1); + phelper->attrid = id; + phelper->valid = ""; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Got attr ID = '"<attrid)<<"'"; + } } -void subgraphid(char const* first, char const* last) +void subgraphid(char const *first, char const *last) { - std::string id(first,last); -// qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(id); - if (phelper) - { - if (id.size()>0 && id[0] == '"') id = id.substr(1); - if (id.size()>0 && id[id.size()-1] == '"') id = id.substr(0,id.size()-1); - phelper->subgraphid = id; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Got subgraph id = '"<subgraphid)<<"'"; - } + std::string id(first, last); + // qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromStdString(id); + if (phelper) { + if (id.size() > 0 && id[0] == '"') + id = id.substr(1); + if (id.size() > 0 && id[id.size() - 1] == '"') + id = id.substr(0, id.size() - 1); + phelper->subgraphid = id; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Got subgraph id = '"<subgraphid)<<"'"; + } } -void valid(char const* first, char const* last) +void valid(char const *first, char const *last) { - std::string id(first,last); - if (phelper) - { - if (id.size()>0 && id[0] == '"') id = id.substr(1); - if (id.size()>0 && id[id.size()-1] == '"') id = id.substr(0,id.size()-1); - phelper->valid = id; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Got attr val = '"< 0 && id[0] == '"') + id = id.substr(1); + if (id.size() > 0 && id[id.size() - 1] == '"') + id = id.substr(0, id.size() - 1); + phelper->valid = id; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Got attr val = '"<attributes.insert(std::make_pair(phelper->attrid,phelper->valid)); - } + if (phelper) { + phelper->attributes.insert(std::make_pair(phelper->attrid, phelper->valid)); + } } void pushAttrListC(char const /*c*/) { - pushAttrList(nullptr, nullptr); + pushAttrList(nullptr, nullptr); } -void pushAttrList(char const* /*first*/, char const* /*last*/) +void pushAttrList(char const * /*first*/, char const * /*last*/) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Pushing attributes"; - if (phelper) - { - phelper->graphAttributesStack.push_back(phelper->graphAttributes); - phelper->nodesAttributesStack.push_back(phelper->nodesAttributes); - phelper->edgesAttributesStack.push_back(phelper->edgesAttributes); - } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Pushing attributes"; + if (phelper) { + phelper->graphAttributesStack.push_back(phelper->graphAttributes); + phelper->nodesAttributesStack.push_back(phelper->nodesAttributes); + phelper->edgesAttributesStack.push_back(phelper->edgesAttributes); + } } void popAttrListC(char const /*c*/) { - popAttrList(nullptr, nullptr); + popAttrList(nullptr, nullptr); } -void popAttrList(char const* /*first*/, char const* /*last*/) +void popAttrList(char const * /*first*/, char const * /*last*/) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Poping attributes"; - if (phelper) - { - phelper->graphAttributes = phelper->graphAttributesStack.back(); - phelper->graphAttributesStack.pop_back(); - phelper->nodesAttributes = phelper->nodesAttributesStack.back(); - phelper->nodesAttributesStack.pop_back(); - phelper->edgesAttributes = phelper->edgesAttributesStack.back(); - phelper->edgesAttributesStack.pop_back(); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Poped"; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Poping attributes"; + if (phelper) { + phelper->graphAttributes = phelper->graphAttributesStack.back(); + phelper->graphAttributesStack.pop_back(); + phelper->nodesAttributes = phelper->nodesAttributesStack.back(); + phelper->nodesAttributesStack.pop_back(); + phelper->edgesAttributes = phelper->edgesAttributesStack.back(); + phelper->edgesAttributesStack.pop_back(); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Poped"; } -void createnode(char const* first, char const* last) +void createnode(char const *first, char const *last) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << (void*)first << (void*)last << QString::fromStdString(std::string(first,last)); - if (phelper && first && last) - { - std::string id(first,last); - if (id.size()>0 && id[0] == '"') id = id.substr(1); - if (id.size()>0 && id[id.size()-1] == '"') id = id.substr(0,id.size()-1); - phelper->createnode(id); - } + // qCDebug(KGRAPHVIEWERLIB_LOG) << (void*)first << (void*)last << QString::fromStdString(std::string(first,last)); + if (phelper && first && last) { + std::string id(first, last); + if (id.size() > 0 && id[0] == '"') + id = id.substr(1); + if (id.size() > 0 && id[id.size() - 1] == '"') + id = id.substr(0, id.size() - 1); + phelper->createnode(id); + } } void createsubgraph(char const /*c*/) { - if (phelper) - { - phelper->createsubgraph(); - } + if (phelper) { + phelper->createsubgraph(); + } +} + +void setgraphattributes(char const * /*first*/, char const * /*last*/) +{ + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setgraphattributes with z = " << phelper->z; + if (phelper) { + if (phelper->z == 1) // main graph + { + phelper->setgraphattributes(); + } else { + phelper->setsubgraphattributes(); + } + } +} + +void setnodeattributes(char const * /*first*/, char const * /*last*/) +{ + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setnodeattributes with z = " << phelper->z; + if (phelper) { + phelper->setnodeattributes(); + } } -void setgraphattributes(char const* /*first*/, char const* /*last*/) +void setattributedlist(char const * /*first*/, char const * /*last*/) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setgraphattributes with z = " << phelper->z; - if (phelper) - { - if (phelper->z == 1) // main graph - { - phelper->setgraphattributes(); + if (phelper) { + phelper->setattributedlist(); } - else - { - phelper->setsubgraphattributes(); +} + +void checkedgeop(char const *first, char const *last) +{ + std::string str(first, last); + if (phelper) { + if (((phelper->graph->directed()) && (str == "->")) || ((!phelper->graph->directed()) && (str == "--"))) + return; + + qCWarning(KGRAPHVIEWERLIB_LOG) << "Error !! uncoherent relation : directed = '" << phelper->graph->directed() << "' and op = '" << QString::fromStdString(str) << "'" << endl; } - } } -void setnodeattributes(char const* /*first*/, char const* /*last*/) +void edgebound(char const *first, char const *last) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setnodeattributes with z = " << phelper->z; - if (phelper) - { - phelper->setnodeattributes(); - } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "edgebound: " << QString::fromStdString(std::string(first,last)); + if (phelper) { + std::string id(first, last); + if (id.size() > 0 && id[0] == '"') + id = id.substr(1); + if (id.size() > 0 && id[id.size() - 1] == '"') + id = id.substr(0, id.size() - 1); + phelper->edgebound(id); + } } -void setattributedlist(char const* /*first*/, char const* /*last*/) +void createedges(char const * /*first*/, char const * /*last*/) { - if (phelper) - { - phelper->setattributedlist(); - } + if (phelper) { + phelper->createedges(); + } } -void checkedgeop(char const* first, char const* last) +void finalactions(char const * /*first*/, char const * /*last*/) { - std::string str(first,last); - if (phelper) - { - if ( ( (phelper->graph->directed()) && (str == "->") ) || - ( (!phelper->graph->directed()) && (str == "--") ) ) - return; - - qCWarning(KGRAPHVIEWERLIB_LOG) << "Error !! uncoherent relation : directed = '" << phelper->graph->directed() << "' and op = '" << QString::fromStdString(str) << "'" << endl; - } + if (phelper) { + phelper->finalactions(); + } } -void edgebound(char const* first, char const* last) +bool parse_point(char const *str, QPoint &p) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "edgebound: " << QString::fromStdString(std::string(first,last)); - if (phelper) - { - std::string id(first,last); - if (id.size()>0 && id[0] == '"') id = id.substr(1); - if (id.size()>0 && id[id.size()-1] == '"') id = id.substr(0,id.size()-1); - phelper->edgebound(id); - } + int x, y; + bool res; + res = parse(str, (int_p[assign_a(x)] >> ',' >> int_p[assign_a(y)]), +space_p).full; + if (!res) + return false; + p = QPoint(x, y); + return true; } -void createedges(char const* /*first*/, char const* /*last*/) +bool parse_numeric_color(char const *str, QColor &c) { - if (phelper) - { - phelper->createedges(); - } + if (str == nullptr) + return false; + int r, g, b, a; + bool res; + uint_parser hex2digits_p; + res = parse(str, (ch_p('#') >> hex2digits_p[assign_a(r)] >> hex2digits_p[assign_a(g)] >> hex2digits_p[assign_a(b)] >> !hex2digits_p[assign_a(a)]), +space_p).full; + if (res) { + c.setRgb(r, g, b); + return true; + } + + double h, s, v; + res = parse(str, (real_p[assign_a(h)] >> !ch_p(',') >> real_p[assign_a(s)] >> !ch_p(',') >> real_p[assign_a(v)]), +space_p).full; + if (res) { + c.setHsv(int(255 * h), int(255 * s), int(255 * v)); + return true; + } + return false; } -void finalactions(char const* /*first*/, char const* /*last*/) +bool parse_real(char const *str, double &d) { - if (phelper) - { - phelper->finalactions(); - } + return parse(str, (real_p[assign_a(d)]), +space_p).full; } -bool parse_point(char const* str, QPoint& p) +bool parse_integers(char const *str, std::vector &v) { - int x,y; - bool res; - res = parse(str, - ( - int_p[assign_a(x)] >> ',' >> int_p[assign_a(y)] - ) - , - +space_p).full; - if (!res) return false; - p = QPoint(x,y); - return true; + return parse(str, (int_p[push_back_a(v)] >> *(',' >> int_p[push_back_a(v)])), +space_p).full; } -bool parse_numeric_color(char const* str, QColor& c) +bool parse_spline(char const *str, QVector> &points) { - if (str == nullptr) return false; - int r,g,b,a; - bool res; - uint_parser hex2digits_p; - res = parse(str, - ( - ch_p('#') >> - hex2digits_p[assign_a(r)] >> - hex2digits_p[assign_a(g)] >> - hex2digits_p[assign_a(b)] >> - !hex2digits_p[assign_a(a)] - ) - , - +space_p).full; - if (res) - { - c.setRgb(r,g,b); - return true; - } - - double h,s,v; - res = parse(str, - ( - real_p[assign_a(h)] >> !ch_p(',') >> real_p[assign_a(s)] >> !ch_p(',') >> real_p[assign_a(v)] - ) - , - +space_p).full; - if (res) - { - c.setHsv(int(255*h),int(255*s),int(255*v)); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing spline..." << QString::fromStdString(str); + char e = 'n', s = 'n'; + int sx, sy, ex, ey; + QPair p; + bool res; + res = parse(str, + (!(ch_p('e')[assign_a(e)] >> ',' >> int_p[assign_a(ex)] >> ',' >> int_p[assign_a(ey)]) >> !(ch_p('s')[assign_a(s)] >> ',' >> int_p[assign_a(sx)] >> ',' >> int_p[assign_a(sy)]) >> + ((int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)]))[push_back_a(points, p)] >> + +((int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points, p)] >> (int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points, p)] >> + (int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points, p)])), + +space_p) + .full; + if (!res) + return false; + if (s == 's') { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "inserting the s point"; + points.insert(points.begin(), qMakePair(float(sx), float(sy))); + } + if (e == 'e') { + // points.insert(points.begin(), qMakePair(float(ex),float(ey))); + } return true; - } - return false; -} - -bool parse_real(char const* str, double& d) -{ - return parse(str, - ( - real_p[assign_a(d)] - ) - , - +space_p).full; -} - -bool parse_integers(char const* str, std::vector& v) -{ - return parse(str, - ( - int_p[push_back_a(v)] >> *(',' >> int_p[push_back_a(v)]) - ) - , - +space_p).full; -} - -bool parse_spline(char const* str, QVector< QPair< float, float > >& points) -{ -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing spline..." << QString::fromStdString(str); - char e = 'n', s = 'n'; - int sx,sy,ex,ey; - QPair< float, float > p; - bool res; - res = parse(str, - ( - !(ch_p('e')[assign_a(e)] >> ',' >> int_p[assign_a(ex)] >> ',' >> int_p[assign_a(ey)]) - >> !(ch_p('s')[assign_a(s)] >> ',' >> int_p[assign_a(sx)] >> ',' >> int_p[assign_a(sy)]) - >> ((int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)]))[push_back_a(points,p)] - >> +( - (int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points,p)] >> - (int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points,p)] >> - (int_p[assign_a(p.first)] >> ',' >> int_p[assign_a(p.second)])[push_back_a(points,p)] - ) - ) - , - +space_p).full; - if (!res) return false; - if (s == 's') - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "inserting the s point"; - points.insert(points.begin(), qMakePair(float(sx),float(sy))); - } - if (e == 'e') - { -// points.insert(points.begin(), qMakePair(float(ex),float(ey))); - } - return true; -} - -DotRenderOp renderop ; - -DotRenderOpVec* renderopvec = nullptr; +} + +DotRenderOp renderop; + +DotRenderOpVec *renderopvec = nullptr; void init_op() { - renderop = DotRenderOp(); + renderop = DotRenderOp(); } -void valid_op(char const* first, char const* last) +void valid_op(char const *first, char const *last) { - std::string s(first, last); - renderop.renderop = QString::fromUtf8(therenderop.c_str()); - renderop.str = QString::fromUtf8(thestr.c_str()); + std::string s(first, last); + renderop.renderop = QString::fromUtf8(therenderop.c_str()); + renderop.str = QString::fromUtf8(thestr.c_str()); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Validating render operation '"<push_back(renderop); - renderop.renderop = ""; - renderop.integers = QList(); - renderop.str = ""; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Validating render operation '"<push_back(renderop); + renderop.renderop = ""; + renderop.integers = QList(); + renderop.str = ""; } -bool parse_renderop(const std::string& str, DotRenderOpVec& arenderopvec) +bool parse_renderop(const std::string &str, DotRenderOpVec &arenderopvec) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromUtf8(str.c_str()) << str.size(); - if (str.empty()) - { - return false; - } - init_op(); - renderopvec = &arenderopvec; - bool res; - int c; - res = parse(str.c_str(), - ( - +( - ( - (ch_p('E')|ch_p('e'))[assign_a(therenderop)] >> +space_p >> - repeat_p(4)[int_p[push_back_a(renderop.integers)] >> !((ch_p(',')|ch_p('.')) >> int_p) >> +space_p] - )[&valid_op] - | ( - (ch_p('P')|ch_p('p')|ch_p('L')|ch_p('B')|ch_p('b'))[assign_a(therenderop)] >> +space_p >> - int_p[assign_a(c)][push_back_a(renderop.integers)] >> +space_p >> - repeat_p(boost::ref(c))[ - int_p[push_back_a(renderop.integers)] >> !((ch_p(',')|ch_p('.')) >> int_p) >> +space_p >> - int_p[push_back_a(renderop.integers)] >> !((ch_p(',')|ch_p('.')) >> int_p) >> +space_p - ] - )[&valid_op] - // "T 1537 228 0 40 9 -#1 (== 0) T 1537 217 0 90 19 -MAIN:./main/main.pl " - // T x y j w n -b1b2...bn Text drawn using the baseline point (x,y). The text consists of the n bytes following '-'. The text should be left-aligned (centered, right-aligned) on the point if j is -1 (0, 1), respectively. The value w gives the width of the text as computed by the library. - // I x y w h n -b1b2...bn Externally-specified image drawn in the box with lower left corner (x,y) and upper right corner (x+w,y+h). The name of the image consists of the n bytes following '-'. This is usually a bitmap image. Note that the image size, even when converted from pixels to points, might be different from the required size (w,h). It is assumed the renderer will perform the necessary scaling. (1.2) - | ( - (ch_p('T')|ch_p('I'))[assign_a(therenderop)] >> +space_p >> - repeat_p(4)[int_p[push_back_a(renderop.integers)] >> !((ch_p(',')|ch_p('.')) >> int_p) >> +space_p] >> - int_p[assign_a(c)] >> +space_p >> '-' >> - (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p - )[&valid_op] - // c 9 -#000000ff - | ( - (ch_p('C')|ch_p('c')|ch_p('S'))[assign_a(therenderop)] >> +space_p >> - int_p[assign_a(c)] >> +space_p >> '-' >> - (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p - )[&valid_op] - // t 0 - // t f Set font characteristics. The integer f is the OR of BOLD=1, ITALIC=2, UNDERLINE=4, SUPERSCRIPT=8, SUBSCRIPT=16, (1.5) STRIKE-THROUGH=32 (1.6), and OVERLINE=64 (1.7). - | ( - (ch_p('t'))[assign_a(therenderop)] >> +space_p >> - int_p[assign_a(c)] >> +space_p - )[&valid_op] - // F 14,000000 11 -Times-Roman - | ( - ch_p('F')[assign_a(therenderop)] >> +space_p >> - int_p[push_back_a(renderop.integers)] >> !((ch_p(',')|ch_p('.')) >> int_p) >> +space_p >> - int_p[assign_a(c)] >> +space_p >> '-' >> - (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p - )[&valid_op] - ) - ) >> !end_p - ).full; - if (res ==false) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "ERROR: parse_renderop failed on "<< QString::fromStdString(str); - qCWarning(KGRAPHVIEWERLIB_LOG) << " Last renderop string is "<> end_p, (+boost::spirit::classic::space_p|boost::spirit::classic::comment_p("/*", "*/"))).full; + // qCDebug(KGRAPHVIEWERLIB_LOG) << QString::fromUtf8(str.c_str()) << str.size(); + if (str.empty()) { + return false; + } + init_op(); + renderopvec = &arenderopvec; + bool res; + int c; + res = parse(str.c_str(), + (+(((ch_p('E') | ch_p('e'))[assign_a(therenderop)] >> +space_p >> repeat_p(4)[int_p[push_back_a(renderop.integers)] >> !((ch_p(',') | ch_p('.')) >> int_p) >> +space_p])[&valid_op] | + ((ch_p('P') | ch_p('p') | ch_p('L') | ch_p('B') | ch_p('b'))[assign_a(therenderop)] >> +space_p >> int_p[assign_a(c)][push_back_a(renderop.integers)] >> +space_p >> + repeat_p(boost::ref(c))[int_p[push_back_a(renderop.integers)] >> !((ch_p(',') | ch_p('.')) >> int_p) >> +space_p >> int_p[push_back_a(renderop.integers)] >> !((ch_p(',') | ch_p('.')) >> int_p) >> +space_p])[&valid_op] + // "T 1537 228 0 40 9 -#1 (== 0) T 1537 217 0 90 19 -MAIN:./main/main.pl " + // T x y j w n -b1b2...bn Text drawn using the baseline point (x,y). The text consists of the n bytes following '-'. The text should be left-aligned (centered, right-aligned) on the point if j is -1 (0, 1), + // respectively. The value w gives the width of the text as computed by the library. I x y w h n -b1b2...bn Externally-specified image drawn in the box with lower left corner (x,y) and upper right corner (x+w,y+h). The + // name of the image consists of the n bytes following '-'. This is usually a bitmap image. Note that the image size, even when converted from pixels to points, might be different from the required size (w,h). It is + // assumed the renderer will perform the necessary scaling. (1.2) + | ((ch_p('T') | ch_p('I'))[assign_a(therenderop)] >> +space_p >> repeat_p(4)[int_p[push_back_a(renderop.integers)] >> !((ch_p(',') | ch_p('.')) >> int_p) >> +space_p] >> int_p[assign_a(c)] >> +space_p >> '-' >> + (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p)[&valid_op] + // c 9 -#000000ff + | ((ch_p('C') | ch_p('c') | ch_p('S'))[assign_a(therenderop)] >> +space_p >> int_p[assign_a(c)] >> +space_p >> '-' >> (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p)[&valid_op] + // t 0 + // t f Set font characteristics. The integer f is the OR of BOLD=1, ITALIC=2, UNDERLINE=4, SUPERSCRIPT=8, SUBSCRIPT=16, (1.5) STRIKE-THROUGH=32 (1.6), and OVERLINE=64 (1.7). + | ((ch_p('t'))[assign_a(therenderop)] >> +space_p >> int_p[assign_a(c)] >> +space_p)[&valid_op] + // F 14,000000 11 -Times-Roman + | (ch_p('F')[assign_a(therenderop)] >> +space_p >> int_p[push_back_a(renderop.integers)] >> !((ch_p(',') | ch_p('.')) >> int_p) >> +space_p >> int_p[assign_a(c)] >> +space_p >> '-' >> + (repeat_p(boost::ref(c))[anychar_p])[assign_a(thestr)] >> +space_p)[&valid_op])) >> + !end_p) + .full; + if (res == false) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "ERROR: parse_renderop failed on " << QString::fromStdString(str); + qCWarning(KGRAPHVIEWERLIB_LOG) << " Last renderop string is " << QString::fromStdString(str.c_str()); + } + // delete renderop; renderop = 0; + return res; } +bool parse(const std::string &str) +{ + DotGrammar g; + return boost::spirit::classic::parse(str.c_str(), g >> end_p, (+boost::spirit::classic::space_p | boost::spirit::classic::comment_p("/*", "*/"))).full; +} diff --git a/src/part/dotgraph.h b/src/part/dotgraph.h --- a/src/part/dotgraph.h +++ b/src/part/dotgraph.h @@ -24,151 +24,231 @@ #define DOT_GRAPH_H #include +#include +#include #include #include -#include -#include #include -#include "kgraphviewer_export.h" +#include "dotdefaults.h" +#include "graphedge.h" #include "graphelement.h" -#include "graphsubgraph.h" #include "graphnode.h" -#include "graphedge.h" -#include "dotdefaults.h" +#include "graphsubgraph.h" +#include "kgraphviewer_export.h" namespace KGraphViewer { - /** - * A class representing the model of a Graphviz DOT graph - */ + * A class representing the model of a Graphviz DOT graph + */ class DotGraph : public GraphElement { - Q_OBJECT + Q_OBJECT public: - enum ParsePhase {Initial, Final}; - - DotGraph(); - DotGraph(const QString& command, const QString& fileName); - - ~DotGraph() override; - - QString chooseLayoutProgramForFile(const QString& str); - bool parseDot(const QString& str); - - /** Constant accessor to the nodes of this graph */ - inline const GraphNodeMap& nodes() const {return m_nodesMap;} - /** Constant accessor to the edges of this graph */ - inline const GraphEdgeMap& edges() const {return m_edgesMap;} - inline const GraphSubgraphMap& subgraphs() const {return m_subgraphsMap;} - /** Accessor to the nodes of this graph */ - inline GraphNodeMap& nodes() {return m_nodesMap;} - /** Accessor to the edges of this graph */ - inline GraphEdgeMap& edges() {return m_edgesMap;} - inline GraphSubgraphMap& subgraphs() {return m_subgraphsMap;} - double width() const {return m_width;} - double height() const {return m_height;} - double scale() const {return m_scale;} - void width(double w) {m_width = w;} - void height(double h) {m_height = h;} - void scale(double s) {m_scale = s;} - QString backColor() const override; - - inline void strict(bool s) {m_strict = s;} - inline void directed(bool d) {m_directed = d;} - inline bool strict() const {return m_strict;} - inline bool directed() const {return m_directed;} - - QSet< GraphNode* >& nodesOfCell(unsigned int id); - - inline unsigned int horizCellFactor() const {return m_horizCellFactor;} - inline unsigned int vertCellFactor() const {return m_vertCellFactor;} - inline double wdhcf() const {return m_wdhcf;} - inline double hdvcf() const {return m_hdvcf;} - - inline void layoutCommand(const QString& command) {m_layoutCommand = command;} - inline const QString& layoutCommand() {return m_layoutCommand;} - - inline void dotFileName(const QString& fileName) {m_dotFileName = fileName;} - inline const QString& dotFileName() const {return m_dotFileName;} - - bool update(); - - inline void setReadWrite() {m_readWrite = true;} - inline void setReadOnly() {m_readWrite = false;} - - void storeOriginalAttributes() override; - - void KGRAPHVIEWER_EXPORT saveTo(const QString& fileName); - - void updateWithGraph(graph_t* newGraph); - void updateWithGraph(const DotGraph& graph); - - void KGRAPHVIEWER_EXPORT setAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue); - - GraphElement* elementNamed(const QString& id); - - inline void setUseLibrary(bool value) {m_useLibrary = value;} - inline bool useLibrary() {return m_useLibrary;} - - void KGRAPHVIEWER_EXPORT setGraphAttributes(QMap attribs); - void KGRAPHVIEWER_EXPORT addNewNode(QMap attribs); - void KGRAPHVIEWER_EXPORT addNewSubgraph(QMap attribs); - void KGRAPHVIEWER_EXPORT addNewNodeToSubgraph(QMap attribs, QString subgraph); - void KGRAPHVIEWER_EXPORT addExistingNodeToSubgraph(QMap attribs,QString subgraph); - void KGRAPHVIEWER_EXPORT moveExistingNodeToMainGraph(QMap attribs); - void KGRAPHVIEWER_EXPORT addNewEdge(QString src, QString tgt, QMap attribs); - using GraphElement::removeAttribute; - void KGRAPHVIEWER_EXPORT removeAttribute(const QString& nodeName, const QString& attribName); - void KGRAPHVIEWER_EXPORT renameNode(const QString& oldNodeName, const QString& newNodeName); - void KGRAPHVIEWER_EXPORT removeNodeNamed(const QString& nodeName); - void KGRAPHVIEWER_EXPORT removeNodeFromSubgraph(const QString& nodeName, const QString& subgraphName); - void KGRAPHVIEWER_EXPORT removeSubgraphNamed(const QString& subgraphName); - void KGRAPHVIEWER_EXPORT removeEdge(const QString& id); - void KGRAPHVIEWER_EXPORT removeElement(const QString& id); + enum ParsePhase { Initial, Final }; + + DotGraph(); + DotGraph(const QString &command, const QString &fileName); + + ~DotGraph() override; + + QString chooseLayoutProgramForFile(const QString &str); + bool parseDot(const QString &str); + + /** Constant accessor to the nodes of this graph */ + inline const GraphNodeMap &nodes() const + { + return m_nodesMap; + } + /** Constant accessor to the edges of this graph */ + inline const GraphEdgeMap &edges() const + { + return m_edgesMap; + } + inline const GraphSubgraphMap &subgraphs() const + { + return m_subgraphsMap; + } + /** Accessor to the nodes of this graph */ + inline GraphNodeMap &nodes() + { + return m_nodesMap; + } + /** Accessor to the edges of this graph */ + inline GraphEdgeMap &edges() + { + return m_edgesMap; + } + inline GraphSubgraphMap &subgraphs() + { + return m_subgraphsMap; + } + double width() const + { + return m_width; + } + double height() const + { + return m_height; + } + double scale() const + { + return m_scale; + } + void width(double w) + { + m_width = w; + } + void height(double h) + { + m_height = h; + } + void scale(double s) + { + m_scale = s; + } + QString backColor() const override; + + inline void strict(bool s) + { + m_strict = s; + } + inline void directed(bool d) + { + m_directed = d; + } + inline bool strict() const + { + return m_strict; + } + inline bool directed() const + { + return m_directed; + } + + QSet &nodesOfCell(unsigned int id); + + inline unsigned int horizCellFactor() const + { + return m_horizCellFactor; + } + inline unsigned int vertCellFactor() const + { + return m_vertCellFactor; + } + inline double wdhcf() const + { + return m_wdhcf; + } + inline double hdvcf() const + { + return m_hdvcf; + } + + inline void layoutCommand(const QString &command) + { + m_layoutCommand = command; + } + inline const QString &layoutCommand() + { + return m_layoutCommand; + } + + inline void dotFileName(const QString &fileName) + { + m_dotFileName = fileName; + } + inline const QString &dotFileName() const + { + return m_dotFileName; + } + + bool update(); + + inline void setReadWrite() + { + m_readWrite = true; + } + inline void setReadOnly() + { + m_readWrite = false; + } + + void storeOriginalAttributes() override; + + void KGRAPHVIEWER_EXPORT saveTo(const QString &fileName); + + void updateWithGraph(graph_t *newGraph); + void updateWithGraph(const DotGraph &graph); + + void KGRAPHVIEWER_EXPORT setAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue); + + GraphElement *elementNamed(const QString &id); + + inline void setUseLibrary(bool value) + { + m_useLibrary = value; + } + inline bool useLibrary() + { + return m_useLibrary; + } + + void KGRAPHVIEWER_EXPORT setGraphAttributes(QMap attribs); + void KGRAPHVIEWER_EXPORT addNewNode(QMap attribs); + void KGRAPHVIEWER_EXPORT addNewSubgraph(QMap attribs); + void KGRAPHVIEWER_EXPORT addNewNodeToSubgraph(QMap attribs, QString subgraph); + void KGRAPHVIEWER_EXPORT addExistingNodeToSubgraph(QMap attribs, QString subgraph); + void KGRAPHVIEWER_EXPORT moveExistingNodeToMainGraph(QMap attribs); + void KGRAPHVIEWER_EXPORT addNewEdge(QString src, QString tgt, QMap attribs); + using GraphElement::removeAttribute; + void KGRAPHVIEWER_EXPORT removeAttribute(const QString &nodeName, const QString &attribName); + void KGRAPHVIEWER_EXPORT renameNode(const QString &oldNodeName, const QString &newNodeName); + void KGRAPHVIEWER_EXPORT removeNodeNamed(const QString &nodeName); + void KGRAPHVIEWER_EXPORT removeNodeFromSubgraph(const QString &nodeName, const QString &subgraphName); + void KGRAPHVIEWER_EXPORT removeSubgraphNamed(const QString &subgraphName); + void KGRAPHVIEWER_EXPORT removeEdge(const QString &id); + void KGRAPHVIEWER_EXPORT removeElement(const QString &id); Q_SIGNALS: - void readyToDisplay(); + void readyToDisplay(); private Q_SLOTS: - void slotDotRunningDone(int,QProcess::ExitStatus); - void slotDotRunningError(QProcess::ProcessError); - + void slotDotRunningDone(int, QProcess::ExitStatus); + void slotDotRunningError(QProcess::ProcessError); + private: - unsigned int cellNumber(int x, int y); - void computeCells(); - QByteArray getDotResult(int exitCode, QProcess::ExitStatus exitStatus); - - QString m_dotFileName; - GraphSubgraphMap m_subgraphsMap; - GraphNodeMap m_nodesMap; - GraphEdgeMap m_edgesMap; - double m_width, m_height; - double m_scale; - bool m_directed; - bool m_strict; - QString m_layoutCommand; - - unsigned int m_horizCellFactor, m_vertCellFactor; - QVector< QSet< GraphNode* > > m_cells; - - double m_wdhcf, m_hdvcf; - - bool m_readWrite; - QProcess* m_dot; - - ParsePhase m_phase; - - QMutex m_dotProcessMutex; - - bool m_useLibrary; -}; + unsigned int cellNumber(int x, int y); + void computeCells(); + QByteArray getDotResult(int exitCode, QProcess::ExitStatus exitStatus); -} + QString m_dotFileName; + GraphSubgraphMap m_subgraphsMap; + GraphNodeMap m_nodesMap; + GraphEdgeMap m_edgesMap; + double m_width, m_height; + double m_scale; + bool m_directed; + bool m_strict; + QString m_layoutCommand; -#endif + unsigned int m_horizCellFactor, m_vertCellFactor; + QVector> m_cells; + + double m_wdhcf, m_hdvcf; + bool m_readWrite; + QProcess *m_dot; + ParsePhase m_phase; + QMutex m_dotProcessMutex; + + bool m_useLibrary; +}; + +} + +#endif diff --git a/src/part/dotgraph.cpp b/src/part/dotgraph.cpp --- a/src/part/dotgraph.cpp +++ b/src/part/dotgraph.cpp @@ -17,990 +17,869 @@ */ #include "dotgraph.h" -#include "dotgrammar.h" -#include "graphexporter.h" #include "DotGraphParsingHelper.h" #include "canvasedge.h" #include "canvassubgraph.h" -#include "layoutagraphthread.h" +#include "dotgrammar.h" +#include "graphexporter.h" #include "kgraphviewerlib_debug.h" +#include "layoutagraphthread.h" -#include -#include -#include #include "fdstream.hpp" #include #include +#include +#include +#include #include +#include #include +#include #include -#include #include -#include #include #include using namespace boost; using namespace boost::spirit::classic; -extern KGraphViewer::DotGraphParsingHelper* phelper; - +extern KGraphViewer::DotGraphParsingHelper *phelper; namespace KGraphViewer { - - const distinct_parser<> keyword_p("0-9a-zA-Z_"); -DotGraph::DotGraph() : - GraphElement(), - m_dotFileName(""),m_width(0.0), m_height(0.0),m_scale(1.0), - m_directed(true),m_strict(false), - m_layoutCommand(""), - m_horizCellFactor(0), m_vertCellFactor(0), - m_wdhcf(0), m_hdvcf(0), - m_readWrite(false), - m_dot(nullptr), - m_phase(Initial), - m_useLibrary(false) -{ - setId("unnamed"); -} +DotGraph::DotGraph() + : GraphElement() + , m_dotFileName("") + , m_width(0.0) + , m_height(0.0) + , m_scale(1.0) + , m_directed(true) + , m_strict(false) + , m_layoutCommand("") + , m_horizCellFactor(0) + , m_vertCellFactor(0) + , m_wdhcf(0) + , m_hdvcf(0) + , m_readWrite(false) + , m_dot(nullptr) + , m_phase(Initial) + , m_useLibrary(false) +{ + setId("unnamed"); +} + +DotGraph::DotGraph(const QString &command, const QString &fileName) + : GraphElement() + , m_dotFileName(fileName) + , m_width(0.0) + , m_height(0.0) + , m_scale(1.0) + , m_directed(true) + , m_strict(false) + , m_layoutCommand(command) + , m_horizCellFactor(0) + , m_vertCellFactor(0) + , m_wdhcf(0) + , m_hdvcf(0) + , m_readWrite(false) + , m_dot(nullptr) + , m_phase(Initial) + , m_useLibrary(false) +{ + setId("unnamed"); +} + +DotGraph::~DotGraph() +{ + qDeleteAll(m_subgraphsMap); + m_subgraphsMap.clear(); + qDeleteAll(m_nodesMap); + m_nodesMap.clear(); + qDeleteAll(m_edgesMap); + m_edgesMap.clear(); +} + +QString DotGraph::chooseLayoutProgramForFile(const QString &str) +{ + QFile iFILE(str); + + if (!iFILE.open(QIODevice::ReadOnly)) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Can't test dot file. Will try to use the dot command on the file: '" << str << "'" << endl; + return "dot"; // -Txdot"; + } -DotGraph::DotGraph(const QString& command, const QString& fileName) : - GraphElement(), - m_dotFileName(fileName),m_width(0.0), m_height(0.0),m_scale(1.0), - m_directed(true),m_strict(false), - m_layoutCommand(command), - m_horizCellFactor(0), m_vertCellFactor(0), - m_wdhcf(0), m_hdvcf(0), - m_readWrite(false), - m_dot(nullptr), - m_phase(Initial), - m_useLibrary(false) -{ - setId("unnamed"); -} + QByteArray fileContent = iFILE.readAll(); + if (fileContent.isEmpty()) + return ""; + std::string s = fileContent.data(); + std::string cmd = "dot"; + parse(s.c_str(), (!(keyword_p("strict")) >> (keyword_p("graph")[assign_a(cmd, "neato")])), (space_p | comment_p("/*", "*/"))); -DotGraph::~DotGraph() -{ - qDeleteAll(m_subgraphsMap); - m_subgraphsMap.clear(); - qDeleteAll(m_nodesMap); - m_nodesMap.clear(); - qDeleteAll(m_edgesMap); - m_edgesMap.clear(); + return QString::fromStdString(cmd); // + " -Txdot" ; } -QString DotGraph::chooseLayoutProgramForFile(const QString& str) +bool DotGraph::parseDot(const QString &str) { - QFile iFILE(str); - - if (!iFILE.open(QIODevice::ReadOnly)) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Can't test dot file. Will try to use the dot command on the file: '" << str << "'" << endl; - return "dot";// -Txdot"; - } - - QByteArray fileContent = iFILE.readAll(); - if (fileContent.isEmpty()) return ""; - std::string s = fileContent.data(); - std::string cmd = "dot"; - parse(s.c_str(), - ( - !(keyword_p("strict")) >> (keyword_p("graph")[assign_a(cmd,"neato")]) - ), (space_p|comment_p("/*", "*/")) ); - - return QString::fromStdString(cmd);// + " -Txdot" ; -} + qCDebug(KGRAPHVIEWERLIB_LOG) << str; + m_useLibrary = false; + if (m_layoutCommand.isEmpty()) { + m_layoutCommand = chooseLayoutProgramForFile(str); + if (m_layoutCommand.isEmpty()) { + m_layoutCommand = chooseLayoutProgramForFile(str); + return false; + } + } -bool DotGraph::parseDot(const QString& str) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << str; - m_useLibrary = false; - if (m_layoutCommand.isEmpty()) - { - m_layoutCommand = chooseLayoutProgramForFile(str); - if (m_layoutCommand.isEmpty()) - { - m_layoutCommand = chooseLayoutProgramForFile(str); - return false; - } - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "Running " << m_layoutCommand << str; - QStringList options; - /// @TODO handle the non-dot commands that could don't know the -T option -// if (m_readWrite && m_phase == Initial) -// { -// options << "-Tdot"; -// } -// else -// { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Running " << m_layoutCommand << str; + QStringList options; + /// @TODO handle the non-dot commands that could don't know the -T option + // if (m_readWrite && m_phase == Initial) + // { + // options << "-Tdot"; + // } + // else + // { options << "-Txdot"; -// } - options << str; - - qCDebug(KGRAPHVIEWERLIB_LOG) << "m_dot is " << m_dot << ". Acquiring mutex"; - QMutexLocker locker(&m_dotProcessMutex); - qCDebug(KGRAPHVIEWERLIB_LOG) << "mutex acquired "; - if (m_dot) - { - disconnect(m_dot, nullptr, this, nullptr); - m_dot->kill(); - delete m_dot; - } - m_dot = new QProcess(); - connect(m_dot, static_cast(&QProcess::finished), - this, &DotGraph::slotDotRunningDone); - connect(m_dot, static_cast(&QProcess::error), - this, &DotGraph::slotDotRunningError); - m_dot->start(m_layoutCommand, options); - qCDebug(KGRAPHVIEWERLIB_LOG) << "process started"; - return true; + // } + options << str; + + qCDebug(KGRAPHVIEWERLIB_LOG) << "m_dot is " << m_dot << ". Acquiring mutex"; + QMutexLocker locker(&m_dotProcessMutex); + qCDebug(KGRAPHVIEWERLIB_LOG) << "mutex acquired "; + if (m_dot) { + disconnect(m_dot, nullptr, this, nullptr); + m_dot->kill(); + delete m_dot; + } + m_dot = new QProcess(); + connect(m_dot, static_cast(&QProcess::finished), this, &DotGraph::slotDotRunningDone); + connect(m_dot, static_cast(&QProcess::error), this, &DotGraph::slotDotRunningError); + m_dot->start(m_layoutCommand, options); + qCDebug(KGRAPHVIEWERLIB_LOG) << "process started"; + return true; } bool DotGraph::update() { - GraphExporter exporter; - if (!m_useLibrary) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "command"; - QString str = exporter.writeDot(this); - return parseDot(str); - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "library"; - graph_t* graph = exporter.exportToGraphviz(this); - - GVC_t* gvc = gvContext(); - threadsafe_wrap_gvLayout(gvc, graph, m_layoutCommand.toUtf8().data()); - threadsafe_wrap_gvRender(gvc, graph, "xdot", nullptr); - - updateWithGraph(graph); - - gvFreeLayout(gvc, graph); - agclose(graph); - bool result = true; //(gvFreeContext(gvc) == 0); - return result; - } + GraphExporter exporter; + if (!m_useLibrary) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "command"; + QString str = exporter.writeDot(this); + return parseDot(str); + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "library"; + graph_t *graph = exporter.exportToGraphviz(this); + + GVC_t *gvc = gvContext(); + threadsafe_wrap_gvLayout(gvc, graph, m_layoutCommand.toUtf8().data()); + threadsafe_wrap_gvRender(gvc, graph, "xdot", nullptr); + + updateWithGraph(graph); + + gvFreeLayout(gvc, graph); + agclose(graph); + bool result = true; //(gvFreeContext(gvc) == 0); + return result; + } } -QByteArray DotGraph::getDotResult(int , QProcess::ExitStatus ) +QByteArray DotGraph::getDotResult(int, QProcess::ExitStatus) { - qCDebug(KGRAPHVIEWERLIB_LOG); + qCDebug(KGRAPHVIEWERLIB_LOG); - QMutexLocker locker(&m_dotProcessMutex); - if (m_dot == nullptr) - { - return QByteArray(); - } - QByteArray result = m_dot->readAll(); - delete m_dot; - m_dot = nullptr; - return result; + QMutexLocker locker(&m_dotProcessMutex); + if (m_dot == nullptr) { + return QByteArray(); + } + QByteArray result = m_dot->readAll(); + delete m_dot; + m_dot = nullptr; + return result; } void DotGraph::slotDotRunningDone(int exitCode, QProcess::ExitStatus exitStatus) { - qCDebug(KGRAPHVIEWERLIB_LOG); - - QByteArray result = getDotResult(exitCode, exitStatus); - result.replace("\\\n",""); - - qCDebug(KGRAPHVIEWERLIB_LOG) << "string content is:" << endl << result << endl << "=====================" << result.size(); - std::string s = result.data(); - // std::cerr << "stdstring content is:" << std::endl << s << std::endl << "===================== " << s.size() << std::endl; - if (phelper) - { - phelper->graph = nullptr; + qCDebug(KGRAPHVIEWERLIB_LOG); + + QByteArray result = getDotResult(exitCode, exitStatus); + result.replace("\\\n", ""); + + qCDebug(KGRAPHVIEWERLIB_LOG) << "string content is:" << endl << result << endl << "=====================" << result.size(); + std::string s = result.data(); + // std::cerr << "stdstring content is:" << std::endl << s << std::endl << "===================== " << s.size() << std::endl; + if (phelper) { + phelper->graph = nullptr; + delete phelper; + } + // if (parsingResult) + // { + // if (m_readWrite) + // { + // storeOriginalAttributes(); + // update(); + // } + // computeCells(); + // } + + DotGraph newGraph(m_layoutCommand, m_dotFileName); + phelper = new DotGraphParsingHelper; + phelper->graph = &newGraph; + phelper->z = 1; + phelper->maxZ = 1; + phelper->uniq = 0; + + qCDebug(KGRAPHVIEWERLIB_LOG) << "parsing new dot"; + bool parsingResult = parse(s); delete phelper; - } -// if (parsingResult) -// { -// if (m_readWrite) -// { -// storeOriginalAttributes(); -// update(); -// } -// computeCells(); -// } - - DotGraph newGraph(m_layoutCommand, m_dotFileName); - phelper = new DotGraphParsingHelper; - phelper->graph = &newGraph; - phelper->z = 1; - phelper->maxZ = 1; - phelper->uniq = 0; - - qCDebug(KGRAPHVIEWERLIB_LOG) << "parsing new dot"; - bool parsingResult = parse(s); - delete phelper; - phelper = nullptr; - qCDebug(KGRAPHVIEWERLIB_LOG) << "phelper deleted"; - - if (parsingResult) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "calling updateWithGraph"; - updateWithGraph(newGraph); - } - else - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "parsing failed"; - } -// return parsingResult; -// if (m_readWrite && m_phase == Initial) -// { -// m_phase = Final; -// update(); -// } -// else -// { + phelper = nullptr; + qCDebug(KGRAPHVIEWERLIB_LOG) << "phelper deleted"; + + if (parsingResult) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "calling updateWithGraph"; + updateWithGraph(newGraph); + } else { + qCWarning(KGRAPHVIEWERLIB_LOG) << "parsing failed"; + } + // return parsingResult; + // if (m_readWrite && m_phase == Initial) + // { + // m_phase = Final; + // update(); + // } + // else + // { qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting readyToDisplay"; emit(readyToDisplay()); -// } + // } } void DotGraph::slotDotRunningError(QProcess::ProcessError error) { - qCWarning(KGRAPHVIEWERLIB_LOG) << "DotGraph::slotDotRunningError" << error; - switch (error) - { + qCWarning(KGRAPHVIEWERLIB_LOG) << "DotGraph::slotDotRunningError" << error; + switch (error) { case QProcess::FailedToStart: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Unable to start %1.", m_layoutCommand)); - break; + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Unable to start %1.", m_layoutCommand)); + break; case QProcess::Crashed: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("%1 crashed.", m_layoutCommand)); - break; + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("%1 crashed.", m_layoutCommand)); + break; case QProcess::Timedout: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("%1 timed out.", m_layoutCommand)); - break; + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("%1 timed out.", m_layoutCommand)); + break; case QProcess::WriteError: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Was not able to write data to the %1 process.", m_layoutCommand)); - break; + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Was not able to write data to the %1 process.", m_layoutCommand)); + break; case QProcess::ReadError: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Was not able to read data from the %1 process.", m_layoutCommand)); - break; + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Was not able to read data from the %1 process.", m_layoutCommand)); + break; default: - QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Unknown error running %1.", m_layoutCommand)); - } + QMessageBox::critical(nullptr, i18n("Layout process failed"), i18n("Unknown error running %1.", m_layoutCommand)); + } } unsigned int DotGraph::cellNumber(int x, int y) { -/* qCDebug(KGRAPHVIEWERLIB_LOG) << "x= " << x << ", y= " << y << ", m_width= " << m_width << ", m_height= " << m_height << ", m_horizCellFactor= " << m_horizCellFactor << ", m_vertCellFactor= " << m_vertCellFactor << ", m_wdhcf= " << m_wdhcf << ", m_hdvcf= " << m_hdvcf;*/ - - unsigned int nx = (unsigned int)(( x - ( x % int(m_wdhcf) ) ) / m_wdhcf); - unsigned int ny = (unsigned int)(( y - ( y % int(m_hdvcf) ) ) / m_hdvcf); -/* qCDebug(KGRAPHVIEWERLIB_LOG) << "nx = " << (unsigned int)(( x - ( x % int(m_wdhcf) ) ) / m_wdhcf); - qCDebug(KGRAPHVIEWERLIB_LOG) << "ny = " << (unsigned int)(( y - ( y % int(m_hdvcf) ) ) / m_hdvcf); - qCDebug(KGRAPHVIEWERLIB_LOG) << "res = " << ny * m_horizCellFactor + nx;*/ - - unsigned int res = ny * m_horizCellFactor + nx; - return res; + /* qCDebug(KGRAPHVIEWERLIB_LOG) << "x= " << x << ", y= " << y << ", m_width= " << m_width << ", m_height= " << m_height << ", m_horizCellFactor= " << m_horizCellFactor << ", m_vertCellFactor= " << m_vertCellFactor << ", m_wdhcf= " << + * m_wdhcf << ", m_hdvcf= " << m_hdvcf;*/ + + unsigned int nx = (unsigned int)((x - (x % int(m_wdhcf))) / m_wdhcf); + unsigned int ny = (unsigned int)((y - (y % int(m_hdvcf))) / m_hdvcf); + /* qCDebug(KGRAPHVIEWERLIB_LOG) << "nx = " << (unsigned int)(( x - ( x % int(m_wdhcf) ) ) / m_wdhcf); + qCDebug(KGRAPHVIEWERLIB_LOG) << "ny = " << (unsigned int)(( y - ( y % int(m_hdvcf) ) ) / m_hdvcf); + qCDebug(KGRAPHVIEWERLIB_LOG) << "res = " << ny * m_horizCellFactor + nx;*/ + + unsigned int res = ny * m_horizCellFactor + nx; + return res; } #define MAXCELLWEIGHT 800 void DotGraph::computeCells() { - return; - qCDebug(KGRAPHVIEWERLIB_LOG) << m_width << m_height << endl; - m_horizCellFactor = m_vertCellFactor = 1; - m_wdhcf = (int)ceil(((double)m_width) / m_horizCellFactor)+1; - m_hdvcf = (int)ceil(((double)m_height) / m_vertCellFactor)+1; - bool stop = true; - do - { - stop = true; - m_cells.clear(); -// m_cells.resize(m_horizCellFactor * m_vertCellFactor); - - GraphNodeMap::iterator it, it_end; - it = m_nodesMap.begin(); it_end = m_nodesMap.end(); - for (; it != it_end; it++) - { - GraphNode* gn = *it; -// int cellNum = cellNumber(int(gn->x()), int(gn->y())); - int cellNum = cellNumber(0,0); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Found cell number " << cellNum; - - if (m_cells.size() <= cellNum) - { - m_cells.resize(cellNum+1); - } - m_cells[cellNum].insert(gn); - - qCDebug(KGRAPHVIEWERLIB_LOG) << "after insert"; - if ( m_cells[cellNum].size() > MAXCELLWEIGHT ) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "cell number " << cellNum << " contains " << m_cells[cellNum].size() << " nodes"; - if ((m_width/m_horizCellFactor) > (m_height/m_vertCellFactor)) - { - m_horizCellFactor++; - m_wdhcf = m_width / m_horizCellFactor; - } - else - { - m_vertCellFactor++; - m_hdvcf = m_height / m_vertCellFactor; + return; + qCDebug(KGRAPHVIEWERLIB_LOG) << m_width << m_height << endl; + m_horizCellFactor = m_vertCellFactor = 1; + m_wdhcf = (int)ceil(((double)m_width) / m_horizCellFactor) + 1; + m_hdvcf = (int)ceil(((double)m_height) / m_vertCellFactor) + 1; + bool stop = true; + do { + stop = true; + m_cells.clear(); + // m_cells.resize(m_horizCellFactor * m_vertCellFactor); + + GraphNodeMap::iterator it, it_end; + it = m_nodesMap.begin(); + it_end = m_nodesMap.end(); + for (; it != it_end; it++) { + GraphNode *gn = *it; + // int cellNum = cellNumber(int(gn->x()), int(gn->y())); + int cellNum = cellNumber(0, 0); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Found cell number " << cellNum; + + if (m_cells.size() <= cellNum) { + m_cells.resize(cellNum + 1); + } + m_cells[cellNum].insert(gn); + + qCDebug(KGRAPHVIEWERLIB_LOG) << "after insert"; + if (m_cells[cellNum].size() > MAXCELLWEIGHT) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "cell number " << cellNum << " contains " << m_cells[cellNum].size() << " nodes"; + if ((m_width / m_horizCellFactor) > (m_height / m_vertCellFactor)) { + m_horizCellFactor++; + m_wdhcf = m_width / m_horizCellFactor; + } else { + m_vertCellFactor++; + m_hdvcf = m_height / m_vertCellFactor; + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "cell factor is now " << m_horizCellFactor << " / " << m_vertCellFactor; + stop = false; + break; + } } - qCDebug(KGRAPHVIEWERLIB_LOG) << "cell factor is now " << m_horizCellFactor << " / " << m_vertCellFactor; - stop = false; - break; - } - } - } while (!stop); - qCDebug(KGRAPHVIEWERLIB_LOG) << "m_wdhcf=" << m_wdhcf << "; m_hdvcf=" << m_hdvcf << endl; - qCDebug(KGRAPHVIEWERLIB_LOG) << "finished" << endl; + } while (!stop); + qCDebug(KGRAPHVIEWERLIB_LOG) << "m_wdhcf=" << m_wdhcf << "; m_hdvcf=" << m_hdvcf << endl; + qCDebug(KGRAPHVIEWERLIB_LOG) << "finished" << endl; } -QSet< GraphNode* >& DotGraph::nodesOfCell(unsigned int id) +QSet &DotGraph::nodesOfCell(unsigned int id) { - return m_cells[id]; + return m_cells[id]; } void DotGraph::storeOriginalAttributes() { - foreach (GraphNode* node, nodes()) - { - node->storeOriginalAttributes(); - } - foreach (GraphEdge* edge, edges()) - { - edge->storeOriginalAttributes(); - } - foreach (GraphSubgraph* subgraph, subgraphs()) - { - subgraph->storeOriginalAttributes(); - } - GraphElement::storeOriginalAttributes(); -} - -void DotGraph::saveTo(const QString& fileName) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << fileName; - m_dotFileName = fileName; - GraphExporter exporter; - exporter.writeDot(this, fileName); -} - -void DotGraph::updateWithGraph(graph_t* newGraph) -{ - qCDebug(KGRAPHVIEWERLIB_LOG); - - // copy global graph render operations and attributes - DotRenderOpVec ops; - // decrease mem peak - setRenderOperations(ops); - - if (agget(newGraph, (char*)"_draw_")) - { - parse_renderop(agget(newGraph, (char*)"_draw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); - } - if (agget(newGraph, (char*)"_ldraw_")) - { - parse_renderop(agget(newGraph, (char*)"_ldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); - } - - setRenderOperations(ops); - - Agsym_t *attr = agnxtattr(newGraph, AGRAPH, nullptr); - while(attr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(newGraph) << ":" << attr->name << agxget(newGraph,attr); - m_attributes[attr->name] = agxget(newGraph,attr); - attr = agnxtattr(newGraph, AGRAPH, attr); - } - - // copy subgraphs - for (graph_t* sg = agfstsubg(newGraph); sg; sg = agnxtsubg(sg)) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph:" << agnameof(sg); - if (subgraphs().contains(agnameof(sg))) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; - // ??? - // nodes()[ngn->name]->setZ(ngn->z()); - subgraphs()[agnameof(sg)]->updateWithSubgraph(sg); - if (subgraphs()[agnameof(sg)]->canvasElement()) - { - // nodes()[ngn->id()]->canvasElement()->setGh(m_height); - } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; - GraphSubgraph* newsg = new GraphSubgraph(sg); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - subgraphs().insert(agnameof(sg), newsg); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; - } - - } - - // copy nodes - node_t* ngn = agfstnode(newGraph); - qCDebug(KGRAPHVIEWERLIB_LOG) << "first node:" << (void*)ngn; - - while (ngn) -// foreach (GraphNode* ngn, newGraph.nodes()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << agnameof(ngn); - if (nodes().contains(agnameof(ngn))) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; -// ??? -// nodes()[ngn->name]->setZ(ngn->z()); - nodes()[agnameof(ngn)]->updateWithNode(ngn); - if (nodes()[agnameof(ngn)]->canvasElement()) - { - // nodes()[ngn->id()]->canvasElement()->setGh(m_height); - } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; - GraphNode* newgn = new GraphNode(ngn); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - nodes().insert(agnameof(ngn), newgn); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; + foreach (GraphNode *node, nodes()) { + node->storeOriginalAttributes(); + } + foreach (GraphEdge *edge, edges()) { + edge->storeOriginalAttributes(); } + foreach (GraphSubgraph *subgraph, subgraphs()) { + subgraph->storeOriginalAttributes(); + } + GraphElement::storeOriginalAttributes(); +} - // copy node edges - edge_t* nge = agfstout(newGraph, ngn); - while (nge) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << nge->id; - const QString edgeName = QString::fromUtf8(agnameof(aghead(nge))) + QString::fromUtf8(agnameof(agtail(nge))); - if (edges().contains(edgeName)) - { -// () << "edge known" << nge->id; -// edges()[nge->name]->setZ(nge->z()); - edges()[edgeName]->updateWithEdge(nge); - if (edges()[edgeName]->canvasEdge()) - { - // edges()[nge->id()]->canvasEdge()->setGh(m_height); +void DotGraph::saveTo(const QString &fileName) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << fileName; + m_dotFileName = fileName; + GraphExporter exporter; + exporter.writeDot(this, fileName); +} + +void DotGraph::updateWithGraph(graph_t *newGraph) +{ + qCDebug(KGRAPHVIEWERLIB_LOG); + + // copy global graph render operations and attributes + DotRenderOpVec ops; + // decrease mem peak + setRenderOperations(ops); + + if (agget(newGraph, (char *)"_draw_")) { + parse_renderop(agget(newGraph, (char *)"_draw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); + } + if (agget(newGraph, (char *)"_ldraw_")) { + parse_renderop(agget(newGraph, (char *)"_ldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); + } + + setRenderOperations(ops); + + Agsym_t *attr = agnxtattr(newGraph, AGRAPH, nullptr); + while (attr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(newGraph) << ":" << attr->name << agxget(newGraph, attr); + m_attributes[attr->name] = agxget(newGraph, attr); + attr = agnxtattr(newGraph, AGRAPH, attr); + } + + // copy subgraphs + for (graph_t *sg = agfstsubg(newGraph); sg; sg = agnxtsubg(sg)) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph:" << agnameof(sg); + if (subgraphs().contains(agnameof(sg))) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; + // ??? + // nodes()[ngn->name]->setZ(ngn->z()); + subgraphs()[agnameof(sg)]->updateWithSubgraph(sg); + if (subgraphs()[agnameof(sg)]->canvasElement()) { + // nodes()[ngn->id()]->canvasElement()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; + GraphSubgraph *newsg = new GraphSubgraph(sg); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; + subgraphs().insert(agnameof(sg), newsg); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new edge" << edgeName; - { - GraphEdge* newEdge = new GraphEdge(); - newEdge->setId(edgeName); - newEdge->updateWithEdge(nge); - if (elementNamed(agnameof(agtail(nge))) == nullptr) - { - GraphNode* newgn = new GraphNode(); + } + + // copy nodes + node_t *ngn = agfstnode(newGraph); + qCDebug(KGRAPHVIEWERLIB_LOG) << "first node:" << (void *)ngn; + + while (ngn) + // foreach (GraphNode* ngn, newGraph.nodes()) + { + qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << agnameof(ngn); + if (nodes().contains(agnameof(ngn))) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; + // ??? + // nodes()[ngn->name]->setZ(ngn->z()); + nodes()[agnameof(ngn)]->updateWithNode(ngn); + if (nodes()[agnameof(ngn)]->canvasElement()) { + // nodes()[ngn->id()]->canvasElement()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; + GraphNode *newgn = new GraphNode(ngn); // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - nodes().insert(agnameof(agtail(nge)), newgn); - } - newEdge->setFromNode(elementNamed(agnameof(agtail(nge)))); - if (elementNamed(agnameof(aghead(nge))) == nullptr) - { - GraphNode* newgn = new GraphNode(); + nodes().insert(agnameof(ngn), newgn); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; + } + + // copy node edges + edge_t *nge = agfstout(newGraph, ngn); + while (nge) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << nge->id; + const QString edgeName = QString::fromUtf8(agnameof(aghead(nge))) + QString::fromUtf8(agnameof(agtail(nge))); + if (edges().contains(edgeName)) { + // () << "edge known" << nge->id; + // edges()[nge->name]->setZ(nge->z()); + edges()[edgeName]->updateWithEdge(nge); + if (edges()[edgeName]->canvasEdge()) { + // edges()[nge->id()]->canvasEdge()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new edge" << edgeName; + { + GraphEdge *newEdge = new GraphEdge(); + newEdge->setId(edgeName); + newEdge->updateWithEdge(nge); + if (elementNamed(agnameof(agtail(nge))) == nullptr) { + GraphNode *newgn = new GraphNode(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; + nodes().insert(agnameof(agtail(nge)), newgn); + } + newEdge->setFromNode(elementNamed(agnameof(agtail(nge)))); + if (elementNamed(agnameof(aghead(nge))) == nullptr) { + GraphNode *newgn = new GraphNode(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; + nodes().insert(agnameof(aghead(nge)), newgn); + } + newEdge->setToNode(elementNamed(agnameof(aghead(nge)))); + edges().insert(edgeName, newEdge); + } + } + nge = agnxtedge(newGraph, nge, ngn); + } + ngn = agnxtnode(newGraph, ngn); + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "Done"; + emit readyToDisplay(); + computeCells(); +} + +void DotGraph::updateWithGraph(const DotGraph &newGraph) +{ + GraphElement::updateWithElement(newGraph); + m_width = newGraph.width(); + m_height = newGraph.height(); + m_scale = newGraph.scale(); + m_directed = newGraph.directed(); + m_strict = newGraph.strict(); + computeCells(); + foreach (GraphSubgraph *nsg, newGraph.subgraphs()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph" << nsg->id(); + if (subgraphs().contains(nsg->id())) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph known" << nsg->id(); + subgraphs().value(nsg->id())->updateWithSubgraph(*nsg); + if (subgraphs().value(nsg->id())->canvasElement()) { + // subgraphs().value(nsg->id())->canvasElement()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new subgraph" << nsg->id(); + GraphSubgraph *newSubgraph = new GraphSubgraph(); + newSubgraph->updateWithSubgraph(*nsg); + newSubgraph->setZ(0); + subgraphs().insert(nsg->id(), newSubgraph); + } + } + foreach (GraphNode *ngn, newGraph.nodes()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << ngn->id(); + if (nodes().contains(ngn->id())) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; + nodes()[ngn->id()]->setZ(ngn->z()); + nodes()[ngn->id()]->updateWithNode(*ngn); + if (nodes()[ngn->id()]->canvasElement()) { + // nodes()[ngn->id()]->canvasElement()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; + GraphNode *newgn = new GraphNode(*ngn); // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - nodes().insert(agnameof(aghead(nge)), newgn); - } - newEdge->setToNode(elementNamed(agnameof(aghead(nge)))); - edges().insert(edgeName, newEdge); + nodes().insert(ngn->id(), newgn); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; } - } - nge = agnxtedge(newGraph, nge, ngn); - } - ngn = agnxtnode(newGraph, ngn); - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "Done"; - emit readyToDisplay(); - computeCells(); -} - -void DotGraph::updateWithGraph(const DotGraph& newGraph) -{ - GraphElement::updateWithElement(newGraph); - m_width=newGraph.width(); - m_height=newGraph.height(); - m_scale=newGraph.scale(); - m_directed=newGraph.directed(); - m_strict=newGraph.strict(); - computeCells(); - foreach (GraphSubgraph* nsg, newGraph.subgraphs()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph" << nsg->id(); - if (subgraphs().contains(nsg->id())) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph known" << nsg->id(); - subgraphs().value(nsg->id())->updateWithSubgraph(*nsg); - if (subgraphs().value(nsg->id())->canvasElement()) - { -// subgraphs().value(nsg->id())->canvasElement()->setGh(m_height); - } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new subgraph" << nsg->id(); - GraphSubgraph* newSubgraph = new GraphSubgraph(); - newSubgraph->updateWithSubgraph(*nsg); - newSubgraph->setZ(0); - subgraphs().insert(nsg->id(), newSubgraph); - } - } - foreach (GraphNode* ngn, newGraph.nodes()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << ngn->id(); - if (nodes().contains(ngn->id())) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "known"; - nodes()[ngn->id()]->setZ(ngn->z()); - nodes()[ngn->id()]->updateWithNode(*ngn); - if (nodes()[ngn->id()]->canvasElement()) - { -// nodes()[ngn->id()]->canvasElement()->setGh(m_height); - } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; - GraphNode* newgn = new GraphNode(*ngn); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - nodes().insert(ngn->id(), newgn); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; - } - } - foreach (GraphEdge* nge, newGraph.edges()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << nge->id(); - if (edges().contains(nge->id())) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "edge known" << nge->id(); - edges()[nge->id()]->setZ(nge->z()); - edges()[nge->id()]->updateWithEdge(*nge); - if (edges()[nge->id()]->canvasEdge()) - { -// edges()[nge->id()]->canvasEdge()->setGh(m_height); - } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new edge" << nge->id(); - { - GraphEdge* newEdge = new GraphEdge(); - newEdge->setId(nge->id()); - newEdge->updateWithEdge(*nge); - newEdge->setFromNode(elementNamed(nge->fromNode()->id())); - newEdge->setToNode(elementNamed(nge->toNode()->id())); - edges().insert(nge->id(), newEdge); - } - } - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "Done"; - computeCells(); -} - -void DotGraph::removeNodeNamed(const QString& nodeName) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName; - GraphNode* node = dynamic_cast(elementNamed(nodeName)); - if (node == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node " << nodeName; - return; - } - - GraphEdgeMap::iterator it, it_end; - it = m_edgesMap.begin(); it_end = m_edgesMap.end(); - while (it != it_end) - { - if ( it.value()->fromNode() == node - || it.value()->toNode() == node ) - { - GraphEdge* edge = it.value(); - if (edge->canvasEdge()) - { - edge->canvasEdge()->hide(); - delete edge->canvasEdge(); - delete edge; - } - it = edges().erase(it); - } - else - { - ++it; } - } + foreach (GraphEdge *nge, newGraph.edges()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "edge " << nge->id(); + if (edges().contains(nge->id())) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "edge known" << nge->id(); + edges()[nge->id()]->setZ(nge->z()); + edges()[nge->id()]->updateWithEdge(*nge); + if (edges()[nge->id()]->canvasEdge()) { + // edges()[nge->id()]->canvasEdge()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new edge" << nge->id(); + { + GraphEdge *newEdge = new GraphEdge(); + newEdge->setId(nge->id()); + newEdge->updateWithEdge(*nge); + newEdge->setFromNode(elementNamed(nge->fromNode()->id())); + newEdge->setToNode(elementNamed(nge->toNode()->id())); + edges().insert(nge->id(), newEdge); + } + } + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "Done"; + computeCells(); +} + +void DotGraph::removeNodeNamed(const QString &nodeName) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName; + GraphNode *node = dynamic_cast(elementNamed(nodeName)); + if (node == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node " << nodeName; + return; + } - if (node->canvasNode()) - { - node->canvasNode()->hide(); - delete node->canvasNode(); - node->setCanvasNode(nullptr); - } - nodes().remove(nodeName); - delete node; + GraphEdgeMap::iterator it, it_end; + it = m_edgesMap.begin(); + it_end = m_edgesMap.end(); + while (it != it_end) { + if (it.value()->fromNode() == node || it.value()->toNode() == node) { + GraphEdge *edge = it.value(); + if (edge->canvasEdge()) { + edge->canvasEdge()->hide(); + delete edge->canvasEdge(); + delete edge; + } + it = edges().erase(it); + } else { + ++it; + } + } + if (node->canvasNode()) { + node->canvasNode()->hide(); + delete node->canvasNode(); + node->setCanvasNode(nullptr); + } + nodes().remove(nodeName); + delete node; } -void DotGraph::removeNodeFromSubgraph( - const QString& nodeName, - const QString& subgraphName) +void DotGraph::removeNodeFromSubgraph(const QString &nodeName, const QString &subgraphName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName << subgraphName; - GraphNode* node = dynamic_cast(elementNamed(nodeName)); - if (node == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node " << nodeName; - return; - } + qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName << subgraphName; + GraphNode *node = dynamic_cast(elementNamed(nodeName)); + if (node == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node " << nodeName; + return; + } - GraphSubgraph* subgraph = subgraphs()[subgraphName]; - if (subgraph == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No such subgraph " << subgraphName; - return; - } - - subgraph->removeElement(node); - if (subgraph->content().isEmpty()) - { - removeSubgraphNamed(subgraphName); - } + GraphSubgraph *subgraph = subgraphs()[subgraphName]; + if (subgraph == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No such subgraph " << subgraphName; + return; + } + + subgraph->removeElement(node); + if (subgraph->content().isEmpty()) { + removeSubgraphNamed(subgraphName); + } } -void DotGraph::removeSubgraphNamed(const QString& subgraphName) +void DotGraph::removeSubgraphNamed(const QString &subgraphName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << subgraphName << " from " << subgraphs().keys(); - GraphSubgraph* subgraph = subgraphs()[subgraphName]; + qCDebug(KGRAPHVIEWERLIB_LOG) << subgraphName << " from " << subgraphs().keys(); + GraphSubgraph *subgraph = subgraphs()[subgraphName]; - if (subgraph == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Subgraph" << subgraphName << "not found"; - return; - } - GraphEdgeMap::iterator it, it_end; - it = m_edgesMap.begin(); it_end = m_edgesMap.end(); - while (it != it_end) - { - if ( it.value()->fromNode() == subgraph - || it.value()->toNode() == subgraph ) - { - GraphEdge* edge = it.value(); - if (edge->canvasEdge()) - { - edge->canvasEdge()->hide(); - delete edge->canvasEdge(); - delete edge; - } - it = edges().erase(it); - } - else - { - ++it; - } - } - - if (subgraph->canvasSubgraph()) - { - subgraph->canvasSubgraph()->hide(); - delete subgraph->canvasSubgraph(); - subgraph->setCanvasSubgraph(nullptr); - } - foreach(GraphElement* element, subgraph->content()) - { - if (dynamic_cast(element)) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding" << element->id() << "to main graph"; - nodes()[element->id()] = dynamic_cast(element); + if (subgraph == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Subgraph" << subgraphName << "not found"; + return; } - else if (dynamic_cast(element)) - { - subgraphs()[element->id()] = dynamic_cast(element); + GraphEdgeMap::iterator it, it_end; + it = m_edgesMap.begin(); + it_end = m_edgesMap.end(); + while (it != it_end) { + if (it.value()->fromNode() == subgraph || it.value()->toNode() == subgraph) { + GraphEdge *edge = it.value(); + if (edge->canvasEdge()) { + edge->canvasEdge()->hide(); + delete edge->canvasEdge(); + delete edge; + } + it = edges().erase(it); + } else { + ++it; + } } - else - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Don't know how to handle" << element->id(); + + if (subgraph->canvasSubgraph()) { + subgraph->canvasSubgraph()->hide(); + delete subgraph->canvasSubgraph(); + subgraph->setCanvasSubgraph(nullptr); + } + foreach (GraphElement *element, subgraph->content()) { + if (dynamic_cast(element)) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding" << element->id() << "to main graph"; + nodes()[element->id()] = dynamic_cast(element); + } else if (dynamic_cast(element)) { + subgraphs()[element->id()] = dynamic_cast(element); + } else { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Don't know how to handle" << element->id(); + } + } + subgraph->content().clear(); + subgraphs().remove(subgraphName); + delete subgraph; +} + +void DotGraph::removeEdge(const QString &id) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << id; + GraphEdgeMap::iterator it = edges().begin(); + for (; it != edges().end(); it++) { + GraphEdge *edge = it.value(); + if (edge->id() == id) { + if (edge->canvasEdge()) { + edge->canvasEdge()->hide(); + delete edge->canvasEdge(); + delete edge; + } + edges().remove(id); + break; + } } - } - subgraph->content().clear(); - subgraphs().remove(subgraphName); - delete subgraph; } -void DotGraph::removeEdge(const QString& id) +void DotGraph::removeElement(const QString &id) { - qCDebug(KGRAPHVIEWERLIB_LOG) << id; - GraphEdgeMap::iterator it = edges().begin(); - for (; it != edges().end(); it++) - { - GraphEdge* edge = it.value(); - if (edge->id() ==id) - { - if (edge->canvasEdge()) - { - edge->canvasEdge()->hide(); - delete edge->canvasEdge(); - delete edge; - } - edges().remove(id); - break; - } - } -} - -void DotGraph::removeElement(const QString& id) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << id; - GraphNodeMap::const_iterator itN = nodes().constBegin(); - for (; itN != nodes().constEnd(); itN++) - { - const GraphNode* node = itN.value(); - if (node->id() == id) - { - removeNodeNamed(id); - return; - } - } - GraphEdgeMap::const_iterator itE = edges().constBegin(); - for (; itE != edges().constEnd(); itE++) - { - const GraphEdge* edge = itE.value(); - if (edge->id() == id) - { - removeEdge(id); - return; - } - } - GraphSubgraphMap::const_iterator itS = subgraphs().constBegin(); - for (; itS != subgraphs().constEnd(); itS++) - { - const GraphSubgraph* subgraph = itS.value(); - if (subgraph->id() == id) - { - removeSubgraphNamed(id); - return; + qCDebug(KGRAPHVIEWERLIB_LOG) << id; + GraphNodeMap::const_iterator itN = nodes().constBegin(); + for (; itN != nodes().constEnd(); itN++) { + const GraphNode *node = itN.value(); + if (node->id() == id) { + removeNodeNamed(id); + return; + } + } + GraphEdgeMap::const_iterator itE = edges().constBegin(); + for (; itE != edges().constEnd(); itE++) { + const GraphEdge *edge = itE.value(); + if (edge->id() == id) { + removeEdge(id); + return; + } + } + GraphSubgraphMap::const_iterator itS = subgraphs().constBegin(); + for (; itS != subgraphs().constEnd(); itS++) { + const GraphSubgraph *subgraph = itS.value(); + if (subgraph->id() == id) { + removeSubgraphNamed(id); + return; + } } - } } -void DotGraph::setAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue) +void DotGraph::setAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue) { - if (nodes().contains(elementId)) - { - nodes()[elementId]->attributes()[attributeName] = attributeValue; - } - else if (edges().contains(elementId)) - { - edges()[elementId]->attributes()[attributeName] = attributeValue; - } - else if (subgraphs().contains(elementId)) - { - subgraphs()[elementId]->attributes()[attributeName] = attributeValue; - } + if (nodes().contains(elementId)) { + nodes()[elementId]->attributes()[attributeName] = attributeValue; + } else if (edges().contains(elementId)) { + edges()[elementId]->attributes()[attributeName] = attributeValue; + } else if (subgraphs().contains(elementId)) { + subgraphs()[elementId]->attributes()[attributeName] = attributeValue; + } } -GraphElement* DotGraph::elementNamed(const QString& id) +GraphElement *DotGraph::elementNamed(const QString &id) { - GraphElement* ret = nullptr; - if ((ret = m_nodesMap.value(id, nullptr))) { - return ret; - } - if ((ret = m_edgesMap.value(id, nullptr))) { - return ret; - } - foreach(GraphSubgraph* subGraph, m_subgraphsMap) { - if ((ret = subGraph->elementNamed(id))) { - return ret; + GraphElement *ret = nullptr; + if ((ret = m_nodesMap.value(id, nullptr))) { + return ret; + } + if ((ret = m_edgesMap.value(id, nullptr))) { + return ret; + } + foreach (GraphSubgraph *subGraph, m_subgraphsMap) { + if ((ret = subGraph->elementNamed(id))) { + return ret; + } } - } - return nullptr; + return nullptr; } -void DotGraph::setGraphAttributes(QMap attribs) +void DotGraph::setGraphAttributes(QMap attribs) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; - attributes() = attribs; + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; + attributes() = attribs; } - -void DotGraph::addNewNode(QMap attribs) +void DotGraph::addNewNode(QMap attribs) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; - GraphNode* newNode = new GraphNode(); - newNode->attributes() = attribs; - nodes().insert(newNode->id(), newNode); - qCDebug(KGRAPHVIEWERLIB_LOG) << "node added as" << newNode->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; + GraphNode *newNode = new GraphNode(); + newNode->attributes() = attribs; + nodes().insert(newNode->id(), newNode); + qCDebug(KGRAPHVIEWERLIB_LOG) << "node added as" << newNode->id(); } -void DotGraph::addNewSubgraph(QMap attribs) +void DotGraph::addNewSubgraph(QMap attribs) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; - GraphSubgraph* newSG = new GraphSubgraph(); - newSG->attributes() = attribs; - subgraphs()[newSG->id()] = newSG; - qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph added as" << newSG->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; + GraphSubgraph *newSG = new GraphSubgraph(); + newSG->attributes() = attribs; + subgraphs()[newSG->id()] = newSG; + qCDebug(KGRAPHVIEWERLIB_LOG) << "subgraph added as" << newSG->id(); } -void DotGraph::addNewNodeToSubgraph(QMap attribs, QString subgraph) +void DotGraph::addNewNodeToSubgraph(QMap attribs, QString subgraph) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs << "to" << subgraph; - GraphNode* newNode = new GraphNode(); - newNode->attributes() = attribs; - subgraphs()[subgraph]->content().push_back(newNode); + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs << "to" << subgraph; + GraphNode *newNode = new GraphNode(); + newNode->attributes() = attribs; + subgraphs()[subgraph]->content().push_back(newNode); - qCDebug(KGRAPHVIEWERLIB_LOG) << "node added as" << newNode->id() << "in" << subgraph; + qCDebug(KGRAPHVIEWERLIB_LOG) << "node added as" << newNode->id() << "in" << subgraph; } -void DotGraph::addExistingNodeToSubgraph(QMap attribs,QString subgraph) +void DotGraph::addExistingNodeToSubgraph(QMap attribs, QString subgraph) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs << "to" << subgraph; - GraphNode* node = dynamic_cast(elementNamed(attribs["id"])); - if (node == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node" << attribs["id"]; - return; - } - if (nodes().contains(attribs["id"])) - { - nodes().remove(attribs["id"]); - node->attributes() = attribs; - subgraphs()[subgraph]->content().push_back(node); - qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << node->id() << " added in " << subgraph; - } - else - { - foreach(GraphSubgraph* gs, subgraphs()) - { - GraphElement* elt = nullptr; - foreach(GraphElement* element, gs->content()) - { - if (element == node) - { - elt = element; - break; + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs << "to" << subgraph; + GraphNode *node = dynamic_cast(elementNamed(attribs["id"])); + if (node == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node" << attribs["id"]; + return; + } + if (nodes().contains(attribs["id"])) { + nodes().remove(attribs["id"]); + node->attributes() = attribs; + subgraphs()[subgraph]->content().push_back(node); + qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << node->id() << " added in " << subgraph; + } else { + foreach (GraphSubgraph *gs, subgraphs()) { + GraphElement *elt = nullptr; + foreach (GraphElement *element, gs->content()) { + if (element == node) { + elt = element; + break; + } + } + if (elt) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "removing node " << elt->id() << " from " << gs->id(); + gs->removeElement(elt); + subgraphs()[subgraph]->content().push_back(elt); + qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << elt->id() << " added in " << subgraph; + break; + } } - } - if (elt) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "removing node " << elt->id() << " from " << gs->id(); - gs->removeElement(elt); - subgraphs()[subgraph]->content().push_back(elt); - qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << elt->id() << " added in " << subgraph; - break; - } } - } } -void DotGraph::moveExistingNodeToMainGraph(QMap attribs) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; - GraphNode* node = dynamic_cast(elementNamed(attribs["id"])); - if (node == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node" << attribs["id"]; - return; - } - else if (nodes().contains(attribs["id"])) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Node" << attribs["id"] << "already in main graph"; - return; - } - else - { - foreach(GraphSubgraph* gs, subgraphs()) - { - bool found = false; - foreach(GraphElement* element, gs->content()) - { - if (element == node) - { - found = true; - break; +void DotGraph::moveExistingNodeToMainGraph(QMap attribs) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; + GraphNode *node = dynamic_cast(elementNamed(attribs["id"])); + if (node == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No such node" << attribs["id"]; + return; + } else if (nodes().contains(attribs["id"])) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Node" << attribs["id"] << "already in main graph"; + return; + } else { + foreach (GraphSubgraph *gs, subgraphs()) { + bool found = false; + foreach (GraphElement *element, gs->content()) { + if (element == node) { + found = true; + break; + } + } + if (found) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "removing node " << node->id() << " from " << gs->id(); + gs->removeElement(node); + nodes()[node->id()] = node; + qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << node->id() << " moved to main graph"; + break; + } } - } - if (found) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "removing node " << node->id() << " from " << gs->id(); - gs->removeElement(node); - nodes()[node->id()] = node; - qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << node->id() << " moved to main graph"; - break; - } - } - } -} - -void DotGraph::addNewEdge(QString src, QString tgt, QMap attribs) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << src << tgt << attribs; - GraphEdge* newEdge = new GraphEdge(); - newEdge->attributes() = attribs; - GraphElement* srcElement = elementNamed(src); - if (srcElement == nullptr) - { - srcElement = elementNamed(QString("cluster_")+src); - } - GraphElement* tgtElement = elementNamed(tgt); - if (tgtElement == nullptr) - { - tgtElement = elementNamed(QString("cluster_")+tgt); - } - - if (srcElement == nullptr || tgtElement == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << src << "or" << tgt << "missing"; - return; - } - if (attribs.contains("id")) - { - newEdge->setId(attribs["id"]); - } - else - { - newEdge->setId(src+tgt+QUuid::createUuid().toString().remove('{').remove('}').remove('-')); - } - newEdge->setFromNode(srcElement); - newEdge->setToNode(tgtElement); - edges().insert(newEdge->id(), newEdge); + } } -void DotGraph::removeAttribute(const QString& nodeName, const QString& attribName) +void DotGraph::addNewEdge(QString src, QString tgt, QMap attribs) { - GraphElement* element = elementNamed(nodeName); - if (element) - { - element->removeAttribute(attribName); - } + qCDebug(KGRAPHVIEWERLIB_LOG) << src << tgt << attribs; + GraphEdge *newEdge = new GraphEdge(); + newEdge->attributes() = attribs; + GraphElement *srcElement = elementNamed(src); + if (srcElement == nullptr) { + srcElement = elementNamed(QString("cluster_") + src); + } + GraphElement *tgtElement = elementNamed(tgt); + if (tgtElement == nullptr) { + tgtElement = elementNamed(QString("cluster_") + tgt); + } + + if (srcElement == nullptr || tgtElement == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << src << "or" << tgt << "missing"; + return; + } + if (attribs.contains("id")) { + newEdge->setId(attribs["id"]); + } else { + newEdge->setId(src + tgt + QUuid::createUuid().toString().remove('{').remove('}').remove('-')); + } + newEdge->setFromNode(srcElement); + newEdge->setToNode(tgtElement); + edges().insert(newEdge->id(), newEdge); } -void DotGraph::renameNode(const QString& oldNodeName, const QString& newNodeName) +void DotGraph::removeAttribute(const QString &nodeName, const QString &attribName) { - if (oldNodeName != newNodeName) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Renaming " << oldNodeName << " into " << newNodeName; - GraphNode* node = nodes()[oldNodeName]; - nodes().remove(oldNodeName); - node->setId(newNodeName); - nodes()[newNodeName] = node; - } + GraphElement *element = elementNamed(nodeName); + if (element) { + element->removeAttribute(attribName); + } } -QString DotGraph::backColor() const +void DotGraph::renameNode(const QString &oldNodeName, const QString &newNodeName) { - if (m_attributes.find("bgcolor") != m_attributes.end()) - { - return m_attributes["bgcolor"]; - } - else - { - return QString(); - } + if (oldNodeName != newNodeName) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Renaming " << oldNodeName << " into " << newNodeName; + GraphNode *node = nodes()[oldNodeName]; + nodes().remove(oldNodeName); + node->setId(newNodeName); + nodes()[newNodeName] = node; + } } +QString DotGraph::backColor() const +{ + if (m_attributes.find("bgcolor") != m_attributes.end()) { + return m_attributes["bgcolor"]; + } else { + return QString(); + } +} } diff --git a/src/part/dotgraphview.h b/src/part/dotgraphview.h --- a/src/part/dotgraphview.h +++ b/src/part/dotgraphview.h @@ -24,16 +24,15 @@ License as published by the Free Software Foundation, version 2. */ - /* * Callgraph View */ #ifndef DOTGRAPHVIEW_H #define DOTGRAPHVIEW_H -#include #include +#include #include #include @@ -56,7 +55,6 @@ namespace KGraphViewer { - class GraphElement; class CanvasElement; class CanvasEdge; @@ -70,182 +68,175 @@ * and another zoomed out CanvasView in a border acting as * a panner to select to visible part (only if needed) */ -class KGRAPHVIEWER_EXPORT DotGraphView: public QGraphicsView +class KGRAPHVIEWER_EXPORT DotGraphView : public QGraphicsView { - Q_OBJECT + Q_OBJECT public: - enum EditingMode { None, AddNewElement, AddNewEdge, DrawNewEdge, SelectingElements }; - enum ScrollDirection { Here, Left, Right, Top, Bottom }; - - explicit KGRAPHVIEWER_EXPORT DotGraphView(KActionCollection* actions, QWidget* parent = nullptr); - ~DotGraphView() override; - - bool KGRAPHVIEWER_EXPORT loadDot(const QString& dotFileName); - bool KGRAPHVIEWER_EXPORT loadLibrary(const QString& dotFileName); - bool KGRAPHVIEWER_EXPORT loadLibrarySync(const QString& dotFileName); - bool loadLibrary(graph_t* graph, const QString& layoutCommand = "dot"); - - void readViewConfig(); - void saveViewConfig(); - - //TODO: rename zoomPos -> bev / panner, but _please_ make it consistent... - KGraphViewerInterface::PannerPosition zoomPos() const; - static KGraphViewerInterface::PannerPosition zoomPos(const QString&); - static QString zoomPosString(KGraphViewerInterface::PannerPosition); - void setPannerEnabled(bool enabled); - - static KConfigGroup* configGroup(KConfig*, const QString& prefix, const QString& postfix); - static void writeConfigEntry(KConfigGroup*, const char* pKey, const QString& value, - const char* def); - static void writeConfigEntry(KConfigGroup*, const char* pKey, - int value, int def); - static void writeConfigEntry(KConfigGroup*, const char* pKey, - bool value, bool def); - static void writeConfigEntry(KConfigGroup*, const char* pKey, - double value, double def); - - /// multiplies current zoom factor with @p factor - void applyZoom(double factor); - /// sets zoom factor to @p factor - void setZoomFactor(double factor); - - void setLayoutCommand(const QString& command); - - const QString& dotFileName(); - - void hideToolsWindows(); - double zoom() const; - KSelectAction* bevPopup(); - - DotGraph* graph(); - const DotGraph* graph() const; - - const GraphElement* defaultNewElement() const; - QPixmap defaultNewElementPixmap() const; - - void setDefaultNewElement(GraphElement* elem); - void setDefaultNewElementPixmap(const QPixmap& pm); - - void prepareAddNewElement(QMap attribs); - void prepareAddNewEdge(QMap attribs); - void prepareSelectElements(); - - void createNewEdgeDraftFrom(CanvasElement* node); - void finishNewEdgeTo(CanvasElement* node); - - EditingMode editingMode() const; - - void KGRAPHVIEWER_EXPORT setReadOnly(); - void KGRAPHVIEWER_EXPORT setReadWrite(); - bool isReadWrite() const; - bool isReadOnly() const; - - void removeSelectedNodes(); - void removeSelectedEdges(); - void removeSelectedSubgraphs(); - void removeSelectedElements(); - - bool highlighting(); - void setHighlighting(bool highlightingValue); - - // public so that the panner view can bubble through - void contextMenuEvent(QContextMenuEvent*) override; - - void setBackgroundColor(const QColor& color); - + enum EditingMode { None, AddNewElement, AddNewEdge, DrawNewEdge, SelectingElements }; + enum ScrollDirection { Here, Left, Right, Top, Bottom }; + + explicit KGRAPHVIEWER_EXPORT DotGraphView(KActionCollection *actions, QWidget *parent = nullptr); + ~DotGraphView() override; + + bool KGRAPHVIEWER_EXPORT loadDot(const QString &dotFileName); + bool KGRAPHVIEWER_EXPORT loadLibrary(const QString &dotFileName); + bool KGRAPHVIEWER_EXPORT loadLibrarySync(const QString &dotFileName); + bool loadLibrary(graph_t *graph, const QString &layoutCommand = "dot"); + + void readViewConfig(); + void saveViewConfig(); + + // TODO: rename zoomPos -> bev / panner, but _please_ make it consistent... + KGraphViewerInterface::PannerPosition zoomPos() const; + static KGraphViewerInterface::PannerPosition zoomPos(const QString &); + static QString zoomPosString(KGraphViewerInterface::PannerPosition); + void setPannerEnabled(bool enabled); + + static KConfigGroup *configGroup(KConfig *, const QString &prefix, const QString &postfix); + static void writeConfigEntry(KConfigGroup *, const char *pKey, const QString &value, const char *def); + static void writeConfigEntry(KConfigGroup *, const char *pKey, int value, int def); + static void writeConfigEntry(KConfigGroup *, const char *pKey, bool value, bool def); + static void writeConfigEntry(KConfigGroup *, const char *pKey, double value, double def); + + /// multiplies current zoom factor with @p factor + void applyZoom(double factor); + /// sets zoom factor to @p factor + void setZoomFactor(double factor); + + void setLayoutCommand(const QString &command); + + const QString &dotFileName(); + + void hideToolsWindows(); + double zoom() const; + KSelectAction *bevPopup(); + + DotGraph *graph(); + const DotGraph *graph() const; + + const GraphElement *defaultNewElement() const; + QPixmap defaultNewElementPixmap() const; + + void setDefaultNewElement(GraphElement *elem); + void setDefaultNewElementPixmap(const QPixmap &pm); + + void prepareAddNewElement(QMap attribs); + void prepareAddNewEdge(QMap attribs); + void prepareSelectElements(); + + void createNewEdgeDraftFrom(CanvasElement *node); + void finishNewEdgeTo(CanvasElement *node); + + EditingMode editingMode() const; + + void KGRAPHVIEWER_EXPORT setReadOnly(); + void KGRAPHVIEWER_EXPORT setReadWrite(); + bool isReadWrite() const; + bool isReadOnly() const; + + void removeSelectedNodes(); + void removeSelectedEdges(); + void removeSelectedSubgraphs(); + void removeSelectedElements(); + + bool highlighting(); + void setHighlighting(bool highlightingValue); + + // public so that the panner view can bubble through + void contextMenuEvent(QContextMenuEvent *) override; + + void setBackgroundColor(const QColor &color); + Q_SIGNALS: - void zoomed(double factor); - void sigViewBevEnabledToggled(bool value); - void sigViewBevActivated(int newPos); - void graphLoaded(); - void newNodeAdded(const QString&); - void newEdgeAdded(const QString&, const QString&); - /** signals that the user has activated a remove edge command */ - void removeEdge(const QString&); - /** signals that the user has activated a remove edge command */ - void removeNodeNamed(const QString&); - /** signals that the user has activated a remove element command */ - void removeElement(const QString&); - /** signals the content of the new selection */ - void selectionIs(const QList, const QPoint&); - /** let the application tweak the created edge if necessary */ - void newEdgeFinished( - const QString&, const QString&, - const QMap&); - void contextMenuEvent(const QString&, const QPoint&); - void hoverEnter(const QString&); - void hoverLeave(const QString&); - + void zoomed(double factor); + void sigViewBevEnabledToggled(bool value); + void sigViewBevActivated(int newPos); + void graphLoaded(); + void newNodeAdded(const QString &); + void newEdgeAdded(const QString &, const QString &); + /** signals that the user has activated a remove edge command */ + void removeEdge(const QString &); + /** signals that the user has activated a remove edge command */ + void removeNodeNamed(const QString &); + /** signals that the user has activated a remove element command */ + void removeElement(const QString &); + /** signals the content of the new selection */ + void selectionIs(const QList, const QPoint &); + /** let the application tweak the created edge if necessary */ + void newEdgeFinished(const QString &, const QString &, const QMap &); + void contextMenuEvent(const QString &, const QPoint &); + void hoverEnter(const QString &); + void hoverLeave(const QString &); + public Q_SLOTS: - void zoomIn(); - void zoomOut(); - void zoomRectMovedTo(QPointF newZoomPos); - void zoomRectMoveFinished(); - bool initEmpty(); - bool slotLoadLibrary(graph_t* graph); - bool reload(); - void dirty(const QString& dotFileName); - void pageSetup(); - void print(); - void printPreview(); - void viewBevActivated(int newPos); - void slotExportImage(); - void slotSelectLayoutAlgo(const QString& text); - void slotLayoutSpecify(); - void slotLayoutReset(); - void slotSelectLayoutDot(); - void slotSelectLayoutNeato(); - void slotSelectLayoutTwopi(); - void slotSelectLayoutFdp(); - void slotSelectLayoutCirco(); - void slotBevToggled(); - void slotBevTopLeft(); - void slotBevTopRight(); - void slotBevBottomLeft(); - void slotBevBottomRight(); - void slotBevAutomatic(); - void slotUpdate(); - bool displayGraph(); - void slotEdgeSelected(CanvasEdge*, Qt::KeyboardModifiers); - void slotElementSelected(CanvasElement*, Qt::KeyboardModifiers); - void slotSelectionChanged(); - void slotContextMenuEvent(const QString&, const QPoint&); - void slotElementHoverEnter(CanvasElement*); - void slotElementHoverLeave(CanvasElement*); - void slotElementHoverEnter(CanvasEdge*); - void slotElementHoverLeave(CanvasEdge*); - void slotSelectNode(const QString& nodeName); - void centerOnNode(const QString& nodeId); + void zoomIn(); + void zoomOut(); + void zoomRectMovedTo(QPointF newZoomPos); + void zoomRectMoveFinished(); + bool initEmpty(); + bool slotLoadLibrary(graph_t *graph); + bool reload(); + void dirty(const QString &dotFileName); + void pageSetup(); + void print(); + void printPreview(); + void viewBevActivated(int newPos); + void slotExportImage(); + void slotSelectLayoutAlgo(const QString &text); + void slotLayoutSpecify(); + void slotLayoutReset(); + void slotSelectLayoutDot(); + void slotSelectLayoutNeato(); + void slotSelectLayoutTwopi(); + void slotSelectLayoutFdp(); + void slotSelectLayoutCirco(); + void slotBevToggled(); + void slotBevTopLeft(); + void slotBevTopRight(); + void slotBevBottomLeft(); + void slotBevBottomRight(); + void slotBevAutomatic(); + void slotUpdate(); + bool displayGraph(); + void slotEdgeSelected(CanvasEdge *, Qt::KeyboardModifiers); + void slotElementSelected(CanvasElement *, Qt::KeyboardModifiers); + void slotSelectionChanged(); + void slotContextMenuEvent(const QString &, const QPoint &); + void slotElementHoverEnter(CanvasElement *); + void slotElementHoverLeave(CanvasElement *); + void slotElementHoverEnter(CanvasEdge *); + void slotElementHoverLeave(CanvasEdge *); + void slotSelectNode(const QString &nodeName); + void centerOnNode(const QString &nodeId); protected: - void scrollViewPercent(bool horizontal, int percent); - - void scrollContentsBy(int dx, int dy) override; - void resizeEvent(QResizeEvent*) override; - void mousePressEvent(QMouseEvent*) override; - void mouseMoveEvent(QMouseEvent*) override; - void mouseReleaseEvent(QMouseEvent*) override; - void mouseDoubleClickEvent(QMouseEvent*) override; - void keyPressEvent(QKeyEvent*) override; - void wheelEvent(QWheelEvent* e) override; - void focusInEvent(QFocusEvent*) override; - void focusOutEvent(QFocusEvent*) override; - - void timerEvent(QTimerEvent* event) override; - void leaveEvent(QEvent* event) override; - void enterEvent(QEvent* event) override; - + void scrollViewPercent(bool horizontal, int percent); + + void scrollContentsBy(int dx, int dy) override; + void resizeEvent(QResizeEvent *) override; + void mousePressEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + void mouseDoubleClickEvent(QMouseEvent *) override; + void keyPressEvent(QKeyEvent *) override; + void wheelEvent(QWheelEvent *e) override; + void focusInEvent(QFocusEvent *) override; + void focusOutEvent(QFocusEvent *) override; + + void timerEvent(QTimerEvent *event) override; + void leaveEvent(QEvent *event) override; + void enterEvent(QEvent *event) override; + private Q_SLOTS: - void slotAGraphReadFinished(); - void slotAGraphLayoutFinished(); - + void slotAGraphReadFinished(); + void slotAGraphLayoutFinished(); + protected: - DotGraphViewPrivate * const d_ptr; + DotGraphViewPrivate *const d_ptr; private: - Q_DECLARE_PRIVATE(DotGraphView); - + Q_DECLARE_PRIVATE(DotGraphView); }; } diff --git a/src/part/dotgraphview.cpp b/src/part/dotgraphview.cpp --- a/src/part/dotgraphview.cpp +++ b/src/part/dotgraphview.cpp @@ -24,1953 +24,1883 @@ License as published by the Free Software Foundation, version 2. */ - /* * Callgraph View */ #include "dotgraphview.h" -#include "dotgraph.h" -#include "graphelement.h" -#include "pannerview.h" -#include "canvassubgraph.h" +#include "FontsCache.h" #include "canvasedge.h" -#include "dot2qtconsts.h" -#include "graphnode.h" #include "canvasnode.h" +#include "canvassubgraph.h" +#include "dot2qtconsts.h" +#include "dotgraph.h" #include "graphedge.h" -#include "FontsCache.h" +#include "graphelement.h" +#include "graphexporter.h" +#include "graphnode.h" #include "kgraphviewer_partsettings.h" #include "kgraphviewerlib_debug.h" -#include "simpleprintingcommand.h" -#include "graphexporter.h" -#include "loadagraphthread.h" #include "layoutagraphthread.h" +#include "loadagraphthread.h" +#include "pannerview.h" +#include "simpleprintingcommand.h" -#include -#include #include +#include +#include +#include +#include +#include +#include #include -#include -#include -#include +#include +#include #include -#include +#include +#include #include +#include +#include +#include +#include #include -#include #include -#include -#include -#include -#include -#include #include -#include -#include +#include +#include #include -#include -#include -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include // DotGraphView defaults -#define DEFAULT_ZOOMPOS KGraphViewerInterface::Auto +#define DEFAULT_ZOOMPOS KGraphViewerInterface::Auto #define KGV_MAX_PANNER_NODES 100 namespace KGraphViewer { - class DotGraphViewPrivate { - public: - DotGraphViewPrivate(KActionCollection* actions, DotGraphView* parent) : - m_labelViews(), - m_popup(nullptr), - m_zoom(1), - m_isMoving(false), - m_exporter(), - m_zoomPosition(DEFAULT_ZOOMPOS), - m_lastAutoPosition(KGraphViewerInterface::TopLeft), - m_graph(nullptr), - m_printCommand(nullptr), - m_actions(actions), - m_detailLevel(DEFAULT_DETAILLEVEL), - m_defaultNewElement(nullptr), - m_defaultNewElementPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newnode.png")), - m_editingMode(DotGraphView::None), - m_newEdgeSource(nullptr), - m_newEdgeDraft(nullptr), - m_readWrite(false), - m_leavedTimer(std::numeric_limits::max()), - m_highlighting(false), - m_loadThread(), - m_layoutThread(), - m_backgroundColor(QColor("white")), - q_ptr( parent ) - { - - } - ~DotGraphViewPrivate() - { - delete m_birdEyeView; - m_birdEyeView = nullptr; - delete m_popup; - if (m_canvas) + DotGraphViewPrivate(KActionCollection *actions, DotGraphView *parent) + : m_labelViews() + , m_popup(nullptr) + , m_zoom(1) + , m_isMoving(false) + , m_exporter() + , m_zoomPosition(DEFAULT_ZOOMPOS) + , m_lastAutoPosition(KGraphViewerInterface::TopLeft) + , m_graph(nullptr) + , m_printCommand(nullptr) + , m_actions(actions) + , m_detailLevel(DEFAULT_DETAILLEVEL) + , m_defaultNewElement(nullptr) + , m_defaultNewElementPixmap(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newnode.png")) + , m_editingMode(DotGraphView::None) + , m_newEdgeSource(nullptr) + , m_newEdgeDraft(nullptr) + , m_readWrite(false) + , m_leavedTimer(std::numeric_limits::max()) + , m_highlighting(false) + , m_loadThread() + , m_layoutThread() + , m_backgroundColor(QColor("white")) + , q_ptr(parent) { - Q_Q(DotGraphView); - q->setScene(nullptr); - delete m_canvas; } - delete m_graph; - } - - - void updateSizes(QSizeF s = QSizeF(0,0)); - void updateBirdEyeView(); - void setupPopup(); - void exportToImage(); - KActionCollection* actionCollection() {return m_actions;} - double detailAdjustedScale(); - int displaySubgraph(GraphSubgraph* gsubgraph, int zValue, CanvasElement* parent = nullptr); + ~DotGraphViewPrivate() + { + delete m_birdEyeView; + m_birdEyeView = nullptr; + delete m_popup; + if (m_canvas) { + Q_Q(DotGraphView); + q->setScene(nullptr); + delete m_canvas; + } + delete m_graph; + } + void updateSizes(QSizeF s = QSizeF(0, 0)); + void updateBirdEyeView(); + void setupPopup(); + void exportToImage(); + KActionCollection *actionCollection() + { + return m_actions; + } + double detailAdjustedScale(); + int displaySubgraph(GraphSubgraph *gsubgraph, int zValue, CanvasElement *parent = nullptr); - QSet m_labelViews; - QGraphicsScene* m_canvas; - QMenu* m_popup; - KSelectAction* m_bevPopup; - KSelectAction* m_layoutAlgoSelectAction; - int m_xMargin, m_yMargin; - PannerView *m_birdEyeView; - double m_cvZoom; - double m_zoom; - bool m_isMoving; - QPoint m_lastPos; + QSet m_labelViews; + QGraphicsScene *m_canvas; + QMenu *m_popup; + KSelectAction *m_bevPopup; + KSelectAction *m_layoutAlgoSelectAction; + int m_xMargin, m_yMargin; + PannerView *m_birdEyeView; + double m_cvZoom; + double m_zoom; + bool m_isMoving; + QPoint m_lastPos; - GraphExporter m_exporter; + GraphExporter m_exporter; - // widget options - KGraphViewerInterface::PannerPosition m_zoomPosition, m_lastAutoPosition; + // widget options + KGraphViewerInterface::PannerPosition m_zoomPosition, m_lastAutoPosition; - DotGraph* m_graph; + DotGraph *m_graph; - KGVSimplePrintingCommand* m_printCommand; + KGVSimplePrintingCommand *m_printCommand; - KToggleAction* m_bevEnabledAction; - KActionCollection* m_actions; + KToggleAction *m_bevEnabledAction; + KActionCollection *m_actions; - int m_detailLevel; + int m_detailLevel; - GraphElement* m_defaultNewElement; + GraphElement *m_defaultNewElement; - /** image used for a new node just added in an edited graph because this new node has - * still no attribute and thus no render operation */ - QPixmap m_defaultNewElementPixmap; - DotGraphView::EditingMode m_editingMode; + /** image used for a new node just added in an edited graph because this new node has + * still no attribute and thus no render operation */ + QPixmap m_defaultNewElementPixmap; + DotGraphView::EditingMode m_editingMode; - CanvasElement* m_newEdgeSource; - QGraphicsLineItem* m_newEdgeDraft; + CanvasElement *m_newEdgeSource; + QGraphicsLineItem *m_newEdgeDraft; - bool m_readWrite; + bool m_readWrite; - QMap m_newElementAttributes; + QMap m_newElementAttributes; - /// identifier of the timer started when the mouse leaves the view during - /// edge drawing - int m_leavedTimer; + /// identifier of the timer started when the mouse leaves the view during + /// edge drawing + int m_leavedTimer; - DotGraphView::ScrollDirection m_scrollDirection; + DotGraphView::ScrollDirection m_scrollDirection; - QPoint m_pressPos; - QPoint m_pressScrollBarsPos; + QPoint m_pressPos; + QPoint m_pressScrollBarsPos; - /// true if elements should be highlighted on hover; false otherwise - bool m_highlighting; + /// true if elements should be highlighted on hover; false otherwise + bool m_highlighting; - /// A thread to load graphviz agraph files - LoadAGraphThread m_loadThread; + /// A thread to load graphviz agraph files + LoadAGraphThread m_loadThread; - /// A thread to layout graphviz agraph files - LayoutAGraphThread m_layoutThread; + /// A thread to layout graphviz agraph files + LayoutAGraphThread m_layoutThread; - /// The graph background color - QColor m_backgroundColor; + /// The graph background color + QColor m_backgroundColor; - DotGraphView * const q_ptr; - Q_DECLARE_PUBLIC(DotGraphView); + DotGraphView *const q_ptr; + Q_DECLARE_PUBLIC(DotGraphView); }; - + void DotGraphViewPrivate::updateSizes(QSizeF s) { - Q_Q(DotGraphView); - if (m_canvas == nullptr) - return; - if (s == QSizeF(0,0)) s = q->size(); - - // the part of the canvas that should be visible - qreal cWidth = m_canvas->width() - 2*m_xMargin + 100; - qreal cHeight = m_canvas->height() - 2*m_yMargin + 100; - - // hide birds eye view if no overview needed - if (//!_data || !_activeItem || - !KGraphViewerPartSettings::birdsEyeViewEnabled() || - (((cWidth * m_zoom) < s.width()) && (cHeight * m_zoom) < s.height())) - { + Q_Q(DotGraphView); + if (m_canvas == nullptr) + return; + if (s == QSizeF(0, 0)) + s = q->size(); + + // the part of the canvas that should be visible + qreal cWidth = m_canvas->width() - 2 * m_xMargin + 100; + qreal cHeight = m_canvas->height() - 2 * m_yMargin + 100; + + // hide birds eye view if no overview needed + if ( //!_data || !_activeItem || + !KGraphViewerPartSettings::birdsEyeViewEnabled() || (((cWidth * m_zoom) < s.width()) && (cHeight * m_zoom) < s.height())) { + m_birdEyeView->hide(); + return; + } m_birdEyeView->hide(); - return; - } - m_birdEyeView->hide(); - - // first, assume use of 1/3 of width/height (possible larger) - double zoom = .33 * s.width() / cWidth; - if (zoom * cHeight < .33 * s.height()) zoom = .33 * s.height() / cHeight; - - // fit to widget size - if (cWidth * zoom > s.width()) zoom = s.width() / (double)cWidth; - if (cHeight * zoom > s.height()) zoom = s.height() / (double)cHeight; - - // scale to never use full height/width - zoom = zoom * 3/4; - - // at most a zoom of 1/3 - if (zoom > .33) zoom = .33; - - if (zoom != m_cvZoom) - { - m_cvZoom = zoom; - - QMatrix wm; - wm.scale( zoom, zoom ); - m_birdEyeView->setMatrix(wm); - - // make it a little bigger to compensate for widget frame - m_birdEyeView->resize((cWidth * zoom) + 4, - (cHeight * zoom) + 4); - - } - updateBirdEyeView(); - m_birdEyeView->setZoomRect(q->mapToScene(q->viewport()->rect()).boundingRect()); - m_birdEyeView->show(); - QSizeF newCanvasSize = m_canvas->sceneRect().size(); - if (newCanvasSize.width() < q->viewport()->width()) - { - newCanvasSize.setWidth(q->viewport()->width()); - } - else if (q->viewport()->width() < m_canvas->sceneRect().size().width()) - { - newCanvasSize.setWidth(m_canvas->sceneRect().size().width()); - } - if (newCanvasSize.height() < q->viewport()->height()) - { - newCanvasSize.setHeight(q->viewport()->height()); - } - else if (q->viewport()->height() < m_canvas->sceneRect().size().height()) - { - newCanvasSize.setHeight(m_canvas->sceneRect().size().height()); - } - // std::cerr << "done." << std::endl; + + // first, assume use of 1/3 of width/height (possible larger) + double zoom = .33 * s.width() / cWidth; + if (zoom * cHeight < .33 * s.height()) + zoom = .33 * s.height() / cHeight; + + // fit to widget size + if (cWidth * zoom > s.width()) + zoom = s.width() / (double)cWidth; + if (cHeight * zoom > s.height()) + zoom = s.height() / (double)cHeight; + + // scale to never use full height/width + zoom = zoom * 3 / 4; + + // at most a zoom of 1/3 + if (zoom > .33) + zoom = .33; + + if (zoom != m_cvZoom) { + m_cvZoom = zoom; + + QMatrix wm; + wm.scale(zoom, zoom); + m_birdEyeView->setMatrix(wm); + + // make it a little bigger to compensate for widget frame + m_birdEyeView->resize((cWidth * zoom) + 4, (cHeight * zoom) + 4); + } + updateBirdEyeView(); + m_birdEyeView->setZoomRect(q->mapToScene(q->viewport()->rect()).boundingRect()); + m_birdEyeView->show(); + QSizeF newCanvasSize = m_canvas->sceneRect().size(); + if (newCanvasSize.width() < q->viewport()->width()) { + newCanvasSize.setWidth(q->viewport()->width()); + } else if (q->viewport()->width() < m_canvas->sceneRect().size().width()) { + newCanvasSize.setWidth(m_canvas->sceneRect().size().width()); + } + if (newCanvasSize.height() < q->viewport()->height()) { + newCanvasSize.setHeight(q->viewport()->height()); + } else if (q->viewport()->height() < m_canvas->sceneRect().size().height()) { + newCanvasSize.setHeight(m_canvas->sceneRect().size().height()); + } + // std::cerr << "done." << std::endl; } void DotGraphViewPrivate::updateBirdEyeView() { - Q_Q(DotGraphView); - qreal cvW = m_birdEyeView->width(); - qreal cvH = m_birdEyeView->height(); - qreal x = q->width()- cvW - q->verticalScrollBar()->width() -2; - qreal y = q->height()-cvH - q->horizontalScrollBar()->height() -2; - QPoint oldZoomPos = m_birdEyeView->pos(); - QPoint newZoomPos = QPoint(0,0); - KGraphViewerInterface::PannerPosition zp = m_zoomPosition; - if (zp == KGraphViewerInterface::Auto) - { - QPointF tl1Pos = q->mapToScene(QPoint(0,0)); - QPointF tl2Pos = q->mapToScene(QPoint(cvW,cvH)); - QPointF tr1Pos = q->mapToScene(QPoint(x,0)); - QPointF tr2Pos = q->mapToScene(QPoint(x+cvW,cvH)); - QPointF bl1Pos = q->mapToScene(QPoint(0,y)); - QPointF bl2Pos = q->mapToScene(QPoint(cvW,y+cvH)); - QPointF br1Pos = q->mapToScene(QPoint(x,y)); - QPointF br2Pos = q->mapToScene(QPoint(x+cvW,y+cvH)); - int tlCols = m_canvas->items(QRectF(tl1Pos.x(),tl1Pos.y(),tl2Pos.x(),tl2Pos.y())).count(); - qCDebug(KGRAPHVIEWERLIB_LOG) << tr1Pos.x() << tr1Pos.y() << tr2Pos.x() << tr2Pos.y(); - int trCols = m_canvas->items(QRectF(tr1Pos.x(),tr1Pos.y(),tr2Pos.x(),tr2Pos.y())).count(); - int blCols = m_canvas->items(QRectF(bl1Pos.x(),bl1Pos.y(),bl2Pos.x(),bl2Pos.y())).count(); - int brCols = m_canvas->items(QRectF(br1Pos.x(),br1Pos.y(),br2Pos.x(),br2Pos.y())).count(); - int minCols = tlCols; - zp = m_lastAutoPosition; - switch(zp) - { - case KGraphViewerInterface::TopRight: minCols = trCols; break; - case KGraphViewerInterface::BottomLeft: minCols = blCols; break; - case KGraphViewerInterface::BottomRight: minCols = brCols; break; - default: - case KGraphViewerInterface::TopLeft: minCols = tlCols; break; - } - if (minCols > tlCols) { minCols = tlCols; zp = KGraphViewerInterface::TopLeft; } - if (minCols > trCols) { minCols = trCols; zp = KGraphViewerInterface::TopRight; } - if (minCols > blCols) { minCols = blCols; zp = KGraphViewerInterface::BottomLeft; } - if (minCols > brCols) { minCols = brCols; zp = KGraphViewerInterface::BottomRight; } - - m_lastAutoPosition = zp; - } - - switch(zp) - { + Q_Q(DotGraphView); + qreal cvW = m_birdEyeView->width(); + qreal cvH = m_birdEyeView->height(); + qreal x = q->width() - cvW - q->verticalScrollBar()->width() - 2; + qreal y = q->height() - cvH - q->horizontalScrollBar()->height() - 2; + QPoint oldZoomPos = m_birdEyeView->pos(); + QPoint newZoomPos = QPoint(0, 0); + KGraphViewerInterface::PannerPosition zp = m_zoomPosition; + if (zp == KGraphViewerInterface::Auto) { + QPointF tl1Pos = q->mapToScene(QPoint(0, 0)); + QPointF tl2Pos = q->mapToScene(QPoint(cvW, cvH)); + QPointF tr1Pos = q->mapToScene(QPoint(x, 0)); + QPointF tr2Pos = q->mapToScene(QPoint(x + cvW, cvH)); + QPointF bl1Pos = q->mapToScene(QPoint(0, y)); + QPointF bl2Pos = q->mapToScene(QPoint(cvW, y + cvH)); + QPointF br1Pos = q->mapToScene(QPoint(x, y)); + QPointF br2Pos = q->mapToScene(QPoint(x + cvW, y + cvH)); + int tlCols = m_canvas->items(QRectF(tl1Pos.x(), tl1Pos.y(), tl2Pos.x(), tl2Pos.y())).count(); + qCDebug(KGRAPHVIEWERLIB_LOG) << tr1Pos.x() << tr1Pos.y() << tr2Pos.x() << tr2Pos.y(); + int trCols = m_canvas->items(QRectF(tr1Pos.x(), tr1Pos.y(), tr2Pos.x(), tr2Pos.y())).count(); + int blCols = m_canvas->items(QRectF(bl1Pos.x(), bl1Pos.y(), bl2Pos.x(), bl2Pos.y())).count(); + int brCols = m_canvas->items(QRectF(br1Pos.x(), br1Pos.y(), br2Pos.x(), br2Pos.y())).count(); + int minCols = tlCols; + zp = m_lastAutoPosition; + switch (zp) { + case KGraphViewerInterface::TopRight: + minCols = trCols; + break; + case KGraphViewerInterface::BottomLeft: + minCols = blCols; + break; + case KGraphViewerInterface::BottomRight: + minCols = brCols; + break; + default: + case KGraphViewerInterface::TopLeft: + minCols = tlCols; + break; + } + if (minCols > tlCols) { + minCols = tlCols; + zp = KGraphViewerInterface::TopLeft; + } + if (minCols > trCols) { + minCols = trCols; + zp = KGraphViewerInterface::TopRight; + } + if (minCols > blCols) { + minCols = blCols; + zp = KGraphViewerInterface::BottomLeft; + } + if (minCols > brCols) { + minCols = brCols; + zp = KGraphViewerInterface::BottomRight; + } + + m_lastAutoPosition = zp; + } + + switch (zp) { case KGraphViewerInterface::TopRight: - newZoomPos = QPoint(x,0); - break; + newZoomPos = QPoint(x, 0); + break; case KGraphViewerInterface::BottomLeft: - newZoomPos = QPoint(0,y); - break; + newZoomPos = QPoint(0, y); + break; case KGraphViewerInterface::BottomRight: - newZoomPos = QPoint(x,y); - break; + newZoomPos = QPoint(x, y); + break; default: - break; - } - if (newZoomPos != oldZoomPos) - m_birdEyeView->move(newZoomPos); + break; + } + if (newZoomPos != oldZoomPos) + m_birdEyeView->move(newZoomPos); } double DotGraphViewPrivate::detailAdjustedScale() { - double scale = m_graph->scale(); - switch (m_detailLevel) - { - case 0: scale *= 0.7; break; - case 2: scale *= 1.3; break; - } - return scale; -} - -int DotGraphViewPrivate::displaySubgraph(GraphSubgraph* gsubgraph, int zValue, CanvasElement* parent) -{ - Q_Q(DotGraphView); - double scale = detailAdjustedScale(); - - qreal gh = m_graph->height(); - - if (gsubgraph->canvasSubgraph() == nullptr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas subgraph for" << gsubgraph->id(); - CanvasSubgraph* csubgraph = new CanvasSubgraph(q, gsubgraph, m_canvas, parent); - csubgraph->initialize(scale, scale, m_xMargin, m_yMargin, gh); - gsubgraph->setCanvasSubgraph(csubgraph); - // csubgraph->setZValue(gsubgraph->z()); - csubgraph->setZValue(zValue+=2); - csubgraph->show(); - m_canvas->addItem(csubgraph); - qCDebug(KGRAPHVIEWERLIB_LOG) << " one CanvasSubgraph... Done"; - } - foreach (GraphElement* element, gsubgraph->content()) - { - GraphNode* gnode = dynamic_cast(element); - if (gnode->canvasNode() == nullptr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas node for:" << gnode->id(); - CanvasNode *cnode = new CanvasNode(q, gnode, m_canvas); - if (cnode == nullptr) continue; - cnode->initialize(scale, scale, m_xMargin, m_yMargin, gh); - gnode->setCanvasNode(cnode); - m_canvas->addItem(cnode); - // cnode->setZValue(gnode->z()); - cnode->setZValue(zValue+1); - cnode->show(); - } - gnode->canvasNode()->computeBoundingRect(); - } - gsubgraph->canvasSubgraph()->computeBoundingRect(); - - int newZvalue = zValue; - foreach(GraphSubgraph* ssg, gsubgraph->subgraphs()) - { - int hereZvalue = displaySubgraph(ssg, zValue, gsubgraph->canvasSubgraph()); - if (hereZvalue > newZvalue) - newZvalue = hereZvalue; - } - return newZvalue; + double scale = m_graph->scale(); + switch (m_detailLevel) { + case 0: + scale *= 0.7; + break; + case 2: + scale *= 1.3; + break; + } + return scale; +} + +int DotGraphViewPrivate::displaySubgraph(GraphSubgraph *gsubgraph, int zValue, CanvasElement *parent) +{ + Q_Q(DotGraphView); + double scale = detailAdjustedScale(); + + qreal gh = m_graph->height(); + + if (gsubgraph->canvasSubgraph() == nullptr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas subgraph for" << gsubgraph->id(); + CanvasSubgraph *csubgraph = new CanvasSubgraph(q, gsubgraph, m_canvas, parent); + csubgraph->initialize(scale, scale, m_xMargin, m_yMargin, gh); + gsubgraph->setCanvasSubgraph(csubgraph); + // csubgraph->setZValue(gsubgraph->z()); + csubgraph->setZValue(zValue += 2); + csubgraph->show(); + m_canvas->addItem(csubgraph); + qCDebug(KGRAPHVIEWERLIB_LOG) << " one CanvasSubgraph... Done"; + } + foreach (GraphElement *element, gsubgraph->content()) { + GraphNode *gnode = dynamic_cast(element); + if (gnode->canvasNode() == nullptr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas node for:" << gnode->id(); + CanvasNode *cnode = new CanvasNode(q, gnode, m_canvas); + if (cnode == nullptr) + continue; + cnode->initialize(scale, scale, m_xMargin, m_yMargin, gh); + gnode->setCanvasNode(cnode); + m_canvas->addItem(cnode); + // cnode->setZValue(gnode->z()); + cnode->setZValue(zValue + 1); + cnode->show(); + } + gnode->canvasNode()->computeBoundingRect(); + } + gsubgraph->canvasSubgraph()->computeBoundingRect(); + + int newZvalue = zValue; + foreach (GraphSubgraph *ssg, gsubgraph->subgraphs()) { + int hereZvalue = displaySubgraph(ssg, zValue, gsubgraph->canvasSubgraph()); + if (hereZvalue > newZvalue) + newZvalue = hereZvalue; + } + return newZvalue; } void DotGraphViewPrivate::setupPopup() { - Q_Q(DotGraphView); - if (m_popup) - { - return; - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::setupPopup"; - m_popup = new QMenu(); - - m_layoutAlgoSelectAction = new KSelectAction(i18n("Select Layout Algo"),q); - actionCollection()->addAction("view_layout_algo",m_layoutAlgoSelectAction); - - QAction* lda = new QAction(i18n("Dot"), q); - lda->setWhatsThis(i18n("Layout the graph using the dot program.")); - actionCollection()->addAction("layout_dot",lda); - lda->setCheckable(true); - - QAction* lna = new QAction(i18n("Neato"), q); - lna->setWhatsThis(i18n("Layout the graph using the neato program.")); - actionCollection()->addAction("layout_neato",lna); - lna->setCheckable(true); - - QAction* lta = new QAction(i18n("Twopi"), q); - lta->setWhatsThis(i18n("Layout the graph using the twopi program.")); - actionCollection()->addAction("layout_twopi",lta); - lta->setCheckable(true); - - QAction* lfa = new QAction(i18n("Fdp"), q); - lfa->setWhatsThis(i18n("Layout the graph using the fdp program.")); - actionCollection()->addAction("layout_fdp",lfa); - lfa->setCheckable(true); - - QAction* lca = new QAction(i18n("Circo"), q); - lca->setWhatsThis(i18n("Layout the graph using the circo program.")); - actionCollection()->addAction("layout_c",lca); - lca->setCheckable(true); - - m_layoutAlgoSelectAction->addAction(lda); - m_layoutAlgoSelectAction->addAction(lna); - m_layoutAlgoSelectAction->addAction(lta); - m_layoutAlgoSelectAction->addAction(lfa); - m_layoutAlgoSelectAction->addAction(lca); - - m_layoutAlgoSelectAction->setCurrentAction(lda); - m_layoutAlgoSelectAction->setEditable(true); - m_layoutAlgoSelectAction->setToolTip(i18n("Choose a Graphviz layout algorithm or edit your own one.")); - m_layoutAlgoSelectAction->setWhatsThis(i18n( - "Choose a Graphviz layout algorithm or type in your own command that will " - "generate a graph in the xdot format on its standard output. For example, to " - "manually specify the G option to the dot command, type in: " - "dot -Gname=MyGraphName -Txdot ")); - QObject::connect(m_layoutAlgoSelectAction, static_cast(&KSelectAction::triggered), - q, &DotGraphView::slotSelectLayoutAlgo); - - - QMenu* layoutPopup = m_popup->addMenu(i18n("Layout")); - layoutPopup->addAction(m_layoutAlgoSelectAction); - QAction* slc = layoutPopup->addAction(i18n("Specify layout command"), q, SLOT(slotLayoutSpecify())); - slc->setWhatsThis(i18n("Specify yourself the layout command to use. Given a dot file, it should produce an xdot file on its standard output.")); - QAction* rlc = layoutPopup->addAction(i18n("Reset layout command to default"), q, SLOT(slotLayoutReset())); - rlc->setWhatsThis(i18n("Resets the layout command to use to the default depending on the graph type (directed or not).")); - - m_popup->addAction(QIcon::fromTheme("zoom-in"), i18n("Zoom In"), q, SLOT(zoomIn())); - m_popup->addAction(QIcon::fromTheme("zoom-out"), i18n("Zoom Out"), q, SLOT(zoomOut())); - - m_popup->addSeparator(); - - KActionMenu* file_exportMenu = new KActionMenu(i18n("Export Graph"), q); - actionCollection()->addAction("file_export",file_exportMenu); - file_exportMenu->setToolTip(i18n("Allows the graph to be exported in another format.")); - file_exportMenu->setWhatsThis(i18n( - "Use the Export Graph menu to export the graph in another format. " - "There is currently only one export format supported: as a PNG image.")); - - - m_popup->addAction(file_exportMenu); - QAction* exportToImageAction = new QAction(i18n("As Image..."),q); - exportToImageAction->setWhatsThis(i18n("Export the graph to an image file.")); - actionCollection()->addAction("export_image", exportToImageAction); - QObject::connect(exportToImageAction, &QAction::triggered, - q, &DotGraphView::slotExportImage); - - file_exportMenu->addAction(exportToImageAction); - - - m_popup->addSeparator(); - - m_bevEnabledAction = new KToggleAction( - QIcon(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-bev.png")), - i18n("Enable Bird's-eye View"), q); - actionCollection()->addAction("view_bev_enabled",m_bevEnabledAction); - actionCollection()->setDefaultShortcut(m_bevEnabledAction, Qt::CTRL+Qt::Key_B); + Q_Q(DotGraphView); + if (m_popup) { + return; + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::setupPopup"; + m_popup = new QMenu(); + + m_layoutAlgoSelectAction = new KSelectAction(i18n("Select Layout Algo"), q); + actionCollection()->addAction("view_layout_algo", m_layoutAlgoSelectAction); + + QAction *lda = new QAction(i18n("Dot"), q); + lda->setWhatsThis(i18n("Layout the graph using the dot program.")); + actionCollection()->addAction("layout_dot", lda); + lda->setCheckable(true); + + QAction *lna = new QAction(i18n("Neato"), q); + lna->setWhatsThis(i18n("Layout the graph using the neato program.")); + actionCollection()->addAction("layout_neato", lna); + lna->setCheckable(true); + + QAction *lta = new QAction(i18n("Twopi"), q); + lta->setWhatsThis(i18n("Layout the graph using the twopi program.")); + actionCollection()->addAction("layout_twopi", lta); + lta->setCheckable(true); + + QAction *lfa = new QAction(i18n("Fdp"), q); + lfa->setWhatsThis(i18n("Layout the graph using the fdp program.")); + actionCollection()->addAction("layout_fdp", lfa); + lfa->setCheckable(true); + + QAction *lca = new QAction(i18n("Circo"), q); + lca->setWhatsThis(i18n("Layout the graph using the circo program.")); + actionCollection()->addAction("layout_c", lca); + lca->setCheckable(true); + + m_layoutAlgoSelectAction->addAction(lda); + m_layoutAlgoSelectAction->addAction(lna); + m_layoutAlgoSelectAction->addAction(lta); + m_layoutAlgoSelectAction->addAction(lfa); + m_layoutAlgoSelectAction->addAction(lca); + + m_layoutAlgoSelectAction->setCurrentAction(lda); + m_layoutAlgoSelectAction->setEditable(true); + m_layoutAlgoSelectAction->setToolTip(i18n("Choose a Graphviz layout algorithm or edit your own one.")); + m_layoutAlgoSelectAction->setWhatsThis( + i18n("Choose a Graphviz layout algorithm or type in your own command that will " + "generate a graph in the xdot format on its standard output. For example, to " + "manually specify the G option to the dot command, type in: " + "dot -Gname=MyGraphName -Txdot ")); + QObject::connect(m_layoutAlgoSelectAction, static_cast(&KSelectAction::triggered), q, &DotGraphView::slotSelectLayoutAlgo); + + QMenu *layoutPopup = m_popup->addMenu(i18n("Layout")); + layoutPopup->addAction(m_layoutAlgoSelectAction); + QAction *slc = layoutPopup->addAction(i18n("Specify layout command"), q, SLOT(slotLayoutSpecify())); + slc->setWhatsThis(i18n("Specify yourself the layout command to use. Given a dot file, it should produce an xdot file on its standard output.")); + QAction *rlc = layoutPopup->addAction(i18n("Reset layout command to default"), q, SLOT(slotLayoutReset())); + rlc->setWhatsThis(i18n("Resets the layout command to use to the default depending on the graph type (directed or not).")); + + m_popup->addAction(QIcon::fromTheme("zoom-in"), i18n("Zoom In"), q, SLOT(zoomIn())); + m_popup->addAction(QIcon::fromTheme("zoom-out"), i18n("Zoom Out"), q, SLOT(zoomOut())); + + m_popup->addSeparator(); + + KActionMenu *file_exportMenu = new KActionMenu(i18n("Export Graph"), q); + actionCollection()->addAction("file_export", file_exportMenu); + file_exportMenu->setToolTip(i18n("Allows the graph to be exported in another format.")); + file_exportMenu->setWhatsThis( + i18n("Use the Export Graph menu to export the graph in another format. " + "There is currently only one export format supported: as a PNG image.")); + + m_popup->addAction(file_exportMenu); + QAction *exportToImageAction = new QAction(i18n("As Image..."), q); + exportToImageAction->setWhatsThis(i18n("Export the graph to an image file.")); + actionCollection()->addAction("export_image", exportToImageAction); + QObject::connect(exportToImageAction, &QAction::triggered, q, &DotGraphView::slotExportImage); + + file_exportMenu->addAction(exportToImageAction); + + m_popup->addSeparator(); + + m_bevEnabledAction = new KToggleAction(QIcon(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-bev.png")), i18n("Enable Bird's-eye View"), q); + actionCollection()->addAction("view_bev_enabled", m_bevEnabledAction); + actionCollection()->setDefaultShortcut(m_bevEnabledAction, Qt::CTRL + Qt::Key_B); m_bevEnabledAction->setWhatsThis(i18n("Enables or disables the Bird's-eye View")); - QObject::connect(m_bevEnabledAction, &QAction::triggered, - q, &DotGraphView::slotBevToggled); + QObject::connect(m_bevEnabledAction, &QAction::triggered, q, &DotGraphView::slotBevToggled); m_bevEnabledAction->setCheckable(true); m_popup->addAction(m_bevEnabledAction); - + m_bevPopup = new KSelectAction(i18n("Birds-eye View"), q); - m_bevPopup->setWhatsThis(i18n("Allows the Bird's-eye View to be setup.")); - m_popup->addAction(m_bevPopup); - actionCollection()->addAction("view_bev",m_bevPopup); - - QAction* btla = new QAction(i18n("Top Left"), q); - btla->setWhatsThis(i18n("Puts the Bird's-eye View in the top-left corner.")); - btla->setCheckable(true); - actionCollection()->addAction("bev_top_left",btla); - QObject::connect(btla, &QAction::triggered, - q, &DotGraphView::slotBevTopLeft); - QAction* btra = new QAction(i18n("Top Right"), q); - btra->setWhatsThis(i18n("Puts the Bird's-eye View in the top-right corner.")); - btra->setCheckable(true); - actionCollection()->addAction("bev_top_right",btra); - QObject::connect(btra, &QAction::triggered, - q, &DotGraphView::slotBevTopRight); - QAction* bbla = new QAction(i18n("Bottom Left"), q); - bbla->setWhatsThis(i18n("Puts the Bird's-eye View in the bottom-left corner.")); - bbla->setCheckable(true); - actionCollection()->addAction("bev_bottom_left",bbla); - QObject::connect(bbla, &QAction::triggered, - q, &DotGraphView::slotBevBottomLeft); - QAction* bbra = new QAction(i18n("Bottom Right"), q); - bbra->setWhatsThis(i18n("Puts the Bird's-eye View in the bottom-right corner.")); - bbra->setCheckable(true); - actionCollection()->addAction("bev_bottom_right",bbra); - QObject::connect(bbra, &QAction::triggered, - q, &DotGraphView::slotBevBottomRight); - QAction* bba = new QAction(i18n("Automatic"), q); - bba->setWhatsThis(i18n("Let KGraphViewer automatically choose the position of the Bird's-eye View.")); - bba->setCheckable(true); - actionCollection()->addAction("bev_automatic",bba); - QObject::connect(bba, &QAction::triggered, - q, &DotGraphView::slotBevAutomatic); - m_bevPopup->addAction(btla); - m_bevPopup->addAction(btra); - m_bevPopup->addAction(bbla); - m_bevPopup->addAction(bbra); - m_bevPopup->addAction(bba); - switch (m_zoomPosition) - { + m_bevPopup->setWhatsThis(i18n("Allows the Bird's-eye View to be setup.")); + m_popup->addAction(m_bevPopup); + actionCollection()->addAction("view_bev", m_bevPopup); + + QAction *btla = new QAction(i18n("Top Left"), q); + btla->setWhatsThis(i18n("Puts the Bird's-eye View in the top-left corner.")); + btla->setCheckable(true); + actionCollection()->addAction("bev_top_left", btla); + QObject::connect(btla, &QAction::triggered, q, &DotGraphView::slotBevTopLeft); + QAction *btra = new QAction(i18n("Top Right"), q); + btra->setWhatsThis(i18n("Puts the Bird's-eye View in the top-right corner.")); + btra->setCheckable(true); + actionCollection()->addAction("bev_top_right", btra); + QObject::connect(btra, &QAction::triggered, q, &DotGraphView::slotBevTopRight); + QAction *bbla = new QAction(i18n("Bottom Left"), q); + bbla->setWhatsThis(i18n("Puts the Bird's-eye View in the bottom-left corner.")); + bbla->setCheckable(true); + actionCollection()->addAction("bev_bottom_left", bbla); + QObject::connect(bbla, &QAction::triggered, q, &DotGraphView::slotBevBottomLeft); + QAction *bbra = new QAction(i18n("Bottom Right"), q); + bbra->setWhatsThis(i18n("Puts the Bird's-eye View in the bottom-right corner.")); + bbra->setCheckable(true); + actionCollection()->addAction("bev_bottom_right", bbra); + QObject::connect(bbra, &QAction::triggered, q, &DotGraphView::slotBevBottomRight); + QAction *bba = new QAction(i18n("Automatic"), q); + bba->setWhatsThis(i18n("Let KGraphViewer automatically choose the position of the Bird's-eye View.")); + bba->setCheckable(true); + actionCollection()->addAction("bev_automatic", bba); + QObject::connect(bba, &QAction::triggered, q, &DotGraphView::slotBevAutomatic); + m_bevPopup->addAction(btla); + m_bevPopup->addAction(btra); + m_bevPopup->addAction(bbla); + m_bevPopup->addAction(bbra); + m_bevPopup->addAction(bba); + switch (m_zoomPosition) { case KGraphViewerInterface::TopLeft: - btla->setChecked(true); - break; + btla->setChecked(true); + break; case KGraphViewerInterface::TopRight: - btra->setChecked(true); - break; + btra->setChecked(true); + break; case KGraphViewerInterface::BottomLeft: - bbla->setChecked(true); - break; + bbla->setChecked(true); + break; case KGraphViewerInterface::BottomRight: - bbra->setChecked(true); - break; + bbra->setChecked(true); + break; case KGraphViewerInterface::Auto: - bba->setChecked(true); - break; - } - - - qCDebug(KGRAPHVIEWERLIB_LOG) << " m_bevEnabledAction setting checked to : " << KGraphViewerPartSettings::birdsEyeViewEnabled(); - m_bevEnabledAction->setChecked(KGraphViewerPartSettings::birdsEyeViewEnabled()); - m_bevPopup->setEnabled(KGraphViewerPartSettings::birdsEyeViewEnabled()); + bba->setChecked(true); + break; + } + + qCDebug(KGRAPHVIEWERLIB_LOG) << " m_bevEnabledAction setting checked to : " << KGraphViewerPartSettings::birdsEyeViewEnabled(); + m_bevEnabledAction->setChecked(KGraphViewerPartSettings::birdsEyeViewEnabled()); + m_bevPopup->setEnabled(KGraphViewerPartSettings::birdsEyeViewEnabled()); } void DotGraphViewPrivate::exportToImage() { - // write current content of canvas as image to file - if (!m_canvas) return; - - QStringList writableMimetypes; - foreach (const QByteArray& mimeType, QImageWriter::supportedMimeTypes()) { - writableMimetypes.append(QString::fromLatin1(mimeType)); - } - const QString svgMimetype = QStringLiteral("image/svg+xml"); - if (!writableMimetypes.contains(svgMimetype)) { - writableMimetypes.append(svgMimetype); - } - - QFileDialog fileDialog(nullptr, i18n("Select file")); - fileDialog.setMimeTypeFilters(writableMimetypes); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - if (fileDialog.exec() != QFileDialog::Accepted) { - return; - } - const QString fn = fileDialog.selectedFiles().at(0); + // write current content of canvas as image to file + if (!m_canvas) + return; - if (!fn.isEmpty()) - { - if (fn.toLower().endsWith(QLatin1String(".svg"))) - { - QSvgGenerator generator; - generator.setFileName(fn); - generator.setSize(m_canvas->sceneRect().size().toSize()); -// generator.setViewBox(); - generator.setTitle(i18n("Graph SVG Generated by KGraphViewer")); - generator.setDescription(i18n("Graph SVG Generated by KGraphViewer.")); - QPainter painter; - painter.begin(&generator); - m_canvas->render( &painter ); - painter.end(); + QStringList writableMimetypes; + foreach (const QByteArray &mimeType, QImageWriter::supportedMimeTypes()) { + writableMimetypes.append(QString::fromLatin1(mimeType)); } - else - { - QPixmap pix(m_canvas->sceneRect().size().toSize()); - QPainter p(&pix); - m_canvas->render( &p ); - pix.save(fn, nullptr, 100); + const QString svgMimetype = QStringLiteral("image/svg+xml"); + if (!writableMimetypes.contains(svgMimetype)) { + writableMimetypes.append(svgMimetype); } - } + QFileDialog fileDialog(nullptr, i18n("Select file")); + fileDialog.setMimeTypeFilters(writableMimetypes); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + if (fileDialog.exec() != QFileDialog::Accepted) { + return; + } + const QString fn = fileDialog.selectedFiles().at(0); + + if (!fn.isEmpty()) { + if (fn.toLower().endsWith(QLatin1String(".svg"))) { + QSvgGenerator generator; + generator.setFileName(fn); + generator.setSize(m_canvas->sceneRect().size().toSize()); + // generator.setViewBox(); + generator.setTitle(i18n("Graph SVG Generated by KGraphViewer")); + generator.setDescription(i18n("Graph SVG Generated by KGraphViewer.")); + QPainter painter; + painter.begin(&generator); + m_canvas->render(&painter); + painter.end(); + } else { + QPixmap pix(m_canvas->sceneRect().size().toSize()); + QPainter p(&pix); + m_canvas->render(&p); + pix.save(fn, nullptr, 100); + } + } } - // // DotGraphView // -DotGraphView::DotGraphView(KActionCollection* actions, QWidget* parent) : - QGraphicsView(parent), d_ptr(new DotGraphViewPrivate(actions, this)) -{ - //qCDebug(KGRAPHVIEWERLIB_LOG) << "New node pic=" << KGlobal::dirs()->findResource("data","kgraphviewerpart/pics/kgraphviewer-newnode.png"); - Q_D(DotGraphView); - d->m_canvas = nullptr; - d->m_xMargin = d->m_yMargin = 0; - d->m_birdEyeView = new PannerView(this); - d->m_cvZoom = 1; - - // if there are ever graphic glitches to be found, remove this again - setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing | QGraphicsView::DontClipPainter | - QGraphicsView::DontSavePainterState); - - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - - d->m_birdEyeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - d->m_birdEyeView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - d->m_birdEyeView->raise(); - d->m_birdEyeView->hide(); - - setFocusPolicy(Qt::StrongFocus); - setBackgroundRole(QPalette::Window); -// viewport()->setMouseTracking(true); - - connect(d->m_birdEyeView, &PannerView::zoomRectMovedTo, - this, &DotGraphView::zoomRectMovedTo); - connect(d->m_birdEyeView, &PannerView::zoomRectMoveFinished, - this, &DotGraphView::zoomRectMoveFinished); - - setWhatsThis( i18n( - "

Graphviz DOT format graph visualization

" - "

If the graph is larger than the widget area, an overview " - "panner is shown in one edge. Choose through the context menu " - "if the optimal position of this overview should be automatically " - "computed or put it where you want.

" - "

How to work with it?

" - "
    " - "
  • To move the graph, you can:" - "
      " - "
    • click & drag it
    • " - "
    • use the elevators
    • " - "
    • press the arrows keys
    • " - "
    • click somewhere in the panner view
    • " - "
    • use the mouse wheel (up and down with no modifier, left and right with the key pressed)
    • " - "
    • or click & drag the panner view
    • " - "
    " - "
  • " - "
  • To zoom, you can either use the zoom in and zoom out toolbar buttons, or click on the key while rolling your mouse wheel.
  • " - "
  • Try the contextual menu (usually by right-clicking) to discover other " - "possibilities.
  • " - "
  • Try the Print preview or the Page setup buttons to explore the printing options.
  • " - "
" - ) ); - - readViewConfig(); - - QMatrix m; - m.scale(d->m_zoom,d->m_zoom); - setMatrix(m); - d->setupPopup(); - setInteractive(true); - setDragMode(NoDrag); - setRenderHint(QPainter::Antialiasing); - - connect(&d->m_loadThread, &LoadAGraphThread::finished, - this, &DotGraphView::slotAGraphReadFinished); - connect(&d->m_layoutThread, &LoadAGraphThread::finished, - this, &DotGraphView::slotAGraphLayoutFinished); +DotGraphView::DotGraphView(KActionCollection *actions, QWidget *parent) + : QGraphicsView(parent) + , d_ptr(new DotGraphViewPrivate(actions, this)) +{ + // qCDebug(KGRAPHVIEWERLIB_LOG) << "New node pic=" << KGlobal::dirs()->findResource("data","kgraphviewerpart/pics/kgraphviewer-newnode.png"); + Q_D(DotGraphView); + d->m_canvas = nullptr; + d->m_xMargin = d->m_yMargin = 0; + d->m_birdEyeView = new PannerView(this); + d->m_cvZoom = 1; + + // if there are ever graphic glitches to be found, remove this again + setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing | QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); + + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + + d->m_birdEyeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + d->m_birdEyeView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + d->m_birdEyeView->raise(); + d->m_birdEyeView->hide(); + + setFocusPolicy(Qt::StrongFocus); + setBackgroundRole(QPalette::Window); + // viewport()->setMouseTracking(true); + + connect(d->m_birdEyeView, &PannerView::zoomRectMovedTo, this, &DotGraphView::zoomRectMovedTo); + connect(d->m_birdEyeView, &PannerView::zoomRectMoveFinished, this, &DotGraphView::zoomRectMoveFinished); + + setWhatsThis( + i18n("

Graphviz DOT format graph visualization

" + "

If the graph is larger than the widget area, an overview " + "panner is shown in one edge. Choose through the context menu " + "if the optimal position of this overview should be automatically " + "computed or put it where you want.

" + "

How to work with it?

" + "
    " + "
  • To move the graph, you can:" + "
      " + "
    • click & drag it
    • " + "
    • use the elevators
    • " + "
    • press the arrows keys
    • " + "
    • click somewhere in the panner view
    • " + "
    • use the mouse wheel (up and down with no modifier, left and right with the key pressed)
    • " + "
    • or click & drag the panner view
    • " + "
    " + "
  • " + "
  • To zoom, you can either use the zoom in and zoom out toolbar buttons, or click on the key while rolling your mouse wheel.
  • " + "
  • Try the contextual menu (usually by right-clicking) to discover other " + "possibilities.
  • " + "
  • Try the Print preview or the Page setup buttons to explore the printing options.
  • " + "
")); + + readViewConfig(); + + QMatrix m; + m.scale(d->m_zoom, d->m_zoom); + setMatrix(m); + d->setupPopup(); + setInteractive(true); + setDragMode(NoDrag); + setRenderHint(QPainter::Antialiasing); + + connect(&d->m_loadThread, &LoadAGraphThread::finished, this, &DotGraphView::slotAGraphReadFinished); + connect(&d->m_layoutThread, &LoadAGraphThread::finished, this, &DotGraphView::slotAGraphLayoutFinished); } DotGraphView::~DotGraphView() { - saveViewConfig(); - Q_D(DotGraphView); - delete d; + saveViewConfig(); + Q_D(DotGraphView); + delete d; } -KGraphViewerInterface::PannerPosition DotGraphView::zoomPos() const { Q_D(const DotGraphView); return d->m_zoomPosition; } +KGraphViewerInterface::PannerPosition DotGraphView::zoomPos() const +{ + Q_D(const DotGraphView); + return d->m_zoomPosition; +} -double DotGraphView::zoom() const {Q_D(const DotGraphView); return d->m_zoom;} -KSelectAction* DotGraphView::bevPopup() {Q_D(DotGraphView); return d->m_bevPopup;} +double DotGraphView::zoom() const +{ + Q_D(const DotGraphView); + return d->m_zoom; +} +KSelectAction *DotGraphView::bevPopup() +{ + Q_D(DotGraphView); + return d->m_bevPopup; +} -DotGraph* DotGraphView::graph() {Q_D(DotGraphView); return d->m_graph;} -const DotGraph* DotGraphView::graph() const {Q_D(const DotGraphView); return d->m_graph;} +DotGraph *DotGraphView::graph() +{ + Q_D(DotGraphView); + return d->m_graph; +} +const DotGraph *DotGraphView::graph() const +{ + Q_D(const DotGraphView); + return d->m_graph; +} -const GraphElement* DotGraphView::defaultNewElement() const {Q_D(const DotGraphView); return d->m_defaultNewElement;} -QPixmap DotGraphView::defaultNewElementPixmap() const {Q_D(const DotGraphView); return d->m_defaultNewElementPixmap;} +const GraphElement *DotGraphView::defaultNewElement() const +{ + Q_D(const DotGraphView); + return d->m_defaultNewElement; +} +QPixmap DotGraphView::defaultNewElementPixmap() const +{ + Q_D(const DotGraphView); + return d->m_defaultNewElementPixmap; +} -void DotGraphView::setDefaultNewElement(GraphElement* elem) {Q_D(DotGraphView); d->m_defaultNewElement = elem;} -void DotGraphView::setDefaultNewElementPixmap(const QPixmap& pm) {Q_D(DotGraphView); d->m_defaultNewElementPixmap = pm;} +void DotGraphView::setDefaultNewElement(GraphElement *elem) +{ + Q_D(DotGraphView); + d->m_defaultNewElement = elem; +} +void DotGraphView::setDefaultNewElementPixmap(const QPixmap &pm) +{ + Q_D(DotGraphView); + d->m_defaultNewElementPixmap = pm; +} -bool DotGraphView::isReadWrite() const {Q_D(const DotGraphView); return d->m_readWrite;} -bool DotGraphView::isReadOnly() const {Q_D(const DotGraphView); return !d->m_readWrite;} +bool DotGraphView::isReadWrite() const +{ + Q_D(const DotGraphView); + return d->m_readWrite; +} +bool DotGraphView::isReadOnly() const +{ + Q_D(const DotGraphView); + return !d->m_readWrite; +} -bool DotGraphView::highlighting() {Q_D(DotGraphView); return d->m_highlighting;} -void DotGraphView::setHighlighting(bool highlightingValue) {Q_D(DotGraphView); d->m_highlighting = highlightingValue;} +bool DotGraphView::highlighting() +{ + Q_D(DotGraphView); + return d->m_highlighting; +} +void DotGraphView::setHighlighting(bool highlightingValue) +{ + Q_D(DotGraphView); + d->m_highlighting = highlightingValue; +} -DotGraphView::EditingMode DotGraphView::editingMode() const {Q_D(const DotGraphView); return d->m_editingMode;} +DotGraphView::EditingMode DotGraphView::editingMode() const +{ + Q_D(const DotGraphView); + return d->m_editingMode; +} -void DotGraphView::setBackgroundColor(const QColor& color) +void DotGraphView::setBackgroundColor(const QColor &color) { - Q_D(DotGraphView); - d->m_backgroundColor = color; - d->m_canvas->setBackgroundBrush(QBrush(d->m_backgroundColor)); + Q_D(DotGraphView); + d->m_backgroundColor = color; + d->m_canvas->setBackgroundBrush(QBrush(d->m_backgroundColor)); } bool DotGraphView::initEmpty() { - Q_D(DotGraphView); - d->m_birdEyeView->hide(); - d->m_birdEyeView->setScene(nullptr); - - if (d->m_canvas) - { - delete d->m_canvas; - d->m_canvas = nullptr; - } - - delete d->m_graph; - d->m_graph = new DotGraph(); - connect(d->m_graph, &DotGraph::readyToDisplay, - this, &DotGraphView::displayGraph); - - if (d->m_readWrite) - { - d->m_graph->setReadWrite(); - } - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing " << m_graph->dotFileName() << " with " << m_graph->layoutCommand(); - d->m_xMargin = 50; - d->m_yMargin = 50; - - QGraphicsScene* newCanvas = new QGraphicsScene(); - QGraphicsSimpleTextItem* item = newCanvas->addSimpleText(i18n("no graph loaded")); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; - - d->m_birdEyeView->setScene(newCanvas); -// std::cerr << "After m_birdEyeView set canvas" << std::endl; - - setScene(newCanvas); - d->m_canvas = newCanvas; - centerOn(item); - - d->m_cvZoom = 0; - - return true; -} - -bool DotGraphView::slotLoadLibrary(graph_t* graph) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << "graph_t"; - Q_D(DotGraphView); - d->m_birdEyeView->setScene(nullptr); - - if (d->m_canvas) - { - d->m_canvas->deleteLater(); - d->m_canvas = nullptr; - } + Q_D(DotGraphView); + d->m_birdEyeView->hide(); + d->m_birdEyeView->setScene(nullptr); - QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); - delete d->m_graph; + if (d->m_canvas) { + delete d->m_canvas; + d->m_canvas = nullptr; + } - if (layoutCommand.isEmpty()) - layoutCommand = "dot"; + delete d->m_graph; + d->m_graph = new DotGraph(); + connect(d->m_graph, &DotGraph::readyToDisplay, this, &DotGraphView::displayGraph); - qCDebug(KGRAPHVIEWERLIB_LOG) << "layoutCommand:" << layoutCommand; - d->m_graph = new DotGraph(layoutCommand,""); - d->m_graph->setUseLibrary(true); + if (d->m_readWrite) { + d->m_graph->setReadWrite(); + } - connect(d->m_graph, &DotGraph::readyToDisplay, - this, &DotGraphView::displayGraph); - connect(this, &DotGraphView::removeEdge, - d->m_graph, &DotGraph::removeEdge); - connect(this, &DotGraphView::removeNodeNamed, - d->m_graph, &DotGraph::removeNodeNamed); - connect(this, &DotGraphView::removeElement, - d->m_graph, &DotGraph::removeElement); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing " << m_graph->dotFileName() << " with " << m_graph->layoutCommand(); + d->m_xMargin = 50; + d->m_yMargin = 50; - if (d->m_readWrite) - { - d->m_graph->setReadWrite(); - } + QGraphicsScene *newCanvas = new QGraphicsScene(); + QGraphicsSimpleTextItem *item = newCanvas->addSimpleText(i18n("no graph loaded")); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; - if (layoutCommand.isEmpty()) - { - layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_graph->dotFileName()); - } - d->m_graph->layoutCommand(layoutCommand); + d->m_birdEyeView->setScene(newCanvas); + // std::cerr << "After m_birdEyeView set canvas" << std::endl; - GVC_t* gvc = gvContext(); - threadsafe_wrap_gvLayout(gvc, graph, layoutCommand.toUtf8().data()); - threadsafe_wrap_gvRender(gvc, graph, "xdot", nullptr); + setScene(newCanvas); + d->m_canvas = newCanvas; + centerOn(item); - d->m_xMargin = 50; - d->m_yMargin = 50; + d->m_cvZoom = 0; - QGraphicsScene* newCanvas = new QGraphicsScene(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; + return true; +} - d->m_birdEyeView->setScene(newCanvas); - // std::cerr << "After m_birdEyeView set canvas" << std::endl; +bool DotGraphView::slotLoadLibrary(graph_t *graph) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << "graph_t"; + Q_D(DotGraphView); + d->m_birdEyeView->setScene(nullptr); + + if (d->m_canvas) { + d->m_canvas->deleteLater(); + d->m_canvas = nullptr; + } - setScene(newCanvas); - connect(newCanvas, &QGraphicsScene::selectionChanged, - this, &DotGraphView::slotSelectionChanged); - d->m_canvas = newCanvas; + QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); + delete d->m_graph; - d->m_cvZoom = 0; + if (layoutCommand.isEmpty()) + layoutCommand = "dot"; - d->m_graph->updateWithGraph(graph); - d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); + qCDebug(KGRAPHVIEWERLIB_LOG) << "layoutCommand:" << layoutCommand; + d->m_graph = new DotGraph(layoutCommand, ""); + d->m_graph->setUseLibrary(true); + + connect(d->m_graph, &DotGraph::readyToDisplay, this, &DotGraphView::displayGraph); + connect(this, &DotGraphView::removeEdge, d->m_graph, &DotGraph::removeEdge); + connect(this, &DotGraphView::removeNodeNamed, d->m_graph, &DotGraph::removeNodeNamed); + connect(this, &DotGraphView::removeElement, d->m_graph, &DotGraph::removeElement); + + if (d->m_readWrite) { + d->m_graph->setReadWrite(); + } - gvFreeLayout(gvc, graph); - gvFreeContext(gvc); - return true; + if (layoutCommand.isEmpty()) { + layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_graph->dotFileName()); + } + d->m_graph->layoutCommand(layoutCommand); + + GVC_t *gvc = gvContext(); + threadsafe_wrap_gvLayout(gvc, graph, layoutCommand.toUtf8().data()); + threadsafe_wrap_gvRender(gvc, graph, "xdot", nullptr); + + d->m_xMargin = 50; + d->m_yMargin = 50; + + QGraphicsScene *newCanvas = new QGraphicsScene(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; + + d->m_birdEyeView->setScene(newCanvas); + // std::cerr << "After m_birdEyeView set canvas" << std::endl; + + setScene(newCanvas); + connect(newCanvas, &QGraphicsScene::selectionChanged, this, &DotGraphView::slotSelectionChanged); + d->m_canvas = newCanvas; + + d->m_cvZoom = 0; + + d->m_graph->updateWithGraph(graph); + d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); + + gvFreeLayout(gvc, graph); + gvFreeContext(gvc); + return true; } -bool DotGraphView::loadDot(const QString& dotFileName) +bool DotGraphView::loadDot(const QString &dotFileName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << dotFileName << "'"; - Q_D(DotGraphView); - d->m_birdEyeView->setScene(nullptr); + qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << dotFileName << "'"; + Q_D(DotGraphView); + d->m_birdEyeView->setScene(nullptr); - if (d->m_canvas) - { - d->m_canvas->deleteLater(); - d->m_canvas = nullptr; - } - - QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); - delete d->m_graph; - - d->m_graph = new DotGraph(layoutCommand,dotFileName); - connect(d->m_graph, &DotGraph::readyToDisplay, - this, &DotGraphView::displayGraph); - - if (d->m_readWrite) - { - d->m_graph->setReadWrite(); - } - if (layoutCommand.isEmpty()) - { - layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_graph->dotFileName()); - } - d->m_graph->layoutCommand(layoutCommand); - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing " << m_graph->dotFileName() << " with " << m_graph->layoutCommand(); - d->m_xMargin = 50; - d->m_yMargin = 50; - - QGraphicsScene* newCanvas = new QGraphicsScene(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; - - d->m_birdEyeView->setScene(newCanvas); -// std::cerr << "After m_birdEyeView set canvas" << std::endl; - - setScene(newCanvas); - connect(newCanvas, &QGraphicsScene::selectionChanged, - this, &DotGraphView::slotSelectionChanged); - d->m_canvas = newCanvas; - - QGraphicsSimpleTextItem* loadingLabel = newCanvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); - loadingLabel->setZValue(100); - centerOn(loadingLabel); - - d->m_cvZoom = 0; - - if (!d->m_graph->parseDot(d->m_graph->dotFileName())) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "NOT successfully parsed!" << endl; - loadingLabel->setText(i18n("error parsing file %1", dotFileName)); - return false; - } - d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); - return true; -} - -bool DotGraphView::loadLibrarySync(const QString& dotFileName) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << "loading sync: '" << dotFileName << "'"; - Q_D(DotGraphView); - if (d->m_canvas) - d->m_canvas->clear(); - QGraphicsSimpleTextItem* loadingLabel = d->m_canvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); - loadingLabel->setZValue(100); - centerOn(loadingLabel); - - // HACK: store filename in m_loadThread data structure for pick up by slotAGraphLayoutFinished() - // Both methods loadLibrarySync(QString) and loadLibrary(QString) after loading the file - // activate the m_layoutThread. And it is only the handler of that thread's finished signal. - // slotAGraphLayoutFinished(), which then completes the loading of the file and stores the - // filename with the graph data, taking it from m_loadThread. - // As intermediate solution to a rewrite of the loading code, for now the filename is simply - // also stored in the m_loadThread object from this code path, so the rest of the existing code - // does not need to be further adapted. - d->m_loadThread.setDotFileName(dotFileName); - - qCDebug(KGRAPHVIEWERLIB_LOG) << dotFileName; - FILE* fp = fopen(dotFileName.toUtf8().data(), "r"); - if (!fp) { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to open file " << dotFileName; - return false; - } - graph_t* graph = agread(fp, nullptr); - if (!graph) { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file, retrying to work around graphviz bug(?)"; - rewind(fp); - graph = agread(fp, nullptr); - } - fclose(fp); - if (!graph) { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file " << dotFileName; - return false; - } - - QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); - if (layoutCommand.isEmpty()) { - layoutCommand = d->m_graph ? d->m_graph->chooseLayoutProgramForFile(dotFileName) : "dot"; - } - d->m_layoutThread.layoutGraph(graph, layoutCommand); - - return true; -} - -bool DotGraphView::loadLibrary(const QString& dotFileName) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << dotFileName << "'"; - Q_D(DotGraphView); - if (d->m_canvas) - d->m_canvas->clear(); - QGraphicsSimpleTextItem* loadingLabel = d->m_canvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); - loadingLabel->setZValue(100); - centerOn(loadingLabel); - - d->m_loadThread.loadFile(dotFileName); - - return true; -} - -bool DotGraphView::loadLibrary(graph_t* graph, const QString& layoutCommand) -{ - qCDebug(KGRAPHVIEWERLIB_LOG) << "graph_t"; - Q_D(DotGraphView); - d->m_birdEyeView->setScene(nullptr); - - if (d->m_canvas) - { - d->m_canvas->deleteLater(); - d->m_canvas = nullptr; - } - - delete d->m_graph; - d->m_graph = nullptr; - - if (!graph) - return false; - - qCDebug(KGRAPHVIEWERLIB_LOG) << "layoutCommand:" << layoutCommand; - d->m_graph = new DotGraph(layoutCommand,""); - d->m_graph->setUseLibrary(true); - - connect(d->m_graph, &DotGraph::readyToDisplay, - this, &DotGraphView::displayGraph); - - if (d->m_readWrite) - { - d->m_graph->setReadWrite(); - } - - d->m_xMargin = 50; - d->m_yMargin = 50; - - QGraphicsScene* newCanvas = new QGraphicsScene(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; - - d->m_birdEyeView->setScene(newCanvas); - setScene(newCanvas); - connect(newCanvas, &QGraphicsScene::selectionChanged, - this, &DotGraphView::slotSelectionChanged); - d->m_canvas = newCanvas; - - d->m_cvZoom = 0; - - d->m_graph->updateWithGraph(graph); - d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); - - return true; + if (d->m_canvas) { + d->m_canvas->deleteLater(); + d->m_canvas = nullptr; + } + + QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); + delete d->m_graph; + + d->m_graph = new DotGraph(layoutCommand, dotFileName); + connect(d->m_graph, &DotGraph::readyToDisplay, this, &DotGraphView::displayGraph); + + if (d->m_readWrite) { + d->m_graph->setReadWrite(); + } + if (layoutCommand.isEmpty()) { + layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_graph->dotFileName()); + } + d->m_graph->layoutCommand(layoutCommand); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Parsing " << m_graph->dotFileName() << " with " << m_graph->layoutCommand(); + d->m_xMargin = 50; + d->m_yMargin = 50; + + QGraphicsScene *newCanvas = new QGraphicsScene(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; + + d->m_birdEyeView->setScene(newCanvas); + // std::cerr << "After m_birdEyeView set canvas" << std::endl; + + setScene(newCanvas); + connect(newCanvas, &QGraphicsScene::selectionChanged, this, &DotGraphView::slotSelectionChanged); + d->m_canvas = newCanvas; + + QGraphicsSimpleTextItem *loadingLabel = newCanvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); + loadingLabel->setZValue(100); + centerOn(loadingLabel); + + d->m_cvZoom = 0; + + if (!d->m_graph->parseDot(d->m_graph->dotFileName())) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "NOT successfully parsed!" << endl; + loadingLabel->setText(i18n("error parsing file %1", dotFileName)); + return false; + } + d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); + return true; +} + +bool DotGraphView::loadLibrarySync(const QString &dotFileName) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << "loading sync: '" << dotFileName << "'"; + Q_D(DotGraphView); + if (d->m_canvas) + d->m_canvas->clear(); + QGraphicsSimpleTextItem *loadingLabel = d->m_canvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); + loadingLabel->setZValue(100); + centerOn(loadingLabel); + + // HACK: store filename in m_loadThread data structure for pick up by slotAGraphLayoutFinished() + // Both methods loadLibrarySync(QString) and loadLibrary(QString) after loading the file + // activate the m_layoutThread. And it is only the handler of that thread's finished signal. + // slotAGraphLayoutFinished(), which then completes the loading of the file and stores the + // filename with the graph data, taking it from m_loadThread. + // As intermediate solution to a rewrite of the loading code, for now the filename is simply + // also stored in the m_loadThread object from this code path, so the rest of the existing code + // does not need to be further adapted. + d->m_loadThread.setDotFileName(dotFileName); + + qCDebug(KGRAPHVIEWERLIB_LOG) << dotFileName; + FILE *fp = fopen(dotFileName.toUtf8().data(), "r"); + if (!fp) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to open file " << dotFileName; + return false; + } + graph_t *graph = agread(fp, nullptr); + if (!graph) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file, retrying to work around graphviz bug(?)"; + rewind(fp); + graph = agread(fp, nullptr); + } + fclose(fp); + if (!graph) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file " << dotFileName; + return false; + } + + QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); + if (layoutCommand.isEmpty()) { + layoutCommand = d->m_graph ? d->m_graph->chooseLayoutProgramForFile(dotFileName) : "dot"; + } + d->m_layoutThread.layoutGraph(graph, layoutCommand); + + return true; +} + +bool DotGraphView::loadLibrary(const QString &dotFileName) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << "'" << dotFileName << "'"; + Q_D(DotGraphView); + if (d->m_canvas) + d->m_canvas->clear(); + QGraphicsSimpleTextItem *loadingLabel = d->m_canvas->addSimpleText(i18n("graph %1 is getting loaded...", dotFileName)); + loadingLabel->setZValue(100); + centerOn(loadingLabel); + + d->m_loadThread.loadFile(dotFileName); + + return true; +} + +bool DotGraphView::loadLibrary(graph_t *graph, const QString &layoutCommand) +{ + qCDebug(KGRAPHVIEWERLIB_LOG) << "graph_t"; + Q_D(DotGraphView); + d->m_birdEyeView->setScene(nullptr); + + if (d->m_canvas) { + d->m_canvas->deleteLater(); + d->m_canvas = nullptr; + } + + delete d->m_graph; + d->m_graph = nullptr; + + if (!graph) + return false; + + qCDebug(KGRAPHVIEWERLIB_LOG) << "layoutCommand:" << layoutCommand; + d->m_graph = new DotGraph(layoutCommand, ""); + d->m_graph->setUseLibrary(true); + + connect(d->m_graph, &DotGraph::readyToDisplay, this, &DotGraphView::displayGraph); + + if (d->m_readWrite) { + d->m_graph->setReadWrite(); + } + + d->m_xMargin = 50; + d->m_yMargin = 50; + + QGraphicsScene *newCanvas = new QGraphicsScene(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Created canvas " << newCanvas; + + d->m_birdEyeView->setScene(newCanvas); + setScene(newCanvas); + connect(newCanvas, &QGraphicsScene::selectionChanged, this, &DotGraphView::slotSelectionChanged); + d->m_canvas = newCanvas; + + d->m_cvZoom = 0; + + d->m_graph->updateWithGraph(graph); + d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); + + return true; } void DotGraphView::slotSelectionChanged() { - qCDebug(KGRAPHVIEWERLIB_LOG) << scene()->selectedItems().size(); + qCDebug(KGRAPHVIEWERLIB_LOG) << scene()->selectedItems().size(); } bool DotGraphView::displayGraph() { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << d->m_graph->backColor(); -// hide(); - viewport()->setUpdatesEnabled(false); - - if (d->m_graph->backColor().size() != 0) - { - setBackgroundColor(QColor(d->m_graph->backColor())); - } - - if (d->m_graph->nodes().size() > KGV_MAX_PANNER_NODES) - { - d->m_birdEyeView->setDrawingEnabled(false); - } - // QCanvasEllipse* eItem; - double scale = d->detailAdjustedScale(); - - qreal gh = d->m_graph->height(); - - d->m_xMargin = 50; - d->m_yMargin = 50; - - -// m_canvas->setSceneRect(0,0,w+2*m_xMargin, h+2*m_yMargin); -// m_canvas->setBackgroundBrush(QBrush(QColor(m_graph->backColor()))); - d->m_canvas->setBackgroundBrush(QBrush(d->m_backgroundColor)); - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "sceneRect is now " << m_canvas->sceneRect(); - - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->subgraphs().size() << "CanvasSubgraphs from" << d->m_graph; - int zvalue = -1; - foreach (GraphSubgraph* gsubgraph, d->m_graph->subgraphs()) - { - int newZvalue = d->displaySubgraph(gsubgraph, zvalue); - if (newZvalue > zvalue) - zvalue = newZvalue; - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->nodes().size() << "nodes from" << d->m_graph; - GraphNodeMap::const_iterator it = d->m_graph->nodes().constBegin(); - for (; it != d->m_graph->nodes().constEnd();it++) - { - const QString& id = it.key(); - GraphNode* gnode = it.value(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Handling" << id << (void*)gnode; - qCDebug(KGRAPHVIEWERLIB_LOG) << " gnode id=" << gnode->id(); - qCDebug(KGRAPHVIEWERLIB_LOG)<< " canvasNode=" << (void*)gnode->canvasNode(); - if (gnode->canvasNode() == nullptr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas node for" << gnode->id(); - CanvasNode *cnode = new CanvasNode(this, gnode, d->m_canvas); - if (cnode == nullptr) continue; - cnode->initialize(scale, scale, d->m_xMargin, d->m_yMargin, gh); - gnode->setCanvasNode(cnode); - d->m_canvas->addItem(cnode); -// cnode->setZValue(gnode->z()); - cnode->setZValue(zvalue+1); - cnode->show(); - } - gnode->canvasNode()->computeBoundingRect(); - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->edges().size() << "edges from" << d->m_graph; - foreach (GraphEdge* gedge, d->m_graph->edges()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "One GraphEdge:" << gedge->id(); - if (gedge->canvasEdge() == nullptr - && gedge->fromNode() - && gedge->toNode()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "New CanvasEdge for" << gedge->id(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "edge fromNode=" << (void*)gedge->fromNode(); - qCDebug(KGRAPHVIEWERLIB_LOG) << " "<< gedge->fromNode()->id(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "edge toNode=" << (void*)gedge->toNode(); - qCDebug(KGRAPHVIEWERLIB_LOG) << " "<< gedge->toNode()->id(); - CanvasEdge* cedge = new CanvasEdge(this, gedge, scale, scale, d->m_xMargin, - d->m_yMargin, gh, d->m_graph->wdhcf(), d->m_graph->hdvcf()); - - gedge->setCanvasEdge(cedge); - // std::cerr << "setting z = " << gedge->z() << std::endl; - // cedge->setZValue(gedge->z()); - cedge->setZValue(zvalue+2); - cedge->show(); - d->m_canvas->addItem(cedge); - } - if (gedge->canvasEdge()) - gedge->canvasEdge()->computeBoundingRect(); - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding graph render operations: " << d->m_graph->renderOperations().size(); - foreach (const DotRenderOp& dro, d->m_graph->renderOperations()) - { - if ( dro.renderop == "T" ) - { -// std::cerr << "Adding graph label '"<m_graph->fontSize(); - QFont* font = FontsCache::changeable().fromName(d->m_graph->fontName()); - font->setPointSize(fontSize); - QFontMetrics fm(*font); - while (fm.width(str) > stringWidthGoal && fontSize > 1) - { - fontSize--; - font->setPointSize(fontSize); - fm = QFontMetrics(*font); - } - QGraphicsSimpleTextItem* labelView = new QGraphicsSimpleTextItem(str, d->m_canvas->activePanel()); - labelView->setFont(*font); - labelView->setPos( - (scale * - ( - (dro.integers[0]) - + (((dro.integers[2])*(dro.integers[3]))/2) - - ( (dro.integers[3])/2 ) - ) - + d->m_xMargin ), - ((gh - (dro.integers[1]))*scale)+ d->m_yMargin); - /// @todo port that ; how to set text color ? - labelView->setPen(QPen(Dot2QtConsts::componentData().qtColor(d->m_graph->fontColor()))); - labelView->setFont(*font); - d->m_labelViews.insert(labelView); - } - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "Finalizing"; - d->m_cvZoom = 0; - d->updateSizes(); - - centerOn(d->m_canvas->sceneRect().center()); - - viewport()->setUpdatesEnabled(true); - QSet::iterator labelViewsIt, labelViewsIt_end; - labelViewsIt = d->m_labelViews.begin(); labelViewsIt_end = d->m_labelViews.end(); - for (; labelViewsIt != labelViewsIt_end; labelViewsIt++) - { - (*labelViewsIt)->show(); - } - d->m_canvas->update(); - - emit graphLoaded(); - - return true; -} - -void DotGraphView::focusInEvent(QFocusEvent*) -{ - Q_D(DotGraphView); - if (!d->m_canvas) return; - -// m_canvas->update(); -} - -void DotGraphView::focusOutEvent(QFocusEvent* e) -{ - // trigger updates as in focusInEvent - focusInEvent(e); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << d->m_graph->backColor(); + // hide(); + viewport()->setUpdatesEnabled(false); + + if (d->m_graph->backColor().size() != 0) { + setBackgroundColor(QColor(d->m_graph->backColor())); + } + + if (d->m_graph->nodes().size() > KGV_MAX_PANNER_NODES) { + d->m_birdEyeView->setDrawingEnabled(false); + } + // QCanvasEllipse* eItem; + double scale = d->detailAdjustedScale(); + + qreal gh = d->m_graph->height(); + + d->m_xMargin = 50; + d->m_yMargin = 50; + + // m_canvas->setSceneRect(0,0,w+2*m_xMargin, h+2*m_yMargin); + // m_canvas->setBackgroundBrush(QBrush(QColor(m_graph->backColor()))); + d->m_canvas->setBackgroundBrush(QBrush(d->m_backgroundColor)); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "sceneRect is now " << m_canvas->sceneRect(); + + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->subgraphs().size() << "CanvasSubgraphs from" << d->m_graph; + int zvalue = -1; + foreach (GraphSubgraph *gsubgraph, d->m_graph->subgraphs()) { + int newZvalue = d->displaySubgraph(gsubgraph, zvalue); + if (newZvalue > zvalue) + zvalue = newZvalue; + } + + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->nodes().size() << "nodes from" << d->m_graph; + GraphNodeMap::const_iterator it = d->m_graph->nodes().constBegin(); + for (; it != d->m_graph->nodes().constEnd(); it++) { + const QString &id = it.key(); + GraphNode *gnode = it.value(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Handling" << id << (void *)gnode; + qCDebug(KGRAPHVIEWERLIB_LOG) << " gnode id=" << gnode->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << " canvasNode=" << (void *)gnode->canvasNode(); + if (gnode->canvasNode() == nullptr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating canvas node for" << gnode->id(); + CanvasNode *cnode = new CanvasNode(this, gnode, d->m_canvas); + if (cnode == nullptr) + continue; + cnode->initialize(scale, scale, d->m_xMargin, d->m_yMargin, gh); + gnode->setCanvasNode(cnode); + d->m_canvas->addItem(cnode); + // cnode->setZValue(gnode->z()); + cnode->setZValue(zvalue + 1); + cnode->show(); + } + gnode->canvasNode()->computeBoundingRect(); + } + + qCDebug(KGRAPHVIEWERLIB_LOG) << "Creating" << d->m_graph->edges().size() << "edges from" << d->m_graph; + foreach (GraphEdge *gedge, d->m_graph->edges()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "One GraphEdge:" << gedge->id(); + if (gedge->canvasEdge() == nullptr && gedge->fromNode() && gedge->toNode()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "New CanvasEdge for" << gedge->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "edge fromNode=" << (void *)gedge->fromNode(); + qCDebug(KGRAPHVIEWERLIB_LOG) << " " << gedge->fromNode()->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "edge toNode=" << (void *)gedge->toNode(); + qCDebug(KGRAPHVIEWERLIB_LOG) << " " << gedge->toNode()->id(); + CanvasEdge *cedge = new CanvasEdge(this, gedge, scale, scale, d->m_xMargin, d->m_yMargin, gh, d->m_graph->wdhcf(), d->m_graph->hdvcf()); + + gedge->setCanvasEdge(cedge); + // std::cerr << "setting z = " << gedge->z() << std::endl; + // cedge->setZValue(gedge->z()); + cedge->setZValue(zvalue + 2); + cedge->show(); + d->m_canvas->addItem(cedge); + } + if (gedge->canvasEdge()) + gedge->canvasEdge()->computeBoundingRect(); + } + qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding graph render operations: " << d->m_graph->renderOperations().size(); + foreach (const DotRenderOp &dro, d->m_graph->renderOperations()) { + if (dro.renderop == "T") { + // std::cerr << "Adding graph label '"<m_graph->fontSize(); + QFont *font = FontsCache::changeable().fromName(d->m_graph->fontName()); + font->setPointSize(fontSize); + QFontMetrics fm(*font); + while (fm.width(str) > stringWidthGoal && fontSize > 1) { + fontSize--; + font->setPointSize(fontSize); + fm = QFontMetrics(*font); + } + QGraphicsSimpleTextItem *labelView = new QGraphicsSimpleTextItem(str, d->m_canvas->activePanel()); + labelView->setFont(*font); + labelView->setPos((scale * ((dro.integers[0]) + (((dro.integers[2]) * (dro.integers[3])) / 2) - ((dro.integers[3]) / 2)) + d->m_xMargin), ((gh - (dro.integers[1])) * scale) + d->m_yMargin); + /// @todo port that ; how to set text color ? + labelView->setPen(QPen(Dot2QtConsts::componentData().qtColor(d->m_graph->fontColor()))); + labelView->setFont(*font); + d->m_labelViews.insert(labelView); + } + } + + qCDebug(KGRAPHVIEWERLIB_LOG) << "Finalizing"; + d->m_cvZoom = 0; + d->updateSizes(); + + centerOn(d->m_canvas->sceneRect().center()); + + viewport()->setUpdatesEnabled(true); + QSet::iterator labelViewsIt, labelViewsIt_end; + labelViewsIt = d->m_labelViews.begin(); + labelViewsIt_end = d->m_labelViews.end(); + for (; labelViewsIt != labelViewsIt_end; labelViewsIt++) { + (*labelViewsIt)->show(); + } + d->m_canvas->update(); + + emit graphLoaded(); + + return true; } -void DotGraphView::scrollViewPercent(bool horizontal, int percent) +void DotGraphView::focusInEvent(QFocusEvent *) { - QScrollBar *scrollbar = horizontal ? horizontalScrollBar() : verticalScrollBar(); - int amount = horizontal ? viewport()->width() : viewport()->height(); - amount = amount * percent / 100; - scrollbar->setValue(scrollbar->value() + amount); + Q_D(DotGraphView); + if (!d->m_canvas) + return; + + // m_canvas->update(); } -void DotGraphView::keyPressEvent(QKeyEvent* e) +void DotGraphView::focusOutEvent(QFocusEvent *e) { - Q_D(DotGraphView); - if (!d->m_canvas) - { - e->ignore(); - return; - } - - // move canvas... - if (e->key() == Qt::Key_Home) - verticalScrollBar()->setValue(verticalScrollBar()->minimum()); - else if (e->key() == Qt::Key_End) - verticalScrollBar()->setValue(verticalScrollBar()->maximum()); - else if (e->key() == Qt::Key_PageUp) - scrollViewPercent(false, -50); - else if (e->key() == Qt::Key_PageDown) - scrollViewPercent(false, 50); - else if (e->key() == Qt::Key_Left) - scrollViewPercent(true, -10); - else if (e->key() == Qt::Key_Right) - scrollViewPercent(true, 10); - else if (e->key() == Qt::Key_Down) - scrollViewPercent(false, 10); - else if (e->key() == Qt::Key_Up) - scrollViewPercent(false, -10); - else - { - e->ignore(); - return; - } + // trigger updates as in focusInEvent + focusInEvent(e); } -void DotGraphView::wheelEvent(QWheelEvent* e) +void DotGraphView::scrollViewPercent(bool horizontal, int percent) { - Q_D(DotGraphView); - if (!d->m_canvas) - { - e->ignore(); - return; - } - e->accept(); - if (QApplication::keyboardModifiers() == Qt::ShiftModifier || - QApplication::keyboardModifiers() == Qt::ControlModifier) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << " + Shift/Ctrl: zooming"; + QScrollBar *scrollbar = horizontal ? horizontalScrollBar() : verticalScrollBar(); + int amount = horizontal ? viewport()->width() : viewport()->height(); + amount = amount * percent / 100; + scrollbar->setValue(scrollbar->value() + amount); +} + +void DotGraphView::keyPressEvent(QKeyEvent *e) +{ + Q_D(DotGraphView); + if (!d->m_canvas) { + e->ignore(); + return; + } + // move canvas... - if (e->delta() < 0) - { - zoomOut(); + if (e->key() == Qt::Key_Home) + verticalScrollBar()->setValue(verticalScrollBar()->minimum()); + else if (e->key() == Qt::Key_End) + verticalScrollBar()->setValue(verticalScrollBar()->maximum()); + else if (e->key() == Qt::Key_PageUp) + scrollViewPercent(false, -50); + else if (e->key() == Qt::Key_PageDown) + scrollViewPercent(false, 50); + else if (e->key() == Qt::Key_Left) + scrollViewPercent(true, -10); + else if (e->key() == Qt::Key_Right) + scrollViewPercent(true, 10); + else if (e->key() == Qt::Key_Down) + scrollViewPercent(false, 10); + else if (e->key() == Qt::Key_Up) + scrollViewPercent(false, -10); + else { + e->ignore(); + return; } - else - { - zoomIn(); +} + +void DotGraphView::wheelEvent(QWheelEvent *e) +{ + Q_D(DotGraphView); + if (!d->m_canvas) { + e->ignore(); + return; + } + e->accept(); + if (QApplication::keyboardModifiers() == Qt::ShiftModifier || QApplication::keyboardModifiers() == Qt::ControlModifier) { + qCDebug(KGRAPHVIEWERLIB_LOG) << " + Shift/Ctrl: zooming"; + // move canvas... + if (e->delta() < 0) { + zoomOut(); + } else { + zoomIn(); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << " : scrolling "; + scrollViewPercent(e->orientation() == Qt::Horizontal, e->delta() < 0 ? 10 : -10); } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << " : scrolling "; - scrollViewPercent(e->orientation() == Qt::Horizontal, e->delta() < 0 ? 10 : -10); - } } void DotGraphView::zoomIn() { - applyZoom(1.10); + applyZoom(1.10); } - void DotGraphView::zoomOut() { - applyZoom(.90); + applyZoom(.90); } void DotGraphView::setZoomFactor(double newZoom) { - Q_D(DotGraphView); - if (newZoom < 0.1 || newZoom > 10) - return; - d->m_zoom = newZoom; - if (d->m_zoom > 1.0 && d->m_zoom < 1.1) - { - d->m_zoom = 1; - } + Q_D(DotGraphView); + if (newZoom < 0.1 || newZoom > 10) + return; + d->m_zoom = newZoom; + if (d->m_zoom > 1.0 && d->m_zoom < 1.1) { + d->m_zoom = 1; + } - setUpdatesEnabled(false); - QMatrix m; - m.scale(d->m_zoom,d->m_zoom); - setMatrix(m); - emit zoomed(d->m_zoom); - setUpdatesEnabled(true); - d->updateSizes(); + setUpdatesEnabled(false); + QMatrix m; + m.scale(d->m_zoom, d->m_zoom); + setMatrix(m); + emit zoomed(d->m_zoom); + setUpdatesEnabled(true); + d->updateSizes(); } void DotGraphView::applyZoom(double factor) { - Q_D(DotGraphView); - setZoomFactor(d->m_zoom * factor); + Q_D(DotGraphView); + setZoomFactor(d->m_zoom * factor); } void DotGraphView::scrollContentsBy(int dx, int dy) { - Q_D(DotGraphView); - QGraphicsView::scrollContentsBy(dx, dy); - if (d->m_birdEyeView && scene()) { // we might be shutting down - d->m_birdEyeView->moveZoomRectTo(mapToScene(viewport()->rect()).boundingRect().center(), false); - } + Q_D(DotGraphView); + QGraphicsView::scrollContentsBy(dx, dy); + if (d->m_birdEyeView && scene()) { // we might be shutting down + d->m_birdEyeView->moveZoomRectTo(mapToScene(viewport()->rect()).boundingRect().center(), false); + } } -void DotGraphView::resizeEvent(QResizeEvent* e) +void DotGraphView::resizeEvent(QResizeEvent *e) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << "resizeEvent"; - QGraphicsView::resizeEvent(e); - if (d->m_canvas) d->updateSizes(e->size()); -// std::cerr << "resizeEvent end" << std::endl; + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << "resizeEvent"; + QGraphicsView::resizeEvent(e); + if (d->m_canvas) + d->updateSizes(e->size()); + // std::cerr << "resizeEvent end" << std::endl; } void DotGraphView::zoomRectMovedTo(QPointF newZoomPos) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::zoomRectMovedTo " << newZoomPos; - centerOn(newZoomPos); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::zoomRectMovedTo " << newZoomPos; + centerOn(newZoomPos); } - + void DotGraphView::zoomRectMoveFinished() { - Q_D(DotGraphView); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "zoomRectMoveFinished"; - d->updateBirdEyeView(); -// std::cerr << "zoomRectMoveFinished end" << std::endl; + Q_D(DotGraphView); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "zoomRectMoveFinished"; + d->updateBirdEyeView(); + // std::cerr << "zoomRectMoveFinished end" << std::endl; } -void DotGraphView::mousePressEvent(QMouseEvent* e) +void DotGraphView::mousePressEvent(QMouseEvent *e) { - Q_D(DotGraphView); - if (e->button() != Qt::LeftButton) { - return; - } - qCDebug(KGRAPHVIEWERLIB_LOG) << e << d->m_editingMode; - QGraphicsView::mousePressEvent(e); - - if (d->m_editingMode == AddNewElement) - { - double scale = d->detailAdjustedScale(); - - qreal gh = d->m_graph->height(); - - - QPointF pos = mapToScene( - e->pos().x()-d->m_defaultNewElementPixmap.width()/2, - e->pos().y()-d->m_defaultNewElementPixmap.height()/2); - GraphNode* newNode = new GraphNode(); - newNode->attributes() = d->m_newElementAttributes; - if (newNode->attributes().find("id") == newNode->attributes().end()) - { - newNode->setId(QString("NewNode%1").arg(d->m_graph->nodes().size())); - } - if (newNode->attributes().find("label") == newNode->attributes().end()) - { - newNode->setLabel(newNode->id()); + Q_D(DotGraphView); + if (e->button() != Qt::LeftButton) { + return; } - d->m_graph->nodes().insert(newNode->id(), newNode); - CanvasNode* newCNode = new CanvasNode(this, newNode, d->m_canvas); - newCNode->initialize(scale, scale, d->m_xMargin, d->m_yMargin, gh); - newNode->setCanvasNode(newCNode); - scene()->addItem(newCNode); - qCDebug(KGRAPHVIEWERLIB_LOG) << "setting pos to " << pos; - newCNode->setPos(pos); - newCNode->setZValue(100); - newCNode->show(); + qCDebug(KGRAPHVIEWERLIB_LOG) << e << d->m_editingMode; + QGraphicsView::mousePressEvent(e); + if (d->m_editingMode == AddNewElement) { + double scale = d->detailAdjustedScale(); - d->m_editingMode = None; - unsetCursor(); - emit newNodeAdded(newNode->id()); - } - else if (d->m_editingMode == SelectingElements) - { - } - else - { - if (d->m_editingMode != None && itemAt(e->pos()) == nullptr) // click outside any item: unselect all - { - if (d->m_editingMode == DrawNewEdge) // was drawing an edge; cancel it - { - if (d->m_newEdgeDraft) - { - d->m_newEdgeDraft->hide(); - scene()->removeItem(d->m_newEdgeDraft); - delete d->m_newEdgeDraft; - d->m_newEdgeDraft = nullptr; - } - d->m_newEdgeSource = nullptr; - d->m_editingMode = None; - } - else if (d->m_editingMode == AddNewEdge) - { - d->m_editingMode = None; - } - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->isSelected()) { - e->setSelected(false); - e->canvasEdge()->update(); + qreal gh = d->m_graph->height(); + + QPointF pos = mapToScene(e->pos().x() - d->m_defaultNewElementPixmap.width() / 2, e->pos().y() - d->m_defaultNewElementPixmap.height() / 2); + GraphNode *newNode = new GraphNode(); + newNode->attributes() = d->m_newElementAttributes; + if (newNode->attributes().find("id") == newNode->attributes().end()) { + newNode->setId(QString("NewNode%1").arg(d->m_graph->nodes().size())); } - } - foreach(GraphNode* n, d->m_graph->nodes()) - { - if (n->isSelected()) { - n->setSelected(false); - n->canvasElement()->update(); + if (newNode->attributes().find("label") == newNode->attributes().end()) { + newNode->setLabel(newNode->id()); } - } - foreach(GraphSubgraph* s, d->m_graph->subgraphs()) - { - if (s->isSelected()) { - s->setSelected(false); - s->canvasElement()->update(); + d->m_graph->nodes().insert(newNode->id(), newNode); + CanvasNode *newCNode = new CanvasNode(this, newNode, d->m_canvas); + newCNode->initialize(scale, scale, d->m_xMargin, d->m_yMargin, gh); + newNode->setCanvasNode(newCNode); + scene()->addItem(newCNode); + qCDebug(KGRAPHVIEWERLIB_LOG) << "setting pos to " << pos; + newCNode->setPos(pos); + newCNode->setZValue(100); + newCNode->show(); + + d->m_editingMode = None; + unsetCursor(); + emit newNodeAdded(newNode->id()); + } else if (d->m_editingMode == SelectingElements) { + } else { + if (d->m_editingMode != None && itemAt(e->pos()) == nullptr) // click outside any item: unselect all + { + if (d->m_editingMode == DrawNewEdge) // was drawing an edge; cancel it + { + if (d->m_newEdgeDraft) { + d->m_newEdgeDraft->hide(); + scene()->removeItem(d->m_newEdgeDraft); + delete d->m_newEdgeDraft; + d->m_newEdgeDraft = nullptr; + } + d->m_newEdgeSource = nullptr; + d->m_editingMode = None; + } else if (d->m_editingMode == AddNewEdge) { + d->m_editingMode = None; + } + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->isSelected()) { + e->setSelected(false); + e->canvasEdge()->update(); + } + } + foreach (GraphNode *n, d->m_graph->nodes()) { + if (n->isSelected()) { + n->setSelected(false); + n->canvasElement()->update(); + } + } + foreach (GraphSubgraph *s, d->m_graph->subgraphs()) { + if (s->isSelected()) { + s->setSelected(false); + s->canvasElement()->update(); + } + } + emit selectionIs(QList(), QPoint()); } - } - emit selectionIs(QList(),QPoint()); + d->m_pressPos = e->globalPos(); + d->m_pressScrollBarsPos = QPoint(horizontalScrollBar()->value(), verticalScrollBar()->value()); } - d->m_pressPos = e->globalPos(); - d->m_pressScrollBarsPos = QPoint(horizontalScrollBar()->value(), verticalScrollBar()->value()); - } - d->m_isMoving = true; + d->m_isMoving = true; } -void DotGraphView::mouseMoveEvent(QMouseEvent* e) +void DotGraphView::mouseMoveEvent(QMouseEvent *e) { - Q_D(DotGraphView); - QGraphicsView::mouseMoveEvent(e); -// qCDebug(KGRAPHVIEWERLIB_LOG) << scene()->selectedItems().size(); + Q_D(DotGraphView); + QGraphicsView::mouseMoveEvent(e); + // qCDebug(KGRAPHVIEWERLIB_LOG) << scene()->selectedItems().size(); - if (d->m_editingMode == DrawNewEdge) - { - if (d->m_newEdgeDraft) - { - QPointF src = d->m_newEdgeDraft->line().p1(); - QPointF tgt = mapToScene(e->pos()); - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting new edge draft line to" << QLineF(src,tgt); - d->m_newEdgeDraft->setLine(QLineF(src,tgt)); - } - } - else if (d->m_editingMode == SelectingElements) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "selecting"; - } - else if (e->buttons().testFlag(Qt::LeftButton)) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << (e->globalPos() - d->m_pressPos); - QPoint diff = e->globalPos() - d->m_pressPos; - horizontalScrollBar()->setValue(d->m_pressScrollBarsPos.x()-diff.x()); - verticalScrollBar()->setValue(d->m_pressScrollBarsPos.y()-diff.y()); - } -} - -void DotGraphView::mouseReleaseEvent(QMouseEvent* e) -{ - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << e << d->m_editingMode; -// qCDebug(KGRAPHVIEWERLIB_LOG) << "setDragMode(NoDrag)"; -// setDragMode(NoDrag); - if (d->m_editingMode == AddNewElement) - { - d->m_editingMode = None; - unsetCursor(); - } - else if (d->m_editingMode == SelectingElements) - { - QGraphicsView::mouseReleaseEvent(e); - qCDebug(KGRAPHVIEWERLIB_LOG) << "Stopping selection" << scene() << d->m_canvas; - QList items = scene()->selectedItems(); - QList selection; - foreach (QGraphicsItem * item, items) - { - CanvasElement* element = dynamic_cast(item); - element->element()->setSelected(true); - if (element) - { - selection.push_back(element->element()->id()); - } + if (d->m_editingMode == DrawNewEdge) { + if (d->m_newEdgeDraft) { + QPointF src = d->m_newEdgeDraft->line().p1(); + QPointF tgt = mapToScene(e->pos()); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Setting new edge draft line to" << QLineF(src,tgt); + d->m_newEdgeDraft->setLine(QLineF(src, tgt)); + } + } else if (d->m_editingMode == SelectingElements) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "selecting"; + } else if (e->buttons().testFlag(Qt::LeftButton)) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << (e->globalPos() - d->m_pressPos); + QPoint diff = e->globalPos() - d->m_pressPos; + horizontalScrollBar()->setValue(d->m_pressScrollBarsPos.x() - diff.x()); + verticalScrollBar()->setValue(d->m_pressScrollBarsPos.y() - diff.y()); } - d->m_editingMode = None; - unsetCursor(); - setDragMode(NoDrag); - if (!selection.isEmpty()) - { - update(); - emit selectionIs(selection, mapToGlobal( e->pos() )); +} + +void DotGraphView::mouseReleaseEvent(QMouseEvent *e) +{ + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << e << d->m_editingMode; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "setDragMode(NoDrag)"; + // setDragMode(NoDrag); + if (d->m_editingMode == AddNewElement) { + d->m_editingMode = None; + unsetCursor(); + } else if (d->m_editingMode == SelectingElements) { + QGraphicsView::mouseReleaseEvent(e); + qCDebug(KGRAPHVIEWERLIB_LOG) << "Stopping selection" << scene() << d->m_canvas; + QList items = scene()->selectedItems(); + QList selection; + foreach (QGraphicsItem *item, items) { + CanvasElement *element = dynamic_cast(item); + element->element()->setSelected(true); + if (element) { + selection.push_back(element->element()->id()); + } + } + d->m_editingMode = None; + unsetCursor(); + setDragMode(NoDrag); + if (!selection.isEmpty()) { + update(); + emit selectionIs(selection, mapToGlobal(e->pos())); + } + } else { + QGraphicsView::mouseReleaseEvent(e); } - } - else - { - QGraphicsView::mouseReleaseEvent(e); - } - d->m_isMoving = false; + d->m_isMoving = false; } -void DotGraphView::mouseDoubleClickEvent(QMouseEvent* e) +void DotGraphView::mouseDoubleClickEvent(QMouseEvent *e) { - QGraphicsView::mouseDoubleClickEvent(e); + QGraphicsView::mouseDoubleClickEvent(e); } -void DotGraphView::contextMenuEvent(QContextMenuEvent* e) +void DotGraphView::contextMenuEvent(QContextMenuEvent *e) { - Q_D(DotGraphView); -// QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + Q_D(DotGraphView); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - d->m_popup->exec(e->globalPos()); + d->m_popup->exec(e->globalPos()); } -void DotGraphView::slotContextMenuEvent(const QString& id, const QPoint& p) +void DotGraphView::slotContextMenuEvent(const QString &id, const QPoint &p) { -// QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - emit (contextMenuEvent(id, p)); + emit(contextMenuEvent(id, p)); } -void DotGraphView::slotElementHoverEnter(CanvasElement* element) +void DotGraphView::slotElementHoverEnter(CanvasElement *element) { - qCDebug(KGRAPHVIEWERLIB_LOG) << element->element()->id(); - // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - - emit (hoverEnter(element->element()->id())); + qCDebug(KGRAPHVIEWERLIB_LOG) << element->element()->id(); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + + emit(hoverEnter(element->element()->id())); } -void DotGraphView::slotElementHoverLeave(CanvasElement* element) +void DotGraphView::slotElementHoverLeave(CanvasElement *element) { - qCDebug(KGRAPHVIEWERLIB_LOG) << element->element()->id(); - // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - - emit (hoverLeave(element->element()->id())); + qCDebug(KGRAPHVIEWERLIB_LOG) << element->element()->id(); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + + emit(hoverLeave(element->element()->id())); } -void DotGraphView::slotElementHoverEnter(CanvasEdge* element) +void DotGraphView::slotElementHoverEnter(CanvasEdge *element) { - qCDebug(KGRAPHVIEWERLIB_LOG) << element->edge()->id(); - // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - - emit (hoverEnter(element->edge()->id())); + qCDebug(KGRAPHVIEWERLIB_LOG) << element->edge()->id(); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + + emit(hoverEnter(element->edge()->id())); } -void DotGraphView::slotElementHoverLeave(CanvasEdge* element) +void DotGraphView::slotElementHoverLeave(CanvasEdge *element) { - qCDebug(KGRAPHVIEWERLIB_LOG) << element->edge()->id(); - // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); - - emit (hoverLeave(element->edge()->id())); + qCDebug(KGRAPHVIEWERLIB_LOG) << element->edge()->id(); + // QList l = scene()->collidingItems(scene()->itemAt(e->pos())); + + emit(hoverLeave(element->edge()->id())); } -void DotGraphView::setLayoutCommand(const QString& command) +void DotGraphView::setLayoutCommand(const QString &command) { - Q_D(DotGraphView); - d->m_graph->layoutCommand(command); - reload(); + Q_D(DotGraphView); + d->m_graph->layoutCommand(command); + reload(); } -KGraphViewerInterface::PannerPosition DotGraphView::zoomPos(const QString& s) +KGraphViewerInterface::PannerPosition DotGraphView::zoomPos(const QString &s) { - KGraphViewerInterface::PannerPosition res = DEFAULT_ZOOMPOS; - if (s == QString("KGraphViewerInterface::TopLeft")) res = KGraphViewerInterface::TopLeft; - if (s == QString("KGraphViewerInterface::TopRight")) res = KGraphViewerInterface::TopRight; - if (s == QString("KGraphViewerInterface::BottomLeft")) res = KGraphViewerInterface::BottomLeft; - if (s == QString("KGraphViewerInterface::BottomRight")) res = KGraphViewerInterface::BottomRight; - if (s == QString("Automatic")) res = KGraphViewerInterface::Auto; + KGraphViewerInterface::PannerPosition res = DEFAULT_ZOOMPOS; + if (s == QString("KGraphViewerInterface::TopLeft")) + res = KGraphViewerInterface::TopLeft; + if (s == QString("KGraphViewerInterface::TopRight")) + res = KGraphViewerInterface::TopRight; + if (s == QString("KGraphViewerInterface::BottomLeft")) + res = KGraphViewerInterface::BottomLeft; + if (s == QString("KGraphViewerInterface::BottomRight")) + res = KGraphViewerInterface::BottomRight; + if (s == QString("Automatic")) + res = KGraphViewerInterface::Auto; - return res; + return res; } void DotGraphView::setPannerEnabled(bool enabled) { - Q_UNUSED(enabled); - Q_D(DotGraphView); - d->m_bevPopup->setEnabled(d->m_bevEnabledAction->isChecked()); - KGraphViewerPartSettings::setBirdsEyeViewEnabled(d->m_bevEnabledAction->isChecked()); - KGraphViewerPartSettings::self()->save(); - d->updateSizes(); + Q_UNUSED(enabled); + Q_D(DotGraphView); + d->m_bevPopup->setEnabled(d->m_bevEnabledAction->isChecked()); + KGraphViewerPartSettings::setBirdsEyeViewEnabled(d->m_bevEnabledAction->isChecked()); + KGraphViewerPartSettings::self()->save(); + d->updateSizes(); } void DotGraphView::viewBevActivated(int newZoomPos) { - Q_D(DotGraphView); - d->m_zoomPosition = (KGraphViewerInterface::PannerPosition)newZoomPos; - d->updateSizes(); - emit(sigViewBevActivated(newZoomPos)); + Q_D(DotGraphView); + d->m_zoomPosition = (KGraphViewerInterface::PannerPosition)newZoomPos; + d->updateSizes(); + emit(sigViewBevActivated(newZoomPos)); } QString DotGraphView::zoomPosString(KGraphViewerInterface::PannerPosition p) { - if (p == KGraphViewerInterface::TopRight) return QString("KGraphViewerInterface::TopRight"); - if (p == KGraphViewerInterface::BottomLeft) return QString("KGraphViewerInterface::BottomLeft"); - if (p == KGraphViewerInterface::BottomRight) return QString("KGraphViewerInterface::BottomRight"); - if (p == KGraphViewerInterface::Auto) return QString("Automatic"); + if (p == KGraphViewerInterface::TopRight) + return QString("KGraphViewerInterface::TopRight"); + if (p == KGraphViewerInterface::BottomLeft) + return QString("KGraphViewerInterface::BottomLeft"); + if (p == KGraphViewerInterface::BottomRight) + return QString("KGraphViewerInterface::BottomRight"); + if (p == KGraphViewerInterface::Auto) + return QString("Automatic"); return QString("KGraphViewerInterface::TopLeft"); } void DotGraphView::readViewConfig() { - Q_D(DotGraphView); - KConfigGroup g(KSharedConfig::openConfig(), "GraphViewLayout"); - - QVariant dl = DEFAULT_DETAILLEVEL; - d->m_detailLevel = g.readEntry("DetailLevel", dl).toInt(); - d->m_zoomPosition = zoomPos(g.readEntry("KGraphViewerInterface::PannerPosition", - zoomPosString(DEFAULT_ZOOMPOS))); - emit(sigViewBevActivated(d->m_zoomPosition)); + Q_D(DotGraphView); + KConfigGroup g(KSharedConfig::openConfig(), "GraphViewLayout"); + + QVariant dl = DEFAULT_DETAILLEVEL; + d->m_detailLevel = g.readEntry("DetailLevel", dl).toInt(); + d->m_zoomPosition = zoomPos(g.readEntry("KGraphViewerInterface::PannerPosition", zoomPosString(DEFAULT_ZOOMPOS))); + emit(sigViewBevActivated(d->m_zoomPosition)); } void DotGraphView::saveViewConfig() { - Q_D(DotGraphView); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "Saving view config"; - KConfigGroup g(KSharedConfig::openConfig(), "GraphViewLayout"); + Q_D(DotGraphView); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Saving view config"; + KConfigGroup g(KSharedConfig::openConfig(), "GraphViewLayout"); writeConfigEntry(&g, "DetailLevel", d->m_detailLevel, DEFAULT_DETAILLEVEL); - writeConfigEntry(&g, "KGraphViewerInterface::PannerPosition", - zoomPosString(d->m_zoomPosition), - zoomPosString(DEFAULT_ZOOMPOS).toUtf8().data()); - g.sync(); + writeConfigEntry(&g, "KGraphViewerInterface::PannerPosition", zoomPosString(d->m_zoomPosition), zoomPosString(DEFAULT_ZOOMPOS).toUtf8().data()); + g.sync(); } void DotGraphView::pageSetup() { - Q_D(DotGraphView); - if (d->m_printCommand == nullptr) - { - d->m_printCommand = new KGVSimplePrintingCommand(this, 0); - } - d->m_printCommand->showPageSetup(d->m_graph->dotFileName()); - return; + Q_D(DotGraphView); + if (d->m_printCommand == nullptr) { + d->m_printCommand = new KGVSimplePrintingCommand(this, 0); + } + d->m_printCommand->showPageSetup(d->m_graph->dotFileName()); + return; } void DotGraphView::print() { - Q_D(DotGraphView); - if (d->m_printCommand == nullptr) - { - d->m_printCommand = new KGVSimplePrintingCommand(this, 0); - } - d->m_printCommand->print(d->m_graph->dotFileName()); - return; + Q_D(DotGraphView); + if (d->m_printCommand == nullptr) { + d->m_printCommand = new KGVSimplePrintingCommand(this, 0); + } + d->m_printCommand->print(d->m_graph->dotFileName()); + return; } void DotGraphView::printPreview() { - Q_D(DotGraphView); - if (d->m_printCommand == nullptr) - { - d->m_printCommand = new KGVSimplePrintingCommand(this, 0); - } - d->m_printCommand->showPrintPreview(d->m_graph->dotFileName(), false); - return; + Q_D(DotGraphView); + if (d->m_printCommand == nullptr) { + d->m_printCommand = new KGVSimplePrintingCommand(this, 0); + } + d->m_printCommand->showPrintPreview(d->m_graph->dotFileName(), false); + return; } bool DotGraphView::reload() { - Q_D(DotGraphView); - QString fileName = d->m_graph->dotFileName(); - if (d->m_graph->useLibrary()) - return loadLibrary(fileName); - else - return loadDot(fileName); + Q_D(DotGraphView); + QString fileName = d->m_graph->dotFileName(); + if (d->m_graph->useLibrary()) + return loadLibrary(fileName); + else + return loadDot(fileName); } -void DotGraphView::dirty(const QString& dotFileName) +void DotGraphView::dirty(const QString &dotFileName) { - Q_D(DotGraphView); -// std::cerr << "SLOT dirty for " << dotFileName << std::endl; - if (dotFileName == d->m_graph->dotFileName()) - { - if (QMessageBox::question(this, - i18n("Reload Confirmation"), - i18n("The file %1 has been modified on disk.\nDo you want to reload it?",dotFileName)) == QMessageBox::Yes) - { - if (d->m_graph->useLibrary()) - loadLibrary(dotFileName); - else - loadDot(dotFileName); + Q_D(DotGraphView); + // std::cerr << "SLOT dirty for " << dotFileName << std::endl; + if (dotFileName == d->m_graph->dotFileName()) { + if (QMessageBox::question(this, i18n("Reload Confirmation"), i18n("The file %1 has been modified on disk.\nDo you want to reload it?", dotFileName)) == QMessageBox::Yes) { + if (d->m_graph->useLibrary()) + loadLibrary(dotFileName); + else + loadDot(dotFileName); + } } - } } -KConfigGroup* DotGraphView::configGroup(KConfig* c, - const QString& group, const QString& post) +KConfigGroup *DotGraphView::configGroup(KConfig *c, const QString &group, const QString &post) { - QStringList gList = c->groupList(); - QString res = group; - if (gList.contains(group+post)) res += post; - return new KConfigGroup(c, res); + QStringList gList = c->groupList(); + QString res = group; + if (gList.contains(group + post)) + res += post; + return new KConfigGroup(c, res); } -void DotGraphView::writeConfigEntry(KConfigGroup* c, const char* pKey, - const QString& value, const char* def) +void DotGraphView::writeConfigEntry(KConfigGroup *c, const char *pKey, const QString &value, const char *def) { - if (!c) return; - if ((value.isEmpty() && ((def == nullptr) || (*def == 0))) || - (value == QString(def))) - c->deleteEntry(pKey); - else - c->writeEntry(pKey, value); + if (!c) + return; + if ((value.isEmpty() && ((def == nullptr) || (*def == 0))) || (value == QString(def))) + c->deleteEntry(pKey); + else + c->writeEntry(pKey, value); } -void DotGraphView::writeConfigEntry(KConfigGroup* c, const char* pKey, - int value, int def) +void DotGraphView::writeConfigEntry(KConfigGroup *c, const char *pKey, int value, int def) { - if (!c) return; - if (value == def) - c->deleteEntry(pKey); - else - c->writeEntry(pKey, value); + if (!c) + return; + if (value == def) + c->deleteEntry(pKey); + else + c->writeEntry(pKey, value); } -void DotGraphView::writeConfigEntry(KConfigGroup* c, const char* pKey, - double value, double def) +void DotGraphView::writeConfigEntry(KConfigGroup *c, const char *pKey, double value, double def) { - if (!c) return; - if (value == def) - c->deleteEntry(pKey); - else - c->writeEntry(pKey, value); + if (!c) + return; + if (value == def) + c->deleteEntry(pKey); + else + c->writeEntry(pKey, value); } -void DotGraphView::writeConfigEntry(KConfigGroup* c, const char* pKey, - bool value, bool def) +void DotGraphView::writeConfigEntry(KConfigGroup *c, const char *pKey, bool value, bool def) { - if (!c) return; - if (value == def) - c->deleteEntry(pKey); - else - c->writeEntry(pKey, value); + if (!c) + return; + if (value == def) + c->deleteEntry(pKey); + else + c->writeEntry(pKey, value); } -const QString& DotGraphView::dotFileName() +const QString &DotGraphView::dotFileName() { - Q_D(DotGraphView); - return d->m_graph->dotFileName(); + Q_D(DotGraphView); + return d->m_graph->dotFileName(); } void DotGraphView::hideToolsWindows() { - Q_D(DotGraphView); - if (d->m_printCommand) - { - d->m_printCommand->hidePageSetup(); - d->m_printCommand->hidePrintPreview(); - } + Q_D(DotGraphView); + if (d->m_printCommand) { + d->m_printCommand->hidePageSetup(); + d->m_printCommand->hidePrintPreview(); + } } void DotGraphView::slotExportImage() { - Q_D(DotGraphView); - d->exportToImage(); + Q_D(DotGraphView); + d->exportToImage(); } void DotGraphView::slotLayoutSpecify() { - { - Q_D(DotGraphView); - bool ok = false; - QString currentLayoutCommand = d->m_graph->layoutCommand(); - QString layoutCommand = - QInputDialog::getText( - this, - i18n("Layout Command"), - i18n("Specify here the command that will be used to layout the graph.\n" - "The command MUST write its results on stdout in xdot format."), - QLineEdit::Normal, - currentLayoutCommand, - &ok, - nullptr); - // std::cerr << "Got layout command: " << layoutCommand << std::endl; - if (ok && layoutCommand != currentLayoutCommand) { - // std::cerr << "Setting new layout command: " << layoutCommand << std::endl; - if (!d->m_layoutAlgoSelectAction->setCurrentAction(layoutCommand, Qt::CaseInsensitive)) - { - QAction *new_action = d->m_layoutAlgoSelectAction->addAction(layoutCommand); - d->m_layoutAlgoSelectAction->setCurrentAction(new_action); - slotSelectLayoutAlgo(layoutCommand); - } + Q_D(DotGraphView); + bool ok = false; + QString currentLayoutCommand = d->m_graph->layoutCommand(); + QString layoutCommand = QInputDialog::getText(this, + i18n("Layout Command"), + i18n("Specify here the command that will be used to layout the graph.\n" + "The command MUST write its results on stdout in xdot format."), + QLineEdit::Normal, + currentLayoutCommand, + &ok, + nullptr); + // std::cerr << "Got layout command: " << layoutCommand << std::endl; + if (ok && layoutCommand != currentLayoutCommand) { + // std::cerr << "Setting new layout command: " << layoutCommand << std::endl; + if (!d->m_layoutAlgoSelectAction->setCurrentAction(layoutCommand, Qt::CaseInsensitive)) { + QAction *new_action = d->m_layoutAlgoSelectAction->addAction(layoutCommand); + d->m_layoutAlgoSelectAction->setCurrentAction(new_action); + slotSelectLayoutAlgo(layoutCommand); + } + } } - } } void DotGraphView::slotLayoutReset() { - Q_D(DotGraphView); - d->m_layoutAlgoSelectAction->setCurrentAction("Dot"); - slotSelectLayoutAlgo("Dot"); -} - -void DotGraphView::slotSelectLayoutAlgo(const QString& ttext) -{ - QString text = ttext;//.mid(1); - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutAlgo '" << text << "'"; - if (text == "Dot") - { - setLayoutCommand("dot"); - } - else if (text == "Neato") - { - setLayoutCommand("neato"); - } - else if (text == "Twopi") - { - setLayoutCommand("twopi"); - } - else if (text == "Fdp") - { - setLayoutCommand("fdp"); - } - else if (text == "Circo") - { - setLayoutCommand("circo"); - } - else - { - setLayoutCommand(text); - } + Q_D(DotGraphView); + d->m_layoutAlgoSelectAction->setCurrentAction("Dot"); + slotSelectLayoutAlgo("Dot"); +} + +void DotGraphView::slotSelectLayoutAlgo(const QString &ttext) +{ + QString text = ttext; //.mid(1); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutAlgo '" << text << "'"; + if (text == "Dot") { + setLayoutCommand("dot"); + } else if (text == "Neato") { + setLayoutCommand("neato"); + } else if (text == "Twopi") { + setLayoutCommand("twopi"); + } else if (text == "Fdp") { + setLayoutCommand("fdp"); + } else if (text == "Circo") { + setLayoutCommand("circo"); + } else { + setLayoutCommand(text); + } } void DotGraphView::slotSelectLayoutDot() { - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutDot"; - setLayoutCommand("dot -Txdot"); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutDot"; + setLayoutCommand("dot -Txdot"); } void DotGraphView::slotSelectLayoutNeato() { - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutNeato"; - setLayoutCommand("neato -Txdot"); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutNeato"; + setLayoutCommand("neato -Txdot"); } void DotGraphView::slotSelectLayoutTwopi() { - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutTwopi"; - setLayoutCommand("twopi -Txdot"); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutTwopi"; + setLayoutCommand("twopi -Txdot"); } void DotGraphView::slotSelectLayoutFdp() { - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutFdp"; - setLayoutCommand("fdp -Txdot"); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutFdp"; + setLayoutCommand("fdp -Txdot"); } void DotGraphView::slotSelectLayoutCirco() { - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutCirco"; - setLayoutCommand("circo -Txdot"); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotSelectLayoutCirco"; + setLayoutCommand("circo -Txdot"); } void DotGraphView::slotBevToggled() { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotBevToggled"; - qCDebug(KGRAPHVIEWERLIB_LOG) << " d->m_bevEnabledAction is checked ? " << d->m_bevEnabledAction->isChecked(); - setPannerEnabled(d->m_bevEnabledAction->isChecked()); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << "DotGraphView::slotBevToggled"; + qCDebug(KGRAPHVIEWERLIB_LOG) << " d->m_bevEnabledAction is checked ? " << d->m_bevEnabledAction->isChecked(); + setPannerEnabled(d->m_bevEnabledAction->isChecked()); } void DotGraphView::slotBevTopLeft() { - viewBevActivated(KGraphViewerInterface::TopLeft); + viewBevActivated(KGraphViewerInterface::TopLeft); } void DotGraphView::slotBevTopRight() { - viewBevActivated(KGraphViewerInterface::TopRight); + viewBevActivated(KGraphViewerInterface::TopRight); } void DotGraphView::slotBevBottomLeft() { - viewBevActivated(KGraphViewerInterface::BottomLeft); + viewBevActivated(KGraphViewerInterface::BottomLeft); } void DotGraphView::slotBevBottomRight() { - viewBevActivated(KGraphViewerInterface::BottomRight); + viewBevActivated(KGraphViewerInterface::BottomRight); } void DotGraphView::slotBevAutomatic() { - viewBevActivated(KGraphViewerInterface::Auto); + viewBevActivated(KGraphViewerInterface::Auto); } void DotGraphView::slotUpdate() { - Q_D(DotGraphView); - d->m_graph->update(); - d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); + Q_D(DotGraphView); + d->m_graph->update(); + d->m_layoutAlgoSelectAction->setCurrentAction(d->m_graph->layoutCommand(), Qt::CaseInsensitive); } -void DotGraphView::prepareAddNewElement(QMap attribs) +void DotGraphView::prepareAddNewElement(QMap attribs) { - Q_D(DotGraphView); - d->m_editingMode = AddNewElement; - d->m_newElementAttributes = attribs; - unsetCursor(); - setCursor(QCursor(d->m_defaultNewElementPixmap)); + Q_D(DotGraphView); + d->m_editingMode = AddNewElement; + d->m_newElementAttributes = attribs; + unsetCursor(); + setCursor(QCursor(d->m_defaultNewElementPixmap)); } -void DotGraphView::prepareAddNewEdge(QMap attribs) +void DotGraphView::prepareAddNewEdge(QMap attribs) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; - bool anySelected = false; - foreach (GraphEdge* edge, d->m_graph->edges()) - { - if (edge->isSelected()) - { - anySelected = true; - QMap::const_iterator it = attribs.constBegin(); - for(; it != attribs.constEnd(); it++) - { - edge->attributes()[it.key()] = it.value(); - } - } - } - if (anySelected) - { - return; - } - d->m_editingMode = AddNewEdge; - d->m_newElementAttributes = attribs; - unsetCursor(); - QBitmap bm(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newedge.png")); - setCursor(QCursor(bm,bm,32,16)); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << attribs; + bool anySelected = false; + foreach (GraphEdge *edge, d->m_graph->edges()) { + if (edge->isSelected()) { + anySelected = true; + QMap::const_iterator it = attribs.constBegin(); + for (; it != attribs.constEnd(); it++) { + edge->attributes()[it.key()] = it.value(); + } + } + } + if (anySelected) { + return; + } + d->m_editingMode = AddNewEdge; + d->m_newElementAttributes = attribs; + unsetCursor(); + QBitmap bm(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/kgraphviewer-newedge.png")); + setCursor(QCursor(bm, bm, 32, 16)); } void DotGraphView::prepareSelectElements() { - Q_D(DotGraphView); - d->m_editingMode = SelectingElements; - setCursor(Qt::CrossCursor); - setDragMode ( RubberBandDrag ); + Q_D(DotGraphView); + d->m_editingMode = SelectingElements; + setCursor(Qt::CrossCursor); + setDragMode(RubberBandDrag); } -void DotGraphView::createNewEdgeDraftFrom(CanvasElement* node) +void DotGraphView::createNewEdgeDraftFrom(CanvasElement *node) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << node->element()->id(); - d->m_editingMode = DrawNewEdge; - unsetCursor(); - d->m_newEdgeSource = node; - - if (d->m_newEdgeDraft) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "removing new edge draft"; - d->m_newEdgeDraft->hide(); - scene()->removeItem(d->m_newEdgeDraft); - delete d->m_newEdgeDraft; - d->m_newEdgeDraft = nullptr; - } - d->m_newEdgeDraft = new QGraphicsLineItem(QLineF(node->boundingRect().center()+node->pos(),node->boundingRect().center()+node->pos()+QPointF(10,10))); - scene()->addItem(d->m_newEdgeDraft); - d->m_newEdgeDraft->setZValue(1000); - d->m_newEdgeDraft->show(); - qCDebug(KGRAPHVIEWERLIB_LOG) << d->m_newEdgeDraft->line(); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << node->element()->id(); + d->m_editingMode = DrawNewEdge; + unsetCursor(); + d->m_newEdgeSource = node; + + if (d->m_newEdgeDraft) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "removing new edge draft"; + d->m_newEdgeDraft->hide(); + scene()->removeItem(d->m_newEdgeDraft); + delete d->m_newEdgeDraft; + d->m_newEdgeDraft = nullptr; + } + d->m_newEdgeDraft = new QGraphicsLineItem(QLineF(node->boundingRect().center() + node->pos(), node->boundingRect().center() + node->pos() + QPointF(10, 10))); + scene()->addItem(d->m_newEdgeDraft); + d->m_newEdgeDraft->setZValue(1000); + d->m_newEdgeDraft->show(); + qCDebug(KGRAPHVIEWERLIB_LOG) << d->m_newEdgeDraft->line(); } -void DotGraphView::finishNewEdgeTo(CanvasElement* node) +void DotGraphView::finishNewEdgeTo(CanvasElement *node) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << node->element()->id(); - d->m_editingMode = None; - unsetCursor(); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << node->element()->id(); + d->m_editingMode = None; + unsetCursor(); - if (d->m_newEdgeDraft) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "removing new edge draft"; - d->m_newEdgeDraft->hide(); - scene()->removeItem(d->m_newEdgeDraft); - delete d->m_newEdgeDraft; - d->m_newEdgeDraft = nullptr; - } + if (d->m_newEdgeDraft) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "removing new edge draft"; + d->m_newEdgeDraft->hide(); + scene()->removeItem(d->m_newEdgeDraft); + delete d->m_newEdgeDraft; + d->m_newEdgeDraft = nullptr; + } - emit newEdgeFinished(d->m_newEdgeSource->element()->id(),node->element()->id(),d->m_newElementAttributes); + emit newEdgeFinished(d->m_newEdgeSource->element()->id(), node->element()->id(), d->m_newElementAttributes); - d->m_newEdgeSource = nullptr; + d->m_newEdgeSource = nullptr; } // void DotGraphView::slotFinishNewEdge( // const QString& srcId, // const QString& tgtId, // const QMap newElementAttributes) // { // qCDebug(KGRAPHVIEWERLIB_LOG) ; -// +// // GraphEdge* gedge = new GraphEdge(); // gedge->setFromNode(d->m_graph->nodes()[srcId]); // gedge->setToNode(d->m_graph->nodes()[tgtId]); @@ -1985,327 +1915,273 @@ // } // gedge->setId(srcId+tgtId+QString::number(d->m_graph->edges().size())); // d->m_graph->edges().insert(gedge->id(), gedge); -// +// // double scale = detailAdjustedScale(); -// +// // qreal gh = d->m_graph->height(); // CanvasEdge* cedge = new CanvasEdge(this, gedge, scale, scale, d->m_xMargin, // d->m_yMargin, gh, d->m_graph->wdhcf(), d->m_graph->hdvcf()); -// +// // gedge->setCanvasEdge(cedge); // // std::cerr << "setting z = " << gedge->z() << std::endl; // cedge->setZValue(gedge->z()); // cedge->show(); // scene()->addItem(cedge); -// +// // emit newEdgeAdded(gedge->fromNode()->id(),gedge->toNode()->id()); // } void DotGraphView::setReadOnly() { - Q_D(DotGraphView); - d-> m_readWrite = false; - if (d->m_graph) - { - d->m_graph->setReadOnly(); - } + Q_D(DotGraphView); + d->m_readWrite = false; + if (d->m_graph) { + d->m_graph->setReadOnly(); + } } void DotGraphView::setReadWrite() { - Q_D(DotGraphView); - d->m_readWrite = true; - if (d->m_graph) - { - d->m_graph->setReadWrite(); - } + Q_D(DotGraphView); + d->m_readWrite = true; + if (d->m_graph) { + d->m_graph->setReadWrite(); + } } -void DotGraphView::slotEdgeSelected(CanvasEdge* edge, Qt::KeyboardModifiers modifiers) +void DotGraphView::slotEdgeSelected(CanvasEdge *edge, Qt::KeyboardModifiers modifiers) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << edge->edge()->id(); - QList selection; - selection.push_back(edge->edge()->id()); - if (!modifiers.testFlag(Qt::ControlModifier)) - { - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->canvasEdge() != edge) - { - e->setSelected(false); - e->canvasEdge()->update(); - } - } - foreach(GraphNode* n, d->m_graph->nodes()) - { - n->setSelected(false); - n->canvasNode()->update(); - } - foreach(GraphSubgraph* s, d->m_graph->subgraphs()) - { - s->setElementSelected(nullptr, false, true); - } - } - else - { - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->canvasEdge() != edge) - { - if (e->isSelected()) - { - selection.push_back(e->id()); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << edge->edge()->id(); + QList selection; + selection.push_back(edge->edge()->id()); + if (!modifiers.testFlag(Qt::ControlModifier)) { + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->canvasEdge() != edge) { + e->setSelected(false); + e->canvasEdge()->update(); + } + } + foreach (GraphNode *n, d->m_graph->nodes()) { + n->setSelected(false); + n->canvasNode()->update(); + } + foreach (GraphSubgraph *s, d->m_graph->subgraphs()) { + s->setElementSelected(nullptr, false, true); + } + } else { + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->canvasEdge() != edge) { + if (e->isSelected()) { + selection.push_back(e->id()); + } + } + } + foreach (GraphNode *n, d->m_graph->nodes()) { + if (n->isSelected()) { + selection.push_back(n->id()); + } + } + foreach (GraphSubgraph *s, d->m_graph->subgraphs()) { + if (s->isSelected()) { + selection.push_back(s->id()); + } } - } - } - foreach(GraphNode* n, d->m_graph->nodes()) - { - if (n->isSelected()) - { - selection.push_back(n->id()); - } - } - foreach(GraphSubgraph* s, d->m_graph->subgraphs()) - { - if (s->isSelected()) - { - selection.push_back(s->id()); - } } - } - emit selectionIs(selection, QPoint()); + emit selectionIs(selection, QPoint()); } -void DotGraphView::slotElementSelected(CanvasElement* element, Qt::KeyboardModifiers modifiers) +void DotGraphView::slotElementSelected(CanvasElement *element, Qt::KeyboardModifiers modifiers) { - Q_D(DotGraphView); - QList selection; - selection.push_back(element->element()->id()); - if (!modifiers.testFlag(Qt::ControlModifier)) - { - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->isSelected()) { - e->setSelected(false); - e->canvasEdge()->update(); - } - } - foreach(GraphNode* e, d->m_graph->nodes()) - { - if (e->canvasElement() != element) - { - if (e->isSelected()) { - e->setSelected(false); - e->canvasElement()->update(); + Q_D(DotGraphView); + QList selection; + selection.push_back(element->element()->id()); + if (!modifiers.testFlag(Qt::ControlModifier)) { + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->isSelected()) { + e->setSelected(false); + e->canvasEdge()->update(); + } + } + foreach (GraphNode *e, d->m_graph->nodes()) { + if (e->canvasElement() != element) { + if (e->isSelected()) { + e->setSelected(false); + e->canvasElement()->update(); + } + } + } + foreach (GraphSubgraph *s, d->m_graph->subgraphs()) { + s->setElementSelected(element->element(), true, true); + } + } else { + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->isSelected()) { + selection.push_back(e->id()); + } + } + foreach (GraphNode *n, d->m_graph->nodes()) { + if (n->isSelected()) { + selection.push_back(n->id()); + } + } + foreach (GraphSubgraph *s, d->m_graph->subgraphs()) { + s->retrieveSelectedElementsIds(selection); } - } - } - foreach(GraphSubgraph* s, d->m_graph->subgraphs()) - { - s->setElementSelected(element->element(), true, true); - } - } - else - { - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->isSelected()) - { - selection.push_back(e->id()); - } - } - foreach(GraphNode* n, d->m_graph->nodes()) - { - if (n->isSelected()) - { - selection.push_back(n->id()); - } - } - foreach(GraphSubgraph* s, d->m_graph->subgraphs()) - { - s->retrieveSelectedElementsIds(selection); } - } - emit selectionIs(selection, QPoint()); + emit selectionIs(selection, QPoint()); } void DotGraphView::removeSelectedEdges() { - Q_D(DotGraphView); - foreach(GraphEdge* e, d->m_graph->edges()) - { - if (e->isSelected()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeEdge " << e->id(); - d->m_graph->removeEdge(e->id()); - emit removeEdge(e->id()); + Q_D(DotGraphView); + foreach (GraphEdge *e, d->m_graph->edges()) { + if (e->isSelected()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeEdge " << e->id(); + d->m_graph->removeEdge(e->id()); + emit removeEdge(e->id()); + } } - } } void DotGraphView::removeSelectedNodes() { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG); - foreach(GraphNode* e, d->m_graph->nodes()) - { - if (e->isSelected()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeElement " << e->id(); - d->m_graph->removeElement(e->id()); - emit removeElement(e->id()); + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG); + foreach (GraphNode *e, d->m_graph->nodes()) { + if (e->isSelected()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeElement " << e->id(); + d->m_graph->removeElement(e->id()); + emit removeElement(e->id()); + } } - } } void DotGraphView::removeSelectedSubgraphs() { - Q_D(DotGraphView); - foreach(GraphSubgraph* e, d->m_graph->subgraphs()) - { - if (e->isSelected()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeElement " << e->id(); - d->m_graph->removeElement(e->id()); - emit removeElement(e->id()); + Q_D(DotGraphView); + foreach (GraphSubgraph *e, d->m_graph->subgraphs()) { + if (e->isSelected()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "emiting removeElement " << e->id(); + d->m_graph->removeElement(e->id()); + emit removeElement(e->id()); + } } - } } void DotGraphView::removeSelectedElements() { - removeSelectedNodes(); - removeSelectedEdges(); - removeSelectedSubgraphs(); -} - -void DotGraphView::timerEvent ( QTimerEvent * event ) -{ - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << event->timerId(); - qreal vpercent = verticalScrollBar()->value()*1.0/100; - qreal hpercent = horizontalScrollBar()->value()*1.0/100; - if (d->m_scrollDirection == Left) - { - horizontalScrollBar()->setValue(horizontalScrollBar()->value()-(5*hpercent)); - } - else if (d->m_scrollDirection == Right) - { - horizontalScrollBar()->setValue(horizontalScrollBar()->value()+(5*hpercent)); - } - else if (d->m_scrollDirection == Top) - { - verticalScrollBar()->setValue(verticalScrollBar()->value()-(5*vpercent)); - } - else if (d->m_scrollDirection == Bottom) - { - verticalScrollBar()->setValue(verticalScrollBar()->value()+(5*vpercent)); - } -} - -void DotGraphView::leaveEvent ( QEvent * /*event*/ ) -{ - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG) << mapFromGlobal(QCursor::pos()); - if (d->m_editingMode == DrawNewEdge) - { - d->m_leavedTimer = startTimer(10); - if (mapFromGlobal(QCursor::pos()).x() <= 0) - { - d->m_scrollDirection = Left; - } - else if (mapFromGlobal(QCursor::pos()).y() <= 0) - { - d->m_scrollDirection = Top; - } - else if (mapFromGlobal(QCursor::pos()).x() >= width()) - { - d->m_scrollDirection = Right; + removeSelectedNodes(); + removeSelectedEdges(); + removeSelectedSubgraphs(); +} + +void DotGraphView::timerEvent(QTimerEvent *event) +{ + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << event->timerId(); + qreal vpercent = verticalScrollBar()->value() * 1.0 / 100; + qreal hpercent = horizontalScrollBar()->value() * 1.0 / 100; + if (d->m_scrollDirection == Left) { + horizontalScrollBar()->setValue(horizontalScrollBar()->value() - (5 * hpercent)); + } else if (d->m_scrollDirection == Right) { + horizontalScrollBar()->setValue(horizontalScrollBar()->value() + (5 * hpercent)); + } else if (d->m_scrollDirection == Top) { + verticalScrollBar()->setValue(verticalScrollBar()->value() - (5 * vpercent)); + } else if (d->m_scrollDirection == Bottom) { + verticalScrollBar()->setValue(verticalScrollBar()->value() + (5 * vpercent)); } - else if (mapFromGlobal(QCursor::pos()).y() >= height()) - { - d->m_scrollDirection = Bottom; +} + +void DotGraphView::leaveEvent(QEvent * /*event*/) +{ + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG) << mapFromGlobal(QCursor::pos()); + if (d->m_editingMode == DrawNewEdge) { + d->m_leavedTimer = startTimer(10); + if (mapFromGlobal(QCursor::pos()).x() <= 0) { + d->m_scrollDirection = Left; + } else if (mapFromGlobal(QCursor::pos()).y() <= 0) { + d->m_scrollDirection = Top; + } else if (mapFromGlobal(QCursor::pos()).x() >= width()) { + d->m_scrollDirection = Right; + } else if (mapFromGlobal(QCursor::pos()).y() >= height()) { + d->m_scrollDirection = Bottom; + } } - } } -void DotGraphView::enterEvent ( QEvent * /*event*/ ) +void DotGraphView::enterEvent(QEvent * /*event*/) { - Q_D(DotGraphView); - qCDebug(KGRAPHVIEWERLIB_LOG); - if (d->m_leavedTimer != std::numeric_limits::max()) - { - killTimer(d->m_leavedTimer); - d->m_leavedTimer = std::numeric_limits::max(); - } + Q_D(DotGraphView); + qCDebug(KGRAPHVIEWERLIB_LOG); + if (d->m_leavedTimer != std::numeric_limits::max()) { + killTimer(d->m_leavedTimer); + d->m_leavedTimer = std::numeric_limits::max(); + } } void DotGraphView::slotAGraphReadFinished() { - Q_D(DotGraphView); - QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); - if (layoutCommand.isEmpty()) - { - if (!d->m_loadThread.dotFileName().isEmpty()) - layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_loadThread.dotFileName()); - else - layoutCommand = "dot"; - } - d->m_layoutThread.layoutGraph(d->m_loadThread.g(), layoutCommand); - d->m_loadThread.processed_finished(); + Q_D(DotGraphView); + QString layoutCommand = (d->m_graph ? d->m_graph->layoutCommand() : QString()); + if (layoutCommand.isEmpty()) { + if (!d->m_loadThread.dotFileName().isEmpty()) + layoutCommand = d->m_graph->chooseLayoutProgramForFile(d->m_loadThread.dotFileName()); + else + layoutCommand = "dot"; + } + d->m_layoutThread.layoutGraph(d->m_loadThread.g(), layoutCommand); + d->m_loadThread.processed_finished(); } void DotGraphView::slotAGraphLayoutFinished() { - Q_D(DotGraphView); - graph_t *g = d->m_layoutThread.g(); - bool result = loadLibrary(g, d->m_layoutThread.layoutCommand()); - if (result) - // file name can be taken from m_loadThread both in sync and async loading cases - // see comment in loadLibrarySync() - d->m_graph->dotFileName(d->m_loadThread.dotFileName()); - else - { - Q_ASSERT(!d->m_canvas); - QGraphicsScene *newCanvas = new QGraphicsScene(); - QGraphicsSimpleTextItem* loadingLabel = newCanvas->addSimpleText(i18n("Failed to open %1", d->m_loadThread.dotFileName())); - loadingLabel->setZValue(100); - centerOn(loadingLabel); - setScene(newCanvas); - d->m_canvas = newCanvas; - } + Q_D(DotGraphView); + graph_t *g = d->m_layoutThread.g(); + bool result = loadLibrary(g, d->m_layoutThread.layoutCommand()); + if (result) + // file name can be taken from m_loadThread both in sync and async loading cases + // see comment in loadLibrarySync() + d->m_graph->dotFileName(d->m_loadThread.dotFileName()); + else { + Q_ASSERT(!d->m_canvas); + QGraphicsScene *newCanvas = new QGraphicsScene(); + QGraphicsSimpleTextItem *loadingLabel = newCanvas->addSimpleText(i18n("Failed to open %1", d->m_loadThread.dotFileName())); + loadingLabel->setZValue(100); + centerOn(loadingLabel); + setScene(newCanvas); + d->m_canvas = newCanvas; + } - if (g) - { - gvFreeLayout(d->m_layoutThread.gvc(), g); - agclose(g); - } - d->m_layoutThread.processed_finished(); + if (g) { + gvFreeLayout(d->m_layoutThread.gvc(), g); + agclose(g); + } + d->m_layoutThread.processed_finished(); } -void DotGraphView::slotSelectNode(const QString& nodeName) +void DotGraphView::slotSelectNode(const QString &nodeName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName; - GraphNode* node = dynamic_cast(graph()->elementNamed(nodeName)); - if (node == nullptr) return; - node->setSelected(true); - if (node->canvasNode()) - { - node->canvasNode()->modelChanged(); - slotElementSelected(node->canvasNode(),Qt::NoModifier); - } + qCDebug(KGRAPHVIEWERLIB_LOG) << nodeName; + GraphNode *node = dynamic_cast(graph()->elementNamed(nodeName)); + if (node == nullptr) + return; + node->setSelected(true); + if (node->canvasNode()) { + node->canvasNode()->modelChanged(); + slotElementSelected(node->canvasNode(), Qt::NoModifier); + } } -void DotGraphView::centerOnNode(const QString& nodeId) +void DotGraphView::centerOnNode(const QString &nodeId) { - GraphNode* node = dynamic_cast(graph()->elementNamed(nodeId)); - if (node == nullptr) return; - if (node->canvasNode()) - { - centerOn(node->canvasNode()); - } + GraphNode *node = dynamic_cast(graph()->elementNamed(nodeId)); + if (node == nullptr) + return; + if (node->canvasNode()) { + centerOn(node->canvasNode()); + } } - } diff --git a/src/part/dotrenderop.h b/src/part/dotrenderop.h --- a/src/part/dotrenderop.h +++ b/src/part/dotrenderop.h @@ -19,21 +19,20 @@ #ifndef DOT_RENDEROP_H #define DOT_RENDEROP_H -#include #include +#include #include /** * members are interpreted in function of render operations definitions given at: * @URL http://www.graphviz.org/cvs/doc/info/output.html#d:dot */ -struct DotRenderOp -{ - QString renderop; - QList< int > integers; - QString str; +struct DotRenderOp { + QString renderop; + QList integers; + QString str; }; -typedef QList< DotRenderOp > DotRenderOpVec; +typedef QList DotRenderOpVec; #endif diff --git a/src/part/graphedge.h b/src/part/graphedge.h --- a/src/part/graphedge.h +++ b/src/part/graphedge.h @@ -24,99 +24,141 @@ License as published by the Free Software Foundation, version 2. */ - /* * Graph Edge */ #ifndef GRAPH_EDGE_H #define GRAPH_EDGE_H #include "canvasnode.h" -#include "graphelement.h" #include "dotgrammar.h" #include "dotrenderop.h" +#include "graphelement.h" #include -#include #include +#include #include namespace KGraphViewer { - class CanvasEdge; class GraphEdge : public GraphElement { - Q_OBJECT + Q_OBJECT public: - GraphEdge(); - ~GraphEdge() override; - - explicit GraphEdge(const GraphEdge& edge); - explicit GraphEdge(edge_t* edge); - - CanvasEdge* canvasEdge() { return (CanvasEdge*)canvasElement(); } - const CanvasEdge* canvasEdge() const { return (CanvasEdge*)canvasElement(); } - void setCanvasEdge(CanvasEdge* ce) { setCanvasElement((CanvasElement*)ce); } - - bool isVisible() { return m_visible; } - void setVisible(bool v) { m_visible = v; } - - GraphElement* fromNode() { return m_fromNode; } - GraphElement* toNode() { return m_toNode; } - const GraphElement* fromNode() const { return m_fromNode; } - const GraphElement* toNode() const { return m_toNode; } - - void setFromNode(GraphElement* n) { m_fromNode = n; } - void setToNode(GraphElement* n) { m_toNode = n; } - -// inline const QVector< QPair< float, float > >& edgePoints() const {return m_edgePoints;} -// inline QVector< QPair< float, float > >& edgePoints() {return m_edgePoints;} -// inline void edgePoints(const QVector< QPair< float, float > >& ep) {m_edgePoints = ep;} - - inline const QStringList& colors() const {return m_colors;} - const QString color(uint i); - void colors(const QString& cs); - -/* inline void labelX(float x) {m_labelX = x;} - inline void labelY(float y) {m_labelY = y;} - inline float labelX() const {return m_labelX;} - inline float labelY() const {return m_labelY;}*/ - - inline const QString& dir() const {return m_dir;} - inline void dir(const QString& dir) {m_dir = dir;} - - inline QList< DotRenderOp >& arrowheads() {return m_arrowheads;} - inline const QList< DotRenderOp >& arrowheads() const {return m_arrowheads;} - - void updateWithEdge(const GraphEdge& edge); - void updateWithEdge(edge_t* edge); + GraphEdge(); + ~GraphEdge() override; + + explicit GraphEdge(const GraphEdge &edge); + explicit GraphEdge(edge_t *edge); + + CanvasEdge *canvasEdge() + { + return (CanvasEdge *)canvasElement(); + } + const CanvasEdge *canvasEdge() const + { + return (CanvasEdge *)canvasElement(); + } + void setCanvasEdge(CanvasEdge *ce) + { + setCanvasElement((CanvasElement *)ce); + } + + bool isVisible() + { + return m_visible; + } + void setVisible(bool v) + { + m_visible = v; + } + + GraphElement *fromNode() + { + return m_fromNode; + } + GraphElement *toNode() + { + return m_toNode; + } + const GraphElement *fromNode() const + { + return m_fromNode; + } + const GraphElement *toNode() const + { + return m_toNode; + } + + void setFromNode(GraphElement *n) + { + m_fromNode = n; + } + void setToNode(GraphElement *n) + { + m_toNode = n; + } + + // inline const QVector< QPair< float, float > >& edgePoints() const {return m_edgePoints;} + // inline QVector< QPair< float, float > >& edgePoints() {return m_edgePoints;} + // inline void edgePoints(const QVector< QPair< float, float > >& ep) {m_edgePoints = ep;} + + inline const QStringList &colors() const + { + return m_colors; + } + const QString color(uint i); + void colors(const QString &cs); + + /* inline void labelX(float x) {m_labelX = x;} + inline void labelY(float y) {m_labelY = y;} + inline float labelX() const {return m_labelX;} + inline float labelY() const {return m_labelY;}*/ + + inline const QString &dir() const + { + return m_dir; + } + inline void dir(const QString &dir) + { + m_dir = dir; + } + + inline QList &arrowheads() + { + return m_arrowheads; + } + inline const QList &arrowheads() const + { + return m_arrowheads; + } + + void updateWithEdge(const GraphEdge &edge); + void updateWithEdge(edge_t *edge); private: - // we have a _ce *and* _from/_to because for collapsed edges, - // only _to or _from will be unequal nullptr - GraphElement *m_fromNode, *m_toNode; - bool m_visible; - QStringList m_colors; - QString m_dir; -// QVector< QPair< float, float > > m_edgePoints; -// float m_labelX, m_labelY; - - QList< DotRenderOp > m_arrowheads; + // we have a _ce *and* _from/_to because for collapsed edges, + // only _to or _from will be unequal nullptr + GraphElement *m_fromNode, *m_toNode; + bool m_visible; + QStringList m_colors; + QString m_dir; + // QVector< QPair< float, float > > m_edgePoints; + // float m_labelX, m_labelY; + + QList m_arrowheads; }; - /** A map associating the bounds nodes of a graph's edges to these edges */ -typedef QMap GraphEdgeMap; +typedef QMap GraphEdgeMap; -QTextStream& operator<<(QTextStream& s, const GraphEdge& e); +QTextStream &operator<<(QTextStream &s, const GraphEdge &e); } #endif - - - diff --git a/src/part/graphedge.cpp b/src/part/graphedge.cpp --- a/src/part/graphedge.cpp +++ b/src/part/graphedge.cpp @@ -25,38 +25,37 @@ */ #include "graphedge.h" -#include "graphnode.h" -#include "graphsubgraph.h" #include "canvasedge.h" #include "dotdefaults.h" +#include "graphnode.h" +#include "graphsubgraph.h" #include "kgraphviewerlib_debug.h" namespace KGraphViewer { - /* * Graph Edge */ -GraphEdge::GraphEdge() : - GraphElement(), - m_fromNode(nullptr), - m_toNode(nullptr), - m_visible(true), - m_colors(), - m_dir(DOT_DEFAULT_EDGE_DIR), - m_arrowheads() +GraphEdge::GraphEdge() + : GraphElement() + , m_fromNode(nullptr) + , m_toNode(nullptr) + , m_visible(true) + , m_colors() + , m_dir(DOT_DEFAULT_EDGE_DIR) + , m_arrowheads() { -// qCDebug(KGRAPHVIEWERLIB_LOG) ; + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } GraphEdge::~GraphEdge() { -// qCDebug(KGRAPHVIEWERLIB_LOG) ; + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } -GraphEdge::GraphEdge(const GraphEdge& edge) : - GraphElement(edge) +GraphEdge::GraphEdge(const GraphEdge &edge) + : GraphElement(edge) { m_fromNode = nullptr; m_toNode = nullptr; @@ -66,109 +65,93 @@ m_arrowheads = edge.m_arrowheads; } -void GraphEdge::colors(const QString& cs) +void GraphEdge::colors(const QString &cs) { - m_colors = cs.split(':'); -// qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << ": nb colors: " << m_colors.size(); + m_colors = cs.split(':'); + // qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << ": nb colors: " << m_colors.size(); } -const QString GraphEdge::color(uint i) +const QString GraphEdge::color(uint i) { - if (i >= (uint)m_colors.count() && m_attributes.find(KEY_COLOR) != m_attributes.end()) - { - colors(m_attributes[KEY_COLOR]); - } - if (i < (uint)m_colors.count()) - { -// std::cerr << "edge color " << i << " is " << m_colors[i] << std::endl; -// qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << "color" << i << "is" << m_colors[i]; - return m_colors[i]; - } - else - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << "no edge color " << i << ". returning " << DOT_DEFAULT_EDGE_COLOR; - return DOT_DEFAULT_EDGE_COLOR; - } + if (i >= (uint)m_colors.count() && m_attributes.find(KEY_COLOR) != m_attributes.end()) { + colors(m_attributes[KEY_COLOR]); + } + if (i < (uint)m_colors.count()) { + // std::cerr << "edge color " << i << " is " << m_colors[i] << std::endl; + // qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << "color" << i << "is" << m_colors[i]; + return m_colors[i]; + } else { + // qCDebug(KGRAPHVIEWERLIB_LOG) << fromNode()->id() << " -> " << toNode()->id() << "no edge color " << i << ". returning " << DOT_DEFAULT_EDGE_COLOR; + return DOT_DEFAULT_EDGE_COLOR; + } } -void GraphEdge::updateWithEdge(const GraphEdge& edge) +void GraphEdge::updateWithEdge(const GraphEdge &edge) { - qCDebug(KGRAPHVIEWERLIB_LOG) << id() << edge.id(); - m_arrowheads = edge.arrowheads(); - m_colors = edge.colors(); - m_dir = edge.dir(); - GraphElement::updateWithElement(edge); - if (canvasEdge()) - { - canvasEdge()->computeBoundingRect(); - canvasEdge()->modelChanged(); - } + qCDebug(KGRAPHVIEWERLIB_LOG) << id() << edge.id(); + m_arrowheads = edge.arrowheads(); + m_colors = edge.colors(); + m_dir = edge.dir(); + GraphElement::updateWithElement(edge); + if (canvasEdge()) { + canvasEdge()->computeBoundingRect(); + canvasEdge()->modelChanged(); + } } -void GraphEdge::updateWithEdge(edge_t* edge) +void GraphEdge::updateWithEdge(edge_t *edge) { - qCDebug(KGRAPHVIEWERLIB_LOG); - DotRenderOpVec ops; - // decrease mem peak - setRenderOperations(ops); - - if (agget(edge, (char*)"_draw_")) - { - parse_renderop(agget(edge, (char*)"_draw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - if (agget(edge, (char*)"_ldraw_")) - { - parse_renderop(agget(edge, (char*)"_ldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - if (agget(edge, (char*)"_hdraw_")) - { - parse_renderop(agget(edge, (char*)"_hdraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - if (agget(edge, (char*)"_tdraw_")) - { - parse_renderop(agget(edge, (char*)"_tdraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - if (agget(edge, (char*)"_hldraw_")) - { - parse_renderop(agget(edge, (char*)"_hldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - if (agget(edge, (char*)"_tldraw_")) - { - parse_renderop(agget(edge, (char*)"_tldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); - } - setRenderOperations(ops); - Agsym_t *attr = agnxtattr(agraphof(agtail(edge)), AGEDGE, nullptr); - while(attr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) /*<< edge->name*/ << ":" << attr->name << agxget(edge,attr); - m_attributes[attr->name] = agxget(edge,attr); - attr = agnxtattr(agraphof(agtail(edge)), AGEDGE, attr); - } - + qCDebug(KGRAPHVIEWERLIB_LOG); + DotRenderOpVec ops; + // decrease mem peak + setRenderOperations(ops); + + if (agget(edge, (char *)"_draw_")) { + parse_renderop(agget(edge, (char *)"_draw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + if (agget(edge, (char *)"_ldraw_")) { + parse_renderop(agget(edge, (char *)"_ldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + if (agget(edge, (char *)"_hdraw_")) { + parse_renderop(agget(edge, (char *)"_hdraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + if (agget(edge, (char *)"_tdraw_")) { + parse_renderop(agget(edge, (char *)"_tdraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + if (agget(edge, (char *)"_hldraw_")) { + parse_renderop(agget(edge, (char *)"_hldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + if (agget(edge, (char *)"_tldraw_")) { + parse_renderop(agget(edge, (char *)"_tldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "element renderOperations size is now " << ops.size(); + } + setRenderOperations(ops); + Agsym_t *attr = agnxtattr(agraphof(agtail(edge)), AGEDGE, nullptr); + while (attr) { + qCDebug(KGRAPHVIEWERLIB_LOG) /*<< edge->name*/ << ":" << attr->name << agxget(edge, attr); + m_attributes[attr->name] = agxget(edge, attr); + attr = agnxtattr(agraphof(agtail(edge)), AGEDGE, attr); + } } -QTextStream& operator<<(QTextStream& s, const GraphEdge& e) +QTextStream &operator<<(QTextStream &s, const GraphEdge &e) { - QString srcLabel = e.fromNode()->id(); - if (dynamic_cast(e.fromNode())) - { - srcLabel = QString("subgraph ") + srcLabel; - } - QString tgtLabel = e.toNode()->id(); - if (dynamic_cast(e.toNode())) - { - tgtLabel = QString("subgraph ") + tgtLabel; - } - s << srcLabel << " -> " << tgtLabel << " [" - << dynamic_cast(e) << "];" << endl; - - return s; + QString srcLabel = e.fromNode()->id(); + if (dynamic_cast(e.fromNode())) { + srcLabel = QString("subgraph ") + srcLabel; + } + QString tgtLabel = e.toNode()->id(); + if (dynamic_cast(e.toNode())) { + tgtLabel = QString("subgraph ") + tgtLabel; + } + s << srcLabel << " -> " << tgtLabel << " [" << dynamic_cast(e) << "];" << endl; + + return s; } } diff --git a/src/part/graphelement.h b/src/part/graphelement.h --- a/src/part/graphelement.h +++ b/src/part/graphelement.h @@ -21,132 +21,246 @@ #include "dotrenderop.h" -#include #include #include #include +#include namespace KGraphViewer { - class CanvasElement; /** * The base of all Graphviz DOT graph elements (nodes, edges, subgraphs, * graphs). It is used to store the element attributes */ -class GraphElement: public QObject +class GraphElement : public QObject { - Q_OBJECT + Q_OBJECT public: - GraphElement(); - GraphElement(const GraphElement& element); - - ~GraphElement() override {} - - inline void setId(const QString& id) {m_attributes[KEY_ID]=id;} - inline void setStyle(const QString& ls) {m_attributes[KEY_STYLE]=ls;} - inline void setShape(const QString& lc) {m_attributes[KEY_SHAPE]=lc;} - inline void setColor(const QString& nt) {m_attributes[KEY_COLOR]=nt;} - inline void setLineColor(const QString& nt) {m_attributes[KEY_COLOR]=nt;} - inline void setBackColor(const QString& nc) {m_attributes[KEY_BGCOLOR]=nc;} - - inline QString id() const {return m_attributes[KEY_ID];} - inline QString style() const {return m_attributes[KEY_STYLE];} - inline QString shape() const {return m_attributes[KEY_SHAPE];} - inline QString color() const {return m_attributes[KEY_COLOR];} - inline QString lineColor() const {return m_attributes[KEY_COLOR];} - virtual QString backColor() const; - - inline void setLabel(const QString& label) {m_attributes[KEY_LABEL]=label;} - inline const QString label() const {return m_attributes[KEY_LABEL];} - - inline unsigned int fontSize() const {return m_attributes[KEY_FONTSIZE].toUInt();} - inline void setFontSize(unsigned int fs) {m_attributes[KEY_FONTSIZE]=QString::number(fs);} - inline QString fontName() const {return m_attributes[KEY_FONTNAME];} - inline void setFontName(const QString& fn) {m_attributes[KEY_FONTNAME]=fn;} - inline QString fontColor() const {return m_attributes[KEY_FONTCOLOR];} - inline void setFontColor(const QString& fc) {m_attributes[KEY_FONTCOLOR] = fc;} - - inline const DotRenderOpVec& renderOperations() const {return m_renderOperations;}; - void setRenderOperations(const DotRenderOpVec& drov); - /** - * indicates the version of the render operations, gets increased every time - * @c setRenderOperations gets called. - */ - inline quint32 renderOperationsRevision() const {return m_renderOperationsRevision;}; - - inline double z() const {return m_z;} - inline void setZ(double thez) {m_z = thez;} - - inline QString shapeFile() const {return m_attributes[KEY_SHAPEFILE];} - inline void setShapeFile(const QString& sf) {m_attributes[KEY_SHAPEFILE] = sf;} - - inline QString url() const {return m_attributes[KEY_URL];} - inline void setUrl(const QString& theUrl) {m_attributes[KEY_URL] = theUrl;} - - virtual void updateWithElement(const GraphElement& element); - - inline QMap& attributes() {return m_attributes;} - inline const QMap& attributes() const {return m_attributes;} - - inline QList& originalAttributes() {return m_originalAttributes;} - inline const QList& originalAttributes() const {return m_originalAttributes;} - - virtual inline void storeOriginalAttributes() {m_originalAttributes = m_attributes.keys();} - - virtual void removeAttribute(const QString& attribName); - - inline CanvasElement* canvasElement() {return m_ce;} - inline const CanvasElement* canvasElement() const {return m_ce;} - inline void setCanvasElement(CanvasElement* ce) {m_ce = ce;} - - inline void setSelected(bool s) {m_selected=s;} - inline bool isSelected() {return m_selected;} - - bool isVisible() const { return m_visible; } - void setVisible(bool v) { m_visible = v; } - - void exportToGraphviz(void* element) const; + GraphElement(); + GraphElement(const GraphElement &element); + + ~GraphElement() override + { + } + + inline void setId(const QString &id) + { + m_attributes[KEY_ID] = id; + } + inline void setStyle(const QString &ls) + { + m_attributes[KEY_STYLE] = ls; + } + inline void setShape(const QString &lc) + { + m_attributes[KEY_SHAPE] = lc; + } + inline void setColor(const QString &nt) + { + m_attributes[KEY_COLOR] = nt; + } + inline void setLineColor(const QString &nt) + { + m_attributes[KEY_COLOR] = nt; + } + inline void setBackColor(const QString &nc) + { + m_attributes[KEY_BGCOLOR] = nc; + } + + inline QString id() const + { + return m_attributes[KEY_ID]; + } + inline QString style() const + { + return m_attributes[KEY_STYLE]; + } + inline QString shape() const + { + return m_attributes[KEY_SHAPE]; + } + inline QString color() const + { + return m_attributes[KEY_COLOR]; + } + inline QString lineColor() const + { + return m_attributes[KEY_COLOR]; + } + virtual QString backColor() const; + + inline void setLabel(const QString &label) + { + m_attributes[KEY_LABEL] = label; + } + inline const QString label() const + { + return m_attributes[KEY_LABEL]; + } + + inline unsigned int fontSize() const + { + return m_attributes[KEY_FONTSIZE].toUInt(); + } + inline void setFontSize(unsigned int fs) + { + m_attributes[KEY_FONTSIZE] = QString::number(fs); + } + inline QString fontName() const + { + return m_attributes[KEY_FONTNAME]; + } + inline void setFontName(const QString &fn) + { + m_attributes[KEY_FONTNAME] = fn; + } + inline QString fontColor() const + { + return m_attributes[KEY_FONTCOLOR]; + } + inline void setFontColor(const QString &fc) + { + m_attributes[KEY_FONTCOLOR] = fc; + } + + inline const DotRenderOpVec &renderOperations() const + { + return m_renderOperations; + }; + void setRenderOperations(const DotRenderOpVec &drov); + /** + * indicates the version of the render operations, gets increased every time + * @c setRenderOperations gets called. + */ + inline quint32 renderOperationsRevision() const + { + return m_renderOperationsRevision; + }; + + inline double z() const + { + return m_z; + } + inline void setZ(double thez) + { + m_z = thez; + } + + inline QString shapeFile() const + { + return m_attributes[KEY_SHAPEFILE]; + } + inline void setShapeFile(const QString &sf) + { + m_attributes[KEY_SHAPEFILE] = sf; + } + + inline QString url() const + { + return m_attributes[KEY_URL]; + } + inline void setUrl(const QString &theUrl) + { + m_attributes[KEY_URL] = theUrl; + } + + virtual void updateWithElement(const GraphElement &element); + + inline QMap &attributes() + { + return m_attributes; + } + inline const QMap &attributes() const + { + return m_attributes; + } + + inline QList &originalAttributes() + { + return m_originalAttributes; + } + inline const QList &originalAttributes() const + { + return m_originalAttributes; + } + + virtual inline void storeOriginalAttributes() + { + m_originalAttributes = m_attributes.keys(); + } + + virtual void removeAttribute(const QString &attribName); + + inline CanvasElement *canvasElement() + { + return m_ce; + } + inline const CanvasElement *canvasElement() const + { + return m_ce; + } + inline void setCanvasElement(CanvasElement *ce) + { + m_ce = ce; + } + + inline void setSelected(bool s) + { + m_selected = s; + } + inline bool isSelected() + { + return m_selected; + } + + bool isVisible() const + { + return m_visible; + } + void setVisible(bool v) + { + m_visible = v; + } + + void exportToGraphviz(void *element) const; Q_SIGNALS: - void changed(); + void changed(); protected: - QMap m_attributes; - QList m_originalAttributes; - - CanvasElement* m_ce; - - static const QString KEY_ID; - static const QString KEY_STYLE; - static const QString KEY_LABEL; - static const QString KEY_SHAPE; - static const QString KEY_SHAPEFILE; - static const QString KEY_COLOR; - static const QString KEY_BGCOLOR; - static const QString KEY_URL; - static const QString KEY_FONTSIZE; - static const QString KEY_FONTNAME; - static const QString KEY_FONTCOLOR; - static const QString KEY_FILLCOLOR; + QMap m_attributes; + QList m_originalAttributes; + + CanvasElement *m_ce; + + static const QString KEY_ID; + static const QString KEY_STYLE; + static const QString KEY_LABEL; + static const QString KEY_SHAPE; + static const QString KEY_SHAPEFILE; + static const QString KEY_COLOR; + static const QString KEY_BGCOLOR; + static const QString KEY_URL; + static const QString KEY_FONTSIZE; + static const QString KEY_FONTNAME; + static const QString KEY_FONTCOLOR; + static const QString KEY_FILLCOLOR; private: - double m_z; - bool m_visible; + double m_z; + bool m_visible; - DotRenderOpVec m_renderOperations; - quint32 m_renderOperationsRevision; + DotRenderOpVec m_renderOperations; + quint32 m_renderOperationsRevision; - bool m_selected; + bool m_selected; }; - -QTextStream& operator<<(QTextStream& s, const GraphElement& n); +QTextStream &operator<<(QTextStream &s, const GraphElement &n); } #endif - - - diff --git a/src/part/graphelement.cpp b/src/part/graphelement.cpp --- a/src/part/graphelement.cpp +++ b/src/part/graphelement.cpp @@ -30,7 +30,6 @@ namespace KGraphViewer { - const QString GraphElement::KEY_ID = QLatin1String("id"); const QString GraphElement::KEY_STYLE = QLatin1String("style"); const QString GraphElement::KEY_LABEL = QLatin1String("label"); @@ -44,188 +43,163 @@ const QString GraphElement::KEY_FONTCOLOR = QLatin1String("fontcolor"); const QString GraphElement::KEY_FILLCOLOR = QLatin1String("fillcolor"); -GraphElement::GraphElement() : - QObject(), - m_attributes(), - m_originalAttributes(), - m_ce(nullptr), - m_z(1.0), - m_renderOperations(), - m_renderOperationsRevision(0), - m_selected(false) +GraphElement::GraphElement() + : QObject() + , m_attributes() + , m_originalAttributes() + , m_ce(nullptr) + , m_z(1.0) + , m_renderOperations() + , m_renderOperationsRevision(0) + , m_selected(false) { -/* label(""); - id(""); - style(DOT_DEFAULT_STYLE); - shape(DOT_DEFAULT_SHAPE); - lineColor(DOT_DEFAULT_LINECOLOR); - backColor(DOT_DEFAULT_BACKCOLOR); - fontName(DOT_DEFAULT_FONTNAME); - fontColor(DOT_DEFAULT_FONTCOLOR); - url(""); - shapeFile("");*/ - setFontSize(DOT_DEFAULT_FONTSIZE); + /* label(""); + id(""); + style(DOT_DEFAULT_STYLE); + shape(DOT_DEFAULT_SHAPE); + lineColor(DOT_DEFAULT_LINECOLOR); + backColor(DOT_DEFAULT_BACKCOLOR); + fontName(DOT_DEFAULT_FONTNAME); + fontColor(DOT_DEFAULT_FONTCOLOR); + url(""); + shapeFile("");*/ + setFontSize(DOT_DEFAULT_FONTSIZE); } -GraphElement::GraphElement(const GraphElement& element) : QObject(), - m_attributes(), - m_originalAttributes(), - m_ce(element.m_ce), - m_z(element.m_z), - m_renderOperations(), - m_renderOperationsRevision(0), - m_selected(element.m_selected) +GraphElement::GraphElement(const GraphElement &element) + : QObject() + , m_attributes() + , m_originalAttributes() + , m_ce(element.m_ce) + , m_z(element.m_z) + , m_renderOperations() + , m_renderOperationsRevision(0) + , m_selected(element.m_selected) { - updateWithElement(element); + updateWithElement(element); } -void GraphElement::setRenderOperations(const DotRenderOpVec& drov) +void GraphElement::setRenderOperations(const DotRenderOpVec &drov) { m_renderOperations = drov; ++m_renderOperationsRevision; } -void GraphElement::updateWithElement(const GraphElement& element) +void GraphElement::updateWithElement(const GraphElement &element) { - qCDebug(KGRAPHVIEWERLIB_LOG) << element.id(); - bool modified = false; - if (element.z() != m_z) - { - m_z = element.z(); - modified = true; - } - QMap ::const_iterator it = element.attributes().constBegin(); - for (;it != element.attributes().constEnd(); it++) - { - const QString &attrib = it.key(); - if ( (!m_attributes.contains(attrib)) || (m_attributes[attrib] != it.value()) ) - { - m_attributes[attrib] = it.value(); - if (attrib == "z") - { - bool ok; - setZ(m_attributes[attrib].toDouble(&ok)); - } - modified = true; + qCDebug(KGRAPHVIEWERLIB_LOG) << element.id(); + bool modified = false; + if (element.z() != m_z) { + m_z = element.z(); + modified = true; + } + QMap::const_iterator it = element.attributes().constBegin(); + for (; it != element.attributes().constEnd(); it++) { + const QString &attrib = it.key(); + if ((!m_attributes.contains(attrib)) || (m_attributes[attrib] != it.value())) { + m_attributes[attrib] = it.value(); + if (attrib == "z") { + bool ok; + setZ(m_attributes[attrib].toDouble(&ok)); + } + modified = true; + } } - } - if (modified) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "modified: update render operations"; - setRenderOperations(element.m_renderOperations); -/* foreach (DotRenderOp op, m_renderOperations) - { - QString msg; - QTextStream dd(&msg); - dd << "an op: " << op.renderop << " "; - foreach (int i, op.integers) - { - dd << i << " "; - } - dd << op.str; - qCDebug(KGRAPHVIEWERLIB_LOG) << msg; + if (modified) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "modified: update render operations"; + setRenderOperations(element.m_renderOperations); + /* foreach (DotRenderOp op, m_renderOperations) + { + QString msg; + QTextStream dd(&msg); + dd << "an op: " << op.renderop << " "; + foreach (int i, op.integers) + { + dd << i << " "; + } + dd << op.str; + qCDebug(KGRAPHVIEWERLIB_LOG) << msg; + } + g() << "modified: emiting changed";*/ + emit changed(); } - g() << "modified: emiting changed";*/ - emit changed(); - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "done" << m_renderOperations.size(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "done" << m_renderOperations.size(); } - QString GraphElement::backColor() const { - if (m_attributes.find(KEY_FILLCOLOR) != m_attributes.end()) - { - return m_attributes[KEY_FILLCOLOR]; - } - else if ( (m_attributes.find(KEY_COLOR) != m_attributes.end()) - && (m_attributes[KEY_STYLE] == QLatin1String("filled")) ) - { - return m_attributes[KEY_COLOR]; - } - else - { - return DOT_DEFAULT_NODE_BACKCOLOR; - } + if (m_attributes.find(KEY_FILLCOLOR) != m_attributes.end()) { + return m_attributes[KEY_FILLCOLOR]; + } else if ((m_attributes.find(KEY_COLOR) != m_attributes.end()) && (m_attributes[KEY_STYLE] == QLatin1String("filled"))) { + return m_attributes[KEY_COLOR]; + } else { + return DOT_DEFAULT_NODE_BACKCOLOR; + } } -void GraphElement::removeAttribute(const QString& attribName) +void GraphElement::removeAttribute(const QString &attribName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << attribName; - m_attributes.remove(attribName); - emit changed(); + qCDebug(KGRAPHVIEWERLIB_LOG) << attribName; + m_attributes.remove(attribName); + emit changed(); } -void GraphElement::exportToGraphviz(void* element) const +void GraphElement::exportToGraphviz(void *element) const { - QMap::const_iterator it, it_end; - it = attributes().begin(); it_end = attributes().end(); - for (;it != it_end; it++) - { - if (!it.value().isEmpty()) - { - if (it.key() == "label") - { - QString label = it.value(); - if (label != "label") - { - label.replace(QRegExp("\n"),"\\n"); - // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << "=\"" << label << "\","; - agsafeset(element, it.key().toUtf8().data(), label.toUtf8().data(), QString().toUtf8().data()); + QMap::const_iterator it, it_end; + it = attributes().begin(); + it_end = attributes().end(); + for (; it != it_end; it++) { + if (!it.value().isEmpty()) { + if (it.key() == "label") { + QString label = it.value(); + if (label != "label") { + label.replace(QRegExp("\n"), "\\n"); + // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << "=\"" << label << "\","; + agsafeset(element, it.key().toUtf8().data(), label.toUtf8().data(), QString().toUtf8().data()); + } + } else if (it.key() == "_draw_" || it.key() == "_ldraw_") { + } else if (originalAttributes().isEmpty() || originalAttributes().contains(it.key())) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << it.value(); + + agsafeset(element, it.key().toUtf8().data(), it.value().toUtf8().data(), QString().toUtf8().data()); + } } - } - else if (it.key() == "_draw_" || it.key() == "_ldraw_") - { - } - else if (originalAttributes().isEmpty() || originalAttributes().contains(it.key())) - { - // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << it.value(); - - agsafeset(element, it.key().toUtf8().data(), it.value().toUtf8().data(), QString().toUtf8().data()); - } } - } } -QTextStream& operator<<(QTextStream& s, const GraphElement& n) +QTextStream &operator<<(QTextStream &s, const GraphElement &n) { - QMap::const_iterator it, it_end; - bool firstAttr = true; - it = n.attributes().begin(); it_end = n.attributes().end(); - for (;it != it_end; it++) - { - if (!it.value().isEmpty()) - { - if (it.key() == "label") - { - QString label = it.value(); - if (label != "label") - { - label.replace(QRegExp("\n"),"\\n"); -// qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << "=\"" << label << "\","; - if (firstAttr) - firstAttr = false; - else - s << ','; - s << it.key() << "=\"" << label << '"'; + QMap::const_iterator it, it_end; + bool firstAttr = true; + it = n.attributes().begin(); + it_end = n.attributes().end(); + for (; it != it_end; it++) { + if (!it.value().isEmpty()) { + if (it.key() == "label") { + QString label = it.value(); + if (label != "label") { + label.replace(QRegExp("\n"), "\\n"); + // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << "=\"" << label << "\","; + if (firstAttr) + firstAttr = false; + else + s << ','; + s << it.key() << "=\"" << label << '"'; + } + } else if (it.key() == "_draw_" || it.key() == "_ldraw_") { + } else if (n.originalAttributes().isEmpty() || n.originalAttributes().contains(it.key())) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << it.value(); + + if (firstAttr) + firstAttr = false; + else + s << ','; + s << it.key() << "=\"" << it.value() << '"'; + } } - } - else if (it.key() == "_draw_" || it.key() == "_ldraw_") - { - } - else if (n.originalAttributes().isEmpty() || n.originalAttributes().contains(it.key())) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << it.key() << it.value(); - - if (firstAttr) - firstAttr = false; - else - s << ','; - s << it.key() << "=\"" << it.value() << '"'; - } } - } - return s; + return s; } } diff --git a/src/part/graphexporter.h b/src/part/graphexporter.h --- a/src/part/graphexporter.h +++ b/src/part/graphexporter.h @@ -35,29 +35,25 @@ #include - namespace KGraphViewer { class DotGraph; - + /** * GraphExporter * * Generates a graph file for "dot" */ class GraphExporter { public: - GraphExporter(); - ~GraphExporter(); + GraphExporter(); + ~GraphExporter(); - QString writeDot(const DotGraph* graph, const QString& fileName = QString()); - graph_t* exportToGraphviz(const DotGraph* graph); + QString writeDot(const DotGraph *graph, const QString &fileName = QString()); + graph_t *exportToGraphviz(const DotGraph *graph); }; } #endif - - - diff --git a/src/part/graphexporter.cpp b/src/part/graphexporter.cpp --- a/src/part/graphexporter.cpp +++ b/src/part/graphexporter.cpp @@ -24,7 +24,6 @@ License as published by the Free Software Foundation, version 2. */ - #include "graphexporter.h" #include "dotgraph.h" #include "kgraphviewerlib_debug.h" @@ -37,127 +36,111 @@ namespace KGraphViewer { - GraphExporter::GraphExporter() { } GraphExporter::~GraphExporter() { } -QString GraphExporter::writeDot(const DotGraph* graph, const QString& fileName) +QString GraphExporter::writeDot(const DotGraph *graph, const QString &fileName) { - qCDebug(KGRAPHVIEWERLIB_LOG) << fileName; - - QString actualFileName = fileName; - - if (fileName.isEmpty()) - { - QTemporaryFile tempFile; - tempFile.setFileTemplate("XXXXXX.dot"); - if (!tempFile.open()) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unable to open for temp file for writing " << tempFile.fileName() << endl; - exit(2); + qCDebug(KGRAPHVIEWERLIB_LOG) << fileName; + + QString actualFileName = fileName; + + if (fileName.isEmpty()) { + QTemporaryFile tempFile; + tempFile.setFileTemplate("XXXXXX.dot"); + if (!tempFile.open()) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unable to open for temp file for writing " << tempFile.fileName() << endl; + exit(2); + } + actualFileName = tempFile.fileName(); + qCDebug(KGRAPHVIEWERLIB_LOG) << "using " << actualFileName; + } + + QFile f(actualFileName); + if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unable to open file for writing " << fileName << endl; + exit(2); + } + + QTextStream stream(&f); + + stream << "digraph \""; + if (graph->id() != "\"\"") { + stream << graph->id(); + } + stream << "\" {\n"; + + stream << "graph [" << *graph << "]" << endl; + + /// @TODO Subgraph are not represented as needed in DotGraph, so it is not + /// possible to save them back : to be changed ! + // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing subgraphs"; + GraphSubgraphMap::const_iterator sit; + for (sit = graph->subgraphs().begin(); sit != graph->subgraphs().end(); ++sit) { + const GraphSubgraph &s = **sit; + (stream) << s; + } + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing nodes"; + GraphNodeMap::const_iterator nit; + for (nit = graph->nodes().begin(); nit != graph->nodes().end(); ++nit) { + (stream) << **nit; } - actualFileName = tempFile.fileName(); - qCDebug(KGRAPHVIEWERLIB_LOG) << "using " << actualFileName; - } - - QFile f(actualFileName); - if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unable to open file for writing " << fileName << endl; - exit(2); - } - - QTextStream stream(&f); - - stream << "digraph \""; - if (graph->id()!="\"\"") - { - stream <id(); - } - stream <<"\" {\n"; - - stream << "graph [" << *graph <<"]" << endl; - - /// @TODO Subgraph are not represented as needed in DotGraph, so it is not - /// possible to save them back : to be changed ! -// qCDebug(KGRAPHVIEWERLIB_LOG) << "writing subgraphs"; - GraphSubgraphMap::const_iterator sit; - for ( sit = graph->subgraphs().begin(); - sit != graph->subgraphs().end(); ++sit ) - { - const GraphSubgraph& s = **sit; - (stream) << s; - } - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "writing nodes"; - GraphNodeMap::const_iterator nit; - for ( nit = graph->nodes().begin(); - nit != graph->nodes().end(); ++nit ) - { - (stream) << **nit; - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edges"; - GraphEdgeMap::const_iterator eit; - for ( eit = graph->edges().begin(); - eit != graph->edges().end(); ++eit ) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edge" << (*eit)->id(); - stream << **eit; - } - - stream << "}\n"; - - f.close(); - return actualFileName; + + qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edges"; + GraphEdgeMap::const_iterator eit; + for (eit = graph->edges().begin(); eit != graph->edges().end(); ++eit) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edge" << (*eit)->id(); + stream << **eit; + } + + stream << "}\n"; + + f.close(); + return actualFileName; } -graph_t* GraphExporter::exportToGraphviz(const DotGraph* graph) +graph_t *GraphExporter::exportToGraphviz(const DotGraph *graph) { - Agdesc_t type = Agstrictundirected; - type.directed = graph->directed(); - type.strict = graph->strict(); - - graph_t* agraph = agopen((graph->id()!="\"\"")?graph->id().toUtf8().data():QString("unnamed").toUtf8().data(), type, nullptr); - - QTextStream stream; - graph->exportToGraphviz(agraph); - /// @TODO Subgraph are not represented as needed in DotGraph, so it is not - /// possible to save them back : to be changed ! - // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing subgraphs"; - GraphSubgraphMap::const_iterator sit; - for ( sit = graph->subgraphs().begin(); - sit != graph->subgraphs().end(); ++sit ) - { - const GraphSubgraph& s = **sit; - graph_t* subgraph = agsubg(agraph, s.id().toUtf8().data(), 1); - s.exportToGraphviz(subgraph); - } - - // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing nodes"; - GraphNodeMap::const_iterator nit; - foreach (GraphNode* n, graph->nodes()) - { - node_t* node = agnode(agraph, n->id().toUtf8().data(), 1); - n->exportToGraphviz(node); - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edges"; - GraphEdgeMap::const_iterator eit; - foreach (GraphEdge* e, graph->edges()) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edge" << e->id(); - edge_t* edge = agedge(agraph, agnode(agraph, e->fromNode()->id().toUtf8().data(), 0), - agnode(agraph, e->toNode()->id().toUtf8().data(), 0), nullptr, 1); - e->exportToGraphviz(edge); - } - - return agraph; + Agdesc_t type = Agstrictundirected; + type.directed = graph->directed(); + type.strict = graph->strict(); + + graph_t *agraph = agopen((graph->id() != "\"\"") ? graph->id().toUtf8().data() : QString("unnamed").toUtf8().data(), type, nullptr); + + QTextStream stream; + graph->exportToGraphviz(agraph); + /// @TODO Subgraph are not represented as needed in DotGraph, so it is not + /// possible to save them back : to be changed ! + // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing subgraphs"; + GraphSubgraphMap::const_iterator sit; + for (sit = graph->subgraphs().begin(); sit != graph->subgraphs().end(); ++sit) { + const GraphSubgraph &s = **sit; + graph_t *subgraph = agsubg(agraph, s.id().toUtf8().data(), 1); + s.exportToGraphviz(subgraph); + } + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "writing nodes"; + GraphNodeMap::const_iterator nit; + foreach (GraphNode *n, graph->nodes()) { + node_t *node = agnode(agraph, n->id().toUtf8().data(), 1); + n->exportToGraphviz(node); + } + + qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edges"; + GraphEdgeMap::const_iterator eit; + foreach (GraphEdge *e, graph->edges()) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "writing edge" << e->id(); + edge_t *edge = agedge(agraph, agnode(agraph, e->fromNode()->id().toUtf8().data(), 0), agnode(agraph, e->toNode()->id().toUtf8().data(), 0), nullptr, 1); + e->exportToGraphviz(edge); + } + + return agraph; } } diff --git a/src/part/graphnode.h b/src/part/graphnode.h --- a/src/part/graphnode.h +++ b/src/part/graphnode.h @@ -24,64 +24,69 @@ License as published by the Free Software Foundation, version 2. */ - /* * Graph Node model */ #ifndef GRAPH_NODE_H #define GRAPH_NODE_H -#include #include #include #include +#include #include -#include "dotrenderop.h" -#include "dotgrammar.h" -#include "graphelement.h" #include "canvaselement.h" #include "canvasnode.h" +#include "dotgrammar.h" +#include "dotrenderop.h" +#include "graphelement.h" namespace KGraphViewer { - class CanvasNode; /** * Colors and styles are DOT names */ class GraphNode : public GraphElement { - Q_OBJECT + Q_OBJECT public: - GraphNode(); - explicit GraphNode(const GraphNode& gn); - explicit GraphNode(node_t* gn); - - ~GraphNode() override {} - - inline CanvasNode* canvasNode() { return dynamic_cast(canvasElement()); } - inline const CanvasNode* canvasNode() const { return dynamic_cast(canvasElement()); } - inline void setCanvasNode(CanvasNode* cn) { setCanvasElement((CanvasElement*)cn); } - - void updateWithNode(const GraphNode& node); - void updateWithNode(node_t* node); + GraphNode(); + explicit GraphNode(const GraphNode &gn); + explicit GraphNode(node_t *gn); + + ~GraphNode() override + { + } + + inline CanvasNode *canvasNode() + { + return dynamic_cast(canvasElement()); + } + inline const CanvasNode *canvasNode() const + { + return dynamic_cast(canvasElement()); + } + inline void setCanvasNode(CanvasNode *cn) + { + setCanvasElement((CanvasElement *)cn); + } + + void updateWithNode(const GraphNode &node); + void updateWithNode(node_t *node); - private: }; /** A map associating the ids of a graph's nodes to these nodes */ -typedef QMap GraphNodeMap; +typedef QMap GraphNodeMap; -QTextStream& operator<<(QTextStream& s, const GraphNode& n); +QTextStream &operator<<(QTextStream &s, const GraphNode &n); } #endif - - - diff --git a/src/part/graphnode.cpp b/src/part/graphnode.cpp --- a/src/part/graphnode.cpp +++ b/src/part/graphnode.cpp @@ -24,96 +24,89 @@ License as published by the Free Software Foundation, version 2. */ - /* * Graph Node */ #include "graphnode.h" -#include "dotgraphview.h" -#include "pannerview.h" #include "canvasnode.h" #include "dotdefaults.h" +#include "dotgraphview.h" #include "kgraphviewerlib_debug.h" +#include "pannerview.h" #include #include namespace KGraphViewer { - // // GraphNode // -GraphNode::GraphNode() : - GraphElement() +GraphNode::GraphNode() + : GraphElement() { -// qCDebug(KGRAPHVIEWERLIB_LOG) ; + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } -GraphNode::GraphNode(const GraphNode& gn) : -GraphElement(gn) +GraphNode::GraphNode(const GraphNode &gn) + : GraphElement(gn) { - // qCDebug(KGRAPHVIEWERLIB_LOG) ; + // qCDebug(KGRAPHVIEWERLIB_LOG) ; } -GraphNode::GraphNode(node_t* gn) : GraphElement() +GraphNode::GraphNode(node_t *gn) + : GraphElement() { - updateWithNode(gn); + updateWithNode(gn); } -void GraphNode::updateWithNode(const GraphNode& node) +void GraphNode::updateWithNode(const GraphNode &node) { - qCDebug(KGRAPHVIEWERLIB_LOG) << id() << node.id(); - GraphElement::updateWithElement(node); - if (canvasNode()) - { - canvasNode()->computeBoundingRect(); - canvasNode()->modelChanged(); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "done"; + qCDebug(KGRAPHVIEWERLIB_LOG) << id() << node.id(); + GraphElement::updateWithElement(node); + if (canvasNode()) { + canvasNode()->computeBoundingRect(); + canvasNode()->modelChanged(); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "done"; } -void GraphNode::updateWithNode(node_t* node) +void GraphNode::updateWithNode(node_t *node) { - qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(node); - m_attributes["id"] = agnameof(node); - m_attributes["label"] = ND_label(node)->text; - - DotRenderOpVec ops; - // decrease mem peak - setRenderOperations(ops); - - if (agget(node, (char*)"_draw_")) - { - parse_renderop(agget(node, (char*)"_draw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); - } - if (agget(node, (char*)"_ldraw_")) - { - parse_renderop(agget(node, (char*)"_ldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); - } - - setRenderOperations(ops); - - Agsym_t *attr = agnxtattr(agraphof(node), AGNODE, nullptr); - while(attr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(node) << ":" << attr->name << agxget(node,attr); - m_attributes[attr->name] = agxget(node,attr); - attr = agnxtattr(agraphof(node), AGNODE, attr); - } + qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(node); + m_attributes["id"] = agnameof(node); + m_attributes["label"] = ND_label(node)->text; + + DotRenderOpVec ops; + // decrease mem peak + setRenderOperations(ops); + + if (agget(node, (char *)"_draw_")) { + parse_renderop(agget(node, (char *)"_draw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); + } + if (agget(node, (char *)"_ldraw_")) { + parse_renderop(agget(node, (char *)"_ldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); + } + + setRenderOperations(ops); + + Agsym_t *attr = agnxtattr(agraphof(node), AGNODE, nullptr); + while (attr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(node) << ":" << attr->name << agxget(node, attr); + m_attributes[attr->name] = agxget(node, attr); + attr = agnxtattr(agraphof(node), AGNODE, attr); + } } -QTextStream& operator<<(QTextStream& s, const GraphNode& n) +QTextStream &operator<<(QTextStream &s, const GraphNode &n) { - s << n.id() << " [" - << dynamic_cast(n) - <<"];"<(n) << "];" << endl; + return s; } } diff --git a/src/part/graphsubgraph.h b/src/part/graphsubgraph.h --- a/src/part/graphsubgraph.h +++ b/src/part/graphsubgraph.h @@ -27,76 +27,89 @@ #include #include "dotgrammar.h" -#include "graphelement.h" #include "dotrenderop.h" +#include "graphelement.h" #include namespace KGraphViewer { - - class CanvasSubgraph; class GraphSubgraph; -typedef QMap GraphSubgraphMap; - +typedef QMap GraphSubgraphMap; /** * Colors and styles are DOT names */ class GraphSubgraph : public GraphElement { - Q_OBJECT + Q_OBJECT public: - GraphSubgraph(); - explicit GraphSubgraph(graph_t* sg); - - ~GraphSubgraph() override {} - - inline const GraphSubgraphMap& subgraphs() const {return m_subgraphsMap;} - inline GraphSubgraphMap& subgraphs() {return m_subgraphsMap;} - - void updateWithSubgraph(const GraphSubgraph& subgraph); - void updateWithSubgraph(graph_t* subgraph); - - CanvasSubgraph* canvasSubgraph() { return (CanvasSubgraph*)canvasElement(); } - void setCanvasSubgraph(CanvasSubgraph* cs) { setCanvasElement((CanvasElement*)cs); } - - QString backColor() const override; - - inline const QList& content() const {return m_content;} - inline QList& content() {return m_content;} - inline void setContent(QList& c) {m_content=c;} - - void removeElement(GraphElement* element); - - /// Recursively walk through this subgraph and its subsubgraphs to find an element named id - /// @return the node found or 0 if there is no such node - GraphElement* elementNamed(const QString& id); - - - /// Recursively walk through this subgraph and its subsubgraphs to make - /// the given element selected or not depending on the selectValue parameter - /// and unselect other elements depending on the unselect others parameter - /// @return true if the given node was found - virtual bool setElementSelected( - GraphElement* element, - bool selectValue, - bool unselectOthers); - - void retrieveSelectedElementsIds(QList selection); - - private: - QList m_content; - GraphSubgraphMap m_subgraphsMap; + GraphSubgraph(); + explicit GraphSubgraph(graph_t *sg); + + ~GraphSubgraph() override + { + } + + inline const GraphSubgraphMap &subgraphs() const + { + return m_subgraphsMap; + } + inline GraphSubgraphMap &subgraphs() + { + return m_subgraphsMap; + } + + void updateWithSubgraph(const GraphSubgraph &subgraph); + void updateWithSubgraph(graph_t *subgraph); + + CanvasSubgraph *canvasSubgraph() + { + return (CanvasSubgraph *)canvasElement(); + } + void setCanvasSubgraph(CanvasSubgraph *cs) + { + setCanvasElement((CanvasElement *)cs); + } + + QString backColor() const override; + + inline const QList &content() const + { + return m_content; + } + inline QList &content() + { + return m_content; + } + inline void setContent(QList &c) + { + m_content = c; + } + + void removeElement(GraphElement *element); + + /// Recursively walk through this subgraph and its subsubgraphs to find an element named id + /// @return the node found or 0 if there is no such node + GraphElement *elementNamed(const QString &id); + + /// Recursively walk through this subgraph and its subsubgraphs to make + /// the given element selected or not depending on the selectValue parameter + /// and unselect other elements depending on the unselect others parameter + /// @return true if the given node was found + virtual bool setElementSelected(GraphElement *element, bool selectValue, bool unselectOthers); + + void retrieveSelectedElementsIds(QList selection); + +private: + QList m_content; + GraphSubgraphMap m_subgraphsMap; }; -QTextStream& operator<<(QTextStream& stream, const GraphSubgraph& s); +QTextStream &operator<<(QTextStream &stream, const GraphSubgraph &s); } #endif - - - diff --git a/src/part/graphsubgraph.cpp b/src/part/graphsubgraph.cpp --- a/src/part/graphsubgraph.cpp +++ b/src/part/graphsubgraph.cpp @@ -21,277 +21,216 @@ */ #include "graphsubgraph.h" -#include "graphnode.h" #include "canvassubgraph.h" #include "dotdefaults.h" +#include "graphnode.h" #include "kgraphviewerlib_debug.h" #include namespace KGraphViewer { - // // GraphSubgraph // -GraphSubgraph::GraphSubgraph() : - GraphElement(), m_content() +GraphSubgraph::GraphSubgraph() + : GraphElement() + , m_content() { } -GraphSubgraph::GraphSubgraph(graph_t* sg) : - GraphElement(), m_content() +GraphSubgraph::GraphSubgraph(graph_t *sg) + : GraphElement() + , m_content() { - updateWithSubgraph(sg); + updateWithSubgraph(sg); } -void GraphSubgraph::updateWithSubgraph(const GraphSubgraph& subgraph) +void GraphSubgraph::updateWithSubgraph(const GraphSubgraph &subgraph) { - qCDebug(KGRAPHVIEWERLIB_LOG) << id() << subgraph.id(); - GraphElement::updateWithElement(subgraph); - - bool found = false; - foreach (GraphElement* updatingge, subgraph.content()) - { - foreach (GraphElement* ge, content()) - { - if (ge->id() == updatingge->id()) - { - found = true; - if (dynamic_cast(ge)) - { - dynamic_cast(ge)->updateWithNode(*dynamic_cast(updatingge)); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << ngn->id(); + qCDebug(KGRAPHVIEWERLIB_LOG) << id() << subgraph.id(); + GraphElement::updateWithElement(subgraph); + + bool found = false; + foreach (GraphElement *updatingge, subgraph.content()) { + foreach (GraphElement *ge, content()) { + if (ge->id() == updatingge->id()) { + found = true; + if (dynamic_cast(ge)) { + dynamic_cast(ge)->updateWithNode(*dynamic_cast(updatingge)); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "node " << ngn->id(); + } else if (dynamic_cast(ge)) { + dynamic_cast(ge)->updateWithSubgraph(*dynamic_cast(updatingge)); + } else { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Updated element is neither a node nor a subgraph"; + } + break; + } } - else if (dynamic_cast(ge)) - { - dynamic_cast(ge)->updateWithSubgraph(*dynamic_cast(updatingge)); + if (!found) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; + if (dynamic_cast(updatingge)) { + GraphNode *newgn = new GraphNode(*dynamic_cast(updatingge)); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; + content().push_back(newgn); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; + } else if (dynamic_cast(updatingge)) { + GraphSubgraph *newsg = new GraphSubgraph(*dynamic_cast(updatingge)); + content().push_back(newsg); + } } - else - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Updated element is neither a node nor a subgraph"; - } - break; - } - } - if (!found) - { - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new"; - if (dynamic_cast(updatingge)) - { - GraphNode* newgn = new GraphNode(*dynamic_cast(updatingge)); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - content().push_back(newgn); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; - } - else if (dynamic_cast(updatingge)) - { - GraphSubgraph* newsg = new GraphSubgraph(*dynamic_cast(updatingge)); - content().push_back(newsg); - } } - } - if (canvasSubgraph()) - { - canvasSubgraph()->modelChanged(); - canvasSubgraph()->computeBoundingRect(); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "done"; + if (canvasSubgraph()) { + canvasSubgraph()->modelChanged(); + canvasSubgraph()->computeBoundingRect(); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "done"; } -void GraphSubgraph::updateWithSubgraph(graph_t* subgraph) +void GraphSubgraph::updateWithSubgraph(graph_t *subgraph) { - qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(subgraph); - m_attributes["id"] = agnameof(subgraph); - if (GD_label(subgraph)) - m_attributes["label"] = GD_label(subgraph)->text; - - DotRenderOpVec ops; - // decrease mem peak - setRenderOperations(ops); - - if (agget(subgraph, (char*)"_draw_")) - { - parse_renderop(agget(subgraph, (char*)"_draw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); - } - if (agget(subgraph, (char*)"_ldraw_")) - { - parse_renderop(agget(subgraph, (char*)"_ldraw_"), ops); - qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); - } - - setRenderOperations(ops); - - Agsym_t *attr = agnxtattr(subgraph, AGRAPH, nullptr); - while(attr) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(subgraph) << ":" << attr->name << agxget(subgraph,attr); - m_attributes[attr->name] = agxget(subgraph,attr); - attr = agnxtattr(subgraph, AGRAPH, attr); - } + qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(subgraph); + m_attributes["id"] = agnameof(subgraph); + if (GD_label(subgraph)) + m_attributes["label"] = GD_label(subgraph)->text; + + DotRenderOpVec ops; + // decrease mem peak + setRenderOperations(ops); + + if (agget(subgraph, (char *)"_draw_")) { + parse_renderop(agget(subgraph, (char *)"_draw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_draw_: element renderOperations size is now " << ops.size(); + } + if (agget(subgraph, (char *)"_ldraw_")) { + parse_renderop(agget(subgraph, (char *)"_ldraw_"), ops); + qCDebug(KGRAPHVIEWERLIB_LOG) << "_ldraw_: element renderOperations size is now " << ops.size(); + } + setRenderOperations(ops); - for (graph_t* sg = agfstsubg(subgraph); sg; sg = agnxtsubg(sg)) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "subsubgraph:" << agnameof(sg); - if ( subgraphs().contains(agnameof(sg))) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "known subsubgraph"; - // ??? - // nodes()[ngn->name]->setZ(ngn->z()); - subgraphs()[agnameof(sg)]->updateWithSubgraph(sg); - if (subgraphs()[agnameof(sg)]->canvasElement()) - { - // nodes()[ngn->id()]->canvasElement()->setGh(m_height); - } + Agsym_t *attr = agnxtattr(subgraph, AGRAPH, nullptr); + while (attr) { + qCDebug(KGRAPHVIEWERLIB_LOG) << agnameof(subgraph) << ":" << attr->name << agxget(subgraph, attr); + m_attributes[attr->name] = agxget(subgraph, attr); + attr = agnxtattr(subgraph, AGRAPH, attr); } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "new subsubgraph"; - GraphSubgraph* newsg = new GraphSubgraph(sg); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; - subgraphs().insert(agnameof(sg), newsg); - // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; + + for (graph_t *sg = agfstsubg(subgraph); sg; sg = agnxtsubg(sg)) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "subsubgraph:" << agnameof(sg); + if (subgraphs().contains(agnameof(sg))) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "known subsubgraph"; + // ??? + // nodes()[ngn->name]->setZ(ngn->z()); + subgraphs()[agnameof(sg)]->updateWithSubgraph(sg); + if (subgraphs()[agnameof(sg)]->canvasElement()) { + // nodes()[ngn->id()]->canvasElement()->setGh(m_height); + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "new subsubgraph"; + GraphSubgraph *newsg = new GraphSubgraph(sg); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new created"; + subgraphs().insert(agnameof(sg), newsg); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "new inserted"; + } } - - } } - QString GraphSubgraph::backColor() const { - if (m_attributes.find("bgcolor") != m_attributes.end()) - { - return m_attributes["bgcolor"]; - } - else if ( (m_attributes.find("style") != m_attributes.end()) - && (m_attributes["style"] == "filled") - && (m_attributes.find("color") != m_attributes.end()) ) - { - return m_attributes["color"]; - } - else if ((m_attributes.find("style") != m_attributes.end()) - && (m_attributes["style"] == "filled") - && (m_attributes.find("fillcolor") != m_attributes.end())) - { - return m_attributes["fillcolor"]; - } - else - { - return DOT_DEFAULT_BACKCOLOR; - } + if (m_attributes.find("bgcolor") != m_attributes.end()) { + return m_attributes["bgcolor"]; + } else if ((m_attributes.find("style") != m_attributes.end()) && (m_attributes["style"] == "filled") && (m_attributes.find("color") != m_attributes.end())) { + return m_attributes["color"]; + } else if ((m_attributes.find("style") != m_attributes.end()) && (m_attributes["style"] == "filled") && (m_attributes.find("fillcolor") != m_attributes.end())) { + return m_attributes["fillcolor"]; + } else { + return DOT_DEFAULT_BACKCOLOR; + } } -void GraphSubgraph::removeElement(GraphElement* element) +void GraphSubgraph::removeElement(GraphElement *element) { - m_content.removeAll(element); + m_content.removeAll(element); } -GraphElement* GraphSubgraph::elementNamed(const QString& id) +GraphElement *GraphSubgraph::elementNamed(const QString &id) { - if (this->id() == id) return this; - foreach (GraphElement* element, content()) - { - if (element->id() == id) - { - return element; - } - else if (dynamic_cast(element)) - { - GraphElement* subgraphElement = dynamic_cast(element)->elementNamed(id); - if (subgraphElement) - { - return subgraphElement; - } + if (this->id() == id) + return this; + foreach (GraphElement *element, content()) { + if (element->id() == id) { + return element; + } else if (dynamic_cast(element)) { + GraphElement *subgraphElement = dynamic_cast(element)->elementNamed(id); + if (subgraphElement) { + return subgraphElement; + } + } } - } - return nullptr; + return nullptr; } -bool GraphSubgraph::setElementSelected( - GraphElement* element, - bool selectValue, - bool unselectOthers) +bool GraphSubgraph::setElementSelected(GraphElement *element, bool selectValue, bool unselectOthers) { - if (element) - qCDebug(KGRAPHVIEWERLIB_LOG) << element->id() << selectValue << unselectOthers; - bool res = false; - if (element == this) - { - if (isSelected() != selectValue) - { - setSelected(selectValue); - canvasElement()->update(); - } - res = true; - } - else if (isSelected() && unselectOthers) - { - setSelected(false); - canvasElement()->update(); - } - foreach (GraphElement* el, content()) - { - if (dynamic_cast(el)) - { - bool subres = dynamic_cast(el)->setElementSelected(element, selectValue, unselectOthers); - if (!res) res = subres; - } - else if (element == el) - { - res = true; - if (el->isSelected() != selectValue) - { - el->setSelected(selectValue); - el->canvasElement()->update(); - } + if (element) + qCDebug(KGRAPHVIEWERLIB_LOG) << element->id() << selectValue << unselectOthers; + bool res = false; + if (element == this) { + if (isSelected() != selectValue) { + setSelected(selectValue); + canvasElement()->update(); + } + res = true; + } else if (isSelected() && unselectOthers) { + setSelected(false); + canvasElement()->update(); } - else - { - if (unselectOthers && el->isSelected()) - { - el->setSelected(false); - el->canvasElement()->update(); - } + foreach (GraphElement *el, content()) { + if (dynamic_cast(el)) { + bool subres = dynamic_cast(el)->setElementSelected(element, selectValue, unselectOthers); + if (!res) + res = subres; + } else if (element == el) { + res = true; + if (el->isSelected() != selectValue) { + el->setSelected(selectValue); + el->canvasElement()->update(); + } + } else { + if (unselectOthers && el->isSelected()) { + el->setSelected(false); + el->canvasElement()->update(); + } + } } - } - return res; + return res; } void GraphSubgraph::retrieveSelectedElementsIds(QList selection) { - if (isSelected()) - { - selection.push_back(id()); - } - foreach (GraphElement* el, content()) - { - if (dynamic_cast(el)) - { - dynamic_cast(el)->retrieveSelectedElementsIds(selection); + if (isSelected()) { + selection.push_back(id()); } - else if (el->isSelected()) - { - selection.push_back(el->id()); + foreach (GraphElement *el, content()) { + if (dynamic_cast(el)) { + dynamic_cast(el)->retrieveSelectedElementsIds(selection); + } else if (el->isSelected()) { + selection.push_back(el->id()); + } } - } } -QTextStream& operator<<(QTextStream& s, const GraphSubgraph& sg) +QTextStream &operator<<(QTextStream &s, const GraphSubgraph &sg) { - s << "subgraph " << sg.id() << " {" << endl - << "graph [ " - << dynamic_cast(sg) - << " ] " << endl; - foreach (const GraphElement* el, sg.content()) - { - s << *(dynamic_cast(el)); - } - s <<"}"<(sg) << " ] " << endl; + foreach (const GraphElement *el, sg.content()) { + s << *(dynamic_cast(el)); + } + s << "}" << endl; + return s; } } diff --git a/src/part/kgraphviewer_interface.h b/src/part/kgraphviewer_interface.h --- a/src/part/kgraphviewer_interface.h +++ b/src/part/kgraphviewer_interface.h @@ -19,20 +19,19 @@ #ifndef KGRAPHVIEWER_INTERFACE_H #define KGRAPHVIEWER_INTERFACE_H -#include #include +#include namespace KParts { - class Part; +class Part; } class QCursor; extern "C" { - typedef struct Agraph_s graph_t; +typedef struct Agraph_s graph_t; } - namespace KGraphViewer { /** @@ -44,7 +43,7 @@ * some signals you can connect to. They aren't in this class cause * we can't have signals without having a QObject, which * KGraphViewerInterface is not. To see a list of signals, take a look at kgraphviewer_part.h - * + * * See the example code below for how to connect to these.. * * Use it like this: @@ -66,72 +65,71 @@ * \endcode * * @author Milian Wolff - * - * + * + * * WARNING: This is highly experimental and no kind of BC guarantees are given! * TODO: documentation */ class KGraphViewerInterface { public: - enum LayoutMethod - { - ExternalProgram, - InternalLibrary - }; - - virtual void setLayoutMethod(LayoutMethod method) = 0; - virtual void zoomIn() = 0; - virtual void zoomOut() = 0; - virtual void zoomBy(double factor) = 0; - virtual void setZoomFactor(double factor) = 0; - - enum PannerPosition { TopLeft, TopRight, BottomLeft, BottomRight, Auto }; - virtual void setPannerPosition(PannerPosition position) = 0; - virtual void setPannerEnabled(bool enabled) = 0; - - virtual void setLayoutCommand(const QString& command) = 0; - - virtual void selectNode(const QString& nodeId) = 0; - virtual void centerOnNode(const QString& nodeId) = 0; - - // Slots - virtual void slotHide(KParts::Part* part) = 0; - virtual void slotUpdate() = 0; - virtual void prepareAddNewElement(const QMap& attribs) = 0; - virtual void prepareAddNewEdge(const QMap& attribs) = 0; - virtual void setReadOnly() = 0; - virtual void setReadWrite() = 0; - virtual void saveTo(const QString& fileName) = 0; - virtual void slotRemoveNode(const QString&) = 0; - virtual void slotRemoveNodeFromSubgraph(const QString& nodeName, const QString& subgraphName) = 0; - virtual void slotRemoveSubgraph(const QString&) = 0; - virtual void slotAddAttribute(const QString&) = 0; - virtual void slotSetAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue) = 0; - virtual void slotRemoveAttribute(const QString&,const QString&) = 0; - virtual void slotSetGraphAttributes(const QMap& attribs) = 0; - virtual void slotAddNewNode(const QMap& attribs) = 0; - virtual void slotAddNewNodeToSubgraph(const QMap& attribs, const QString& subgraph) = 0; - virtual void slotAddExistingNodeToSubgraph(const QMap& attribs, const QString& subgraph) = 0; - virtual void slotMoveExistingNodeToMainGraph(const QMap& attribs) = 0; - virtual void slotAddNewSubgraph(const QMap& attribs) = 0; - virtual void slotAddNewEdge(const QString& src, const QString& tgt, const QMap& attribs) = 0; - virtual void slotRemoveEdge(const QString& id) = 0; - virtual void slotRemoveElement(const QString& id) = 0; - virtual void slotSelectNode(const QString&) = 0; - virtual void slotSetHighlighting(bool highlightingValue) = 0; - virtual void slotPrepareToSelect() = 0; - virtual void slotSetCursor(const QCursor& cursor) = 0; - virtual void slotUnsetCursor() = 0; - virtual void slotSetLayoutMethod(LayoutMethod method) = 0; - virtual void slotRenameNode(const QString& oldName, const QString& newName) = 0; - virtual bool slotLoadLibrary(graph_t* graph) = 0; - virtual void setBackgroundColor(const QColor& color) = 0; - + enum LayoutMethod { ExternalProgram, InternalLibrary }; + + virtual void setLayoutMethod(LayoutMethod method) = 0; + virtual void zoomIn() = 0; + virtual void zoomOut() = 0; + virtual void zoomBy(double factor) = 0; + virtual void setZoomFactor(double factor) = 0; + + enum PannerPosition { TopLeft, TopRight, BottomLeft, BottomRight, Auto }; + virtual void setPannerPosition(PannerPosition position) = 0; + virtual void setPannerEnabled(bool enabled) = 0; + + virtual void setLayoutCommand(const QString &command) = 0; + + virtual void selectNode(const QString &nodeId) = 0; + virtual void centerOnNode(const QString &nodeId) = 0; + + // Slots + virtual void slotHide(KParts::Part *part) = 0; + virtual void slotUpdate() = 0; + virtual void prepareAddNewElement(const QMap &attribs) = 0; + virtual void prepareAddNewEdge(const QMap &attribs) = 0; + virtual void setReadOnly() = 0; + virtual void setReadWrite() = 0; + virtual void saveTo(const QString &fileName) = 0; + virtual void slotRemoveNode(const QString &) = 0; + virtual void slotRemoveNodeFromSubgraph(const QString &nodeName, const QString &subgraphName) = 0; + virtual void slotRemoveSubgraph(const QString &) = 0; + virtual void slotAddAttribute(const QString &) = 0; + virtual void slotSetAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue) = 0; + virtual void slotRemoveAttribute(const QString &, const QString &) = 0; + virtual void slotSetGraphAttributes(const QMap &attribs) = 0; + virtual void slotAddNewNode(const QMap &attribs) = 0; + virtual void slotAddNewNodeToSubgraph(const QMap &attribs, const QString &subgraph) = 0; + virtual void slotAddExistingNodeToSubgraph(const QMap &attribs, const QString &subgraph) = 0; + virtual void slotMoveExistingNodeToMainGraph(const QMap &attribs) = 0; + virtual void slotAddNewSubgraph(const QMap &attribs) = 0; + virtual void slotAddNewEdge(const QString &src, const QString &tgt, const QMap &attribs) = 0; + virtual void slotRemoveEdge(const QString &id) = 0; + virtual void slotRemoveElement(const QString &id) = 0; + virtual void slotSelectNode(const QString &) = 0; + virtual void slotSetHighlighting(bool highlightingValue) = 0; + virtual void slotPrepareToSelect() = 0; + virtual void slotSetCursor(const QCursor &cursor) = 0; + virtual void slotUnsetCursor() = 0; + virtual void slotSetLayoutMethod(LayoutMethod method) = 0; + virtual void slotRenameNode(const QString &oldName, const QString &newName) = 0; + virtual bool slotLoadLibrary(graph_t *graph) = 0; + virtual void setBackgroundColor(const QColor &color) = 0; protected: - KGraphViewerInterface() {} - virtual ~KGraphViewerInterface() {} + KGraphViewerInterface() + { + } + virtual ~KGraphViewerInterface() + { + } }; } diff --git a/src/part/kgraphviewer_part.h b/src/part/kgraphviewer_part.h --- a/src/part/kgraphviewer_part.h +++ b/src/part/kgraphviewer_part.h @@ -19,9 +19,9 @@ #ifndef _KGRAPHVIEWERPART_H_ #define _KGRAPHVIEWERPART_H_ -#include #include #include +#include #include "kgraphviewer_interface.h" @@ -31,7 +31,6 @@ namespace KGraphViewer { - class DotGraph; class KGraphViewerPartPrivate; @@ -48,101 +47,95 @@ Q_OBJECT Q_INTERFACES(KGraphViewer::KGraphViewerInterface) -//BEGIN: KGraphViewerInterface + // BEGIN: KGraphViewerInterface public: void setLayoutMethod(LayoutMethod method) override; - void centerOnNode(const QString& nodeId) override; - void selectNode(const QString& nodeId) override; - void setLayoutCommand(const QString& command) override; + void centerOnNode(const QString &nodeId) override; + void selectNode(const QString &nodeId) override; + void setLayoutCommand(const QString &command) override; void setPannerPosition(PannerPosition position) override; void setPannerEnabled(bool enabled) override; void zoomBy(double factor) override; void setZoomFactor(double factor) override; void zoomIn() override; void zoomOut() override; - void setBackgroundColor(const QColor& color) override; + void setBackgroundColor(const QColor &color) override; public: /** * Default constructor */ KGraphViewerPart(QWidget *parentWidget, QObject *parent, const QVariantList &); - /** * Destructor */ ~KGraphViewerPart() override; - // Return information about the part - static KAboutData* createAboutData(); + // Return information about the part + static KAboutData *createAboutData(); Q_SIGNALS: - void graphLoaded(); - void newNodeAdded(const QString&); - void newEdgeAdded(const QString&, const QString&); - /** signals that the user has activated a remove edge command */ - void removeEdge(const QString&); - /** signals that the user has activated a remove element command */ - void removeElement(const QString&); - void selectionIs(const QList, const QPoint&); - void contextMenuEvent(const QString&, const QPoint&); - /** let the application tweak the created edge if necessary */ - void newEdgeFinished( - const QString&, const QString&, - const QMap&); - /// emitted when the mouse enters a node, a subgraph or an edge. The parameter is the hovered element id - void hoverEnter(const QString&); - /// emitted when the mouse leaves a node, a subgraph or an edge. The parameter is the hovered element id - void hoverLeave(const QString&); + void graphLoaded(); + void newNodeAdded(const QString &); + void newEdgeAdded(const QString &, const QString &); + /** signals that the user has activated a remove edge command */ + void removeEdge(const QString &); + /** signals that the user has activated a remove element command */ + void removeElement(const QString &); + void selectionIs(const QList, const QPoint &); + void contextMenuEvent(const QString &, const QPoint &); + /** let the application tweak the created edge if necessary */ + void newEdgeFinished(const QString &, const QString &, const QMap &); + /// emitted when the mouse enters a node, a subgraph or an edge. The parameter is the hovered element id + void hoverEnter(const QString &); + /// emitted when the mouse leaves a node, a subgraph or an edge. The parameter is the hovered element id + void hoverLeave(const QString &); public Q_SLOTS: - void slotHide(KParts::Part* part) override; - void slotUpdate() override; - void prepareAddNewElement(const QMap& attribs) override; - void prepareAddNewEdge(const QMap& attribs) override; - void setReadOnly() override; - void setReadWrite() override; - void saveTo(const QString& fileName) override; - void slotRemoveNode(const QString&) override; - void slotRemoveNodeFromSubgraph( - const QString& nodeName, - const QString& subgraphName) override; - void slotRemoveSubgraph(const QString&) override; - void slotAddAttribute(const QString&) override; - void slotSetAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue) override; - void slotRemoveAttribute(const QString&,const QString&) override; - void slotSetGraphAttributes(const QMap& attribs) override; - void slotAddNewNode(const QMap& attribs) override; - void slotAddNewNodeToSubgraph(const QMap& attribs, const QString& subgraph) override; - void slotAddExistingNodeToSubgraph(const QMap& attribs, const QString& subgraph) override; - void slotMoveExistingNodeToMainGraph(const QMap& attribs) override; - void slotAddNewSubgraph(const QMap& attribs) override; - void slotAddNewEdge(const QString& src, const QString& tgt, const QMap& attribs) override; - void slotRemoveEdge(const QString& id) override; - void slotRemoveElement(const QString& id) override; - void slotSelectNode(const QString&) override; - void slotSetHighlighting(bool highlightingValue) override; - void slotPrepareToSelect() override; - void slotSetCursor(const QCursor& cursor) override; - void slotUnsetCursor() override; - bool closeUrl() override; - bool slotLoadLibrary(graph_t* graph) override; - void slotSetLayoutMethod(LayoutMethod method) override; - void slotRenameNode(const QString& oldNodeName, const QString& newNodeName) override; - -/* inline DotGraph* graph() {return m_widget->graph();} - inline const DotGraph* graph() const {return m_widget->graph();}*/ - - - protected: + void slotHide(KParts::Part *part) override; + void slotUpdate() override; + void prepareAddNewElement(const QMap &attribs) override; + void prepareAddNewEdge(const QMap &attribs) override; + void setReadOnly() override; + void setReadWrite() override; + void saveTo(const QString &fileName) override; + void slotRemoveNode(const QString &) override; + void slotRemoveNodeFromSubgraph(const QString &nodeName, const QString &subgraphName) override; + void slotRemoveSubgraph(const QString &) override; + void slotAddAttribute(const QString &) override; + void slotSetAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue) override; + void slotRemoveAttribute(const QString &, const QString &) override; + void slotSetGraphAttributes(const QMap &attribs) override; + void slotAddNewNode(const QMap &attribs) override; + void slotAddNewNodeToSubgraph(const QMap &attribs, const QString &subgraph) override; + void slotAddExistingNodeToSubgraph(const QMap &attribs, const QString &subgraph) override; + void slotMoveExistingNodeToMainGraph(const QMap &attribs) override; + void slotAddNewSubgraph(const QMap &attribs) override; + void slotAddNewEdge(const QString &src, const QString &tgt, const QMap &attribs) override; + void slotRemoveEdge(const QString &id) override; + void slotRemoveElement(const QString &id) override; + void slotSelectNode(const QString &) override; + void slotSetHighlighting(bool highlightingValue) override; + void slotPrepareToSelect() override; + void slotSetCursor(const QCursor &cursor) override; + void slotUnsetCursor() override; + bool closeUrl() override; + bool slotLoadLibrary(graph_t *graph) override; + void slotSetLayoutMethod(LayoutMethod method) override; + void slotRenameNode(const QString &oldNodeName, const QString &newNodeName) override; + + /* inline DotGraph* graph() {return m_widget->graph();} + inline const DotGraph* graph() const {return m_widget->graph();}*/ + +protected: /** * This must be implemented by each part. Use openUrl to open a file */ bool openFile() override; private: - KGraphViewerPartPrivate * const d; + KGraphViewerPartPrivate *const d; }; } diff --git a/src/part/kgraphviewer_part.cpp b/src/part/kgraphviewer_part.cpp --- a/src/part/kgraphviewer_part.cpp +++ b/src/part/kgraphviewer_part.cpp @@ -16,135 +16,113 @@ 02110-1301, USA */ - #include "kgraphviewer_part.h" -#include "kgraphviewerlib_debug.h" -#include "dotgraphview.h" -#include "dotgraph.h" #include "config-kgraphviewer.h" +#include "dotgraph.h" +#include "dotgraphview.h" +#include "kgraphviewerlib_debug.h" +#include #include -#include -#include -#include -#include -#include +#include #include +#include #include -#include #include #include -#include -#include #include +#include +#include +#include +#include +#include #include - // #include "kgraphviewersettings.h" #include "kgraphviewer_partsettings.h" namespace KGraphViewer { - K_PLUGIN_FACTORY(KGraphViewerPartFactory, registerPlugin();) class KGraphViewerPartPrivate { public: - KGraphViewerPartPrivate() : m_watch(new KDirWatch()), m_layoutMethod(KGraphViewerInterface::InternalLibrary) - { - - } - - ~KGraphViewerPartPrivate() - { - delete m_watch; - } - - DotGraphView *m_widget; - KDirWatch* m_watch; - KGraphViewerPart::LayoutMethod m_layoutMethod; - + KGraphViewerPartPrivate() + : m_watch(new KDirWatch()) + , m_layoutMethod(KGraphViewerInterface::InternalLibrary) + { + } + + ~KGraphViewerPartPrivate() + { + delete m_watch; + } + + DotGraphView *m_widget; + KDirWatch *m_watch; + KGraphViewerPart::LayoutMethod m_layoutMethod; }; -KGraphViewerPart::KGraphViewerPart( QWidget *parentWidget, QObject *parent, const QVariantList & ) -: KParts::ReadOnlyPart(parent), d(new KGraphViewerPartPrivate()) -{ - /* set the component name (1st argument) so that the XMLGUI .rc - file is found also when this part is called from applications - different then kgraphviewer (like kgrapheditor and konqueror). - */ - KAboutData aboutData( - QStringLiteral("kgraphviewer"), - i18n("KGraphViewerPart"), - KGRAPHVIEWER_VERSION_STRING, - i18n("Graphviz DOT files viewer"), - KAboutLicense::GPL, - i18n("(c) 2005-2006, Gaƫl de Chalendar ") - ); - setComponentData(aboutData, false); - - // set our XML-UI resource file - setXMLFile(QStringLiteral("kgraphviewer_part.rc"), true); - - // this should be your custom internal widget - d->m_widget = new DotGraphView( actionCollection(), parentWidget); - d->m_widget->initEmpty(); - d->m_widget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - connect(d->m_widget, &DotGraphView::graphLoaded, - this, &KGraphViewerPart::graphLoaded); - connect(d->m_widget, &DotGraphView::newEdgeAdded, - this, &KGraphViewerPart::newEdgeAdded); - connect(d->m_widget, &DotGraphView::newNodeAdded, - this, &KGraphViewerPart::newNodeAdded); - connect(d->m_widget, &DotGraphView::removeEdge, - this, &KGraphViewerPart::removeEdge); - connect(d->m_widget, &DotGraphView::removeElement, - this, &KGraphViewerPart::removeElement); - connect(d->m_widget, &DotGraphView::selectionIs, - this, &KGraphViewerPart::selectionIs); - connect(d->m_widget, static_cast(&DotGraphView::contextMenuEvent), - this, &KGraphViewerPart::contextMenuEvent); - connect(d->m_widget, &DotGraphView::newEdgeFinished, - this, &KGraphViewerPart::newEdgeFinished); - connect(d->m_widget, &DotGraphView::hoverEnter, - this, &KGraphViewerPart::hoverEnter); - connect(d->m_widget, &DotGraphView::hoverLeave, - this, &KGraphViewerPart::hoverLeave); - - - - - // notify the part that this is our internal widget - setWidget(d->m_widget); - - QAction* printAct = actionCollection()->addAction(KStandardAction::Print, "file_print", d->m_widget, SLOT(print())); - actionCollection()->setDefaultShortcut(printAct, Qt::ControlModifier + Qt::Key_P); - printAct->setWhatsThis(i18n("Print the graph using current page setup settings")); - - QAction* printPreviewAct = actionCollection()->addAction(KStandardAction::PrintPreview, "file_print_preview", d->m_widget, SLOT(printPreview())); - actionCollection()->setDefaultShortcut(printPreviewAct, Qt::ControlModifier + Qt::ShiftModifier + Qt::Key_P); - printPreviewAct->setWhatsThis(i18n("Open the print preview window")); - -// KAction* pagesetupAct = new KAction(i18n("&Page setup"), this); //actionCollection(), "file_page_setup"); - QAction* pagesetupAct = actionCollection()->addAction("file_page_setup", d->m_widget, SLOT(pageSetup())); - pagesetupAct->setText(i18n("Page setup")); - pagesetupAct->setWhatsThis(i18n("Opens the Page Setup dialog to allow graph printing to be setup")); - - QAction* redisplayAct = actionCollection()->addAction(KStandardAction::Redisplay, "view_redisplay", d->m_widget, SLOT(reload())); - redisplayAct->setWhatsThis(i18n("Reload the current graph from file")); - redisplayAct->setShortcut(Qt::Key_F5); - - QAction* zoomInAct = actionCollection()->addAction(KStandardAction::ZoomIn, "view_zoom_in", d->m_widget, SLOT(zoomIn())); - // xgettext: no-c-format - zoomInAct->setWhatsThis(i18n("Zoom in by 10% on the currently viewed graph")); - zoomInAct->setShortcut(Qt::Key_F7); - - QAction* zoomOutAct = actionCollection()->addAction(KStandardAction::ZoomOut, "view_zoom_out", d->m_widget, SLOT(zoomOut())); - // xgettext: no-c-format - zoomOutAct->setWhatsThis(i18n("Zoom out by 10% from the currently viewed graph")); - zoomOutAct->setShortcut(Qt::Key_F8); +KGraphViewerPart::KGraphViewerPart(QWidget *parentWidget, QObject *parent, const QVariantList &) + : KParts::ReadOnlyPart(parent) + , d(new KGraphViewerPartPrivate()) +{ + /* set the component name (1st argument) so that the XMLGUI .rc + file is found also when this part is called from applications + different then kgraphviewer (like kgrapheditor and konqueror). + */ + KAboutData aboutData(QStringLiteral("kgraphviewer"), i18n("KGraphViewerPart"), KGRAPHVIEWER_VERSION_STRING, i18n("Graphviz DOT files viewer"), KAboutLicense::GPL, i18n("(c) 2005-2006, Gaƫl de Chalendar ")); + setComponentData(aboutData, false); + + // set our XML-UI resource file + setXMLFile(QStringLiteral("kgraphviewer_part.rc"), true); + + // this should be your custom internal widget + d->m_widget = new DotGraphView(actionCollection(), parentWidget); + d->m_widget->initEmpty(); + d->m_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + connect(d->m_widget, &DotGraphView::graphLoaded, this, &KGraphViewerPart::graphLoaded); + connect(d->m_widget, &DotGraphView::newEdgeAdded, this, &KGraphViewerPart::newEdgeAdded); + connect(d->m_widget, &DotGraphView::newNodeAdded, this, &KGraphViewerPart::newNodeAdded); + connect(d->m_widget, &DotGraphView::removeEdge, this, &KGraphViewerPart::removeEdge); + connect(d->m_widget, &DotGraphView::removeElement, this, &KGraphViewerPart::removeElement); + connect(d->m_widget, &DotGraphView::selectionIs, this, &KGraphViewerPart::selectionIs); + connect(d->m_widget, static_cast(&DotGraphView::contextMenuEvent), this, &KGraphViewerPart::contextMenuEvent); + connect(d->m_widget, &DotGraphView::newEdgeFinished, this, &KGraphViewerPart::newEdgeFinished); + connect(d->m_widget, &DotGraphView::hoverEnter, this, &KGraphViewerPart::hoverEnter); + connect(d->m_widget, &DotGraphView::hoverLeave, this, &KGraphViewerPart::hoverLeave); + + // notify the part that this is our internal widget + setWidget(d->m_widget); + + QAction *printAct = actionCollection()->addAction(KStandardAction::Print, "file_print", d->m_widget, SLOT(print())); + actionCollection()->setDefaultShortcut(printAct, Qt::ControlModifier + Qt::Key_P); + printAct->setWhatsThis(i18n("Print the graph using current page setup settings")); + + QAction *printPreviewAct = actionCollection()->addAction(KStandardAction::PrintPreview, "file_print_preview", d->m_widget, SLOT(printPreview())); + actionCollection()->setDefaultShortcut(printPreviewAct, Qt::ControlModifier + Qt::ShiftModifier + Qt::Key_P); + printPreviewAct->setWhatsThis(i18n("Open the print preview window")); + + // KAction* pagesetupAct = new KAction(i18n("&Page setup"), this); //actionCollection(), "file_page_setup"); + QAction *pagesetupAct = actionCollection()->addAction("file_page_setup", d->m_widget, SLOT(pageSetup())); + pagesetupAct->setText(i18n("Page setup")); + pagesetupAct->setWhatsThis(i18n("Opens the Page Setup dialog to allow graph printing to be setup")); + + QAction *redisplayAct = actionCollection()->addAction(KStandardAction::Redisplay, "view_redisplay", d->m_widget, SLOT(reload())); + redisplayAct->setWhatsThis(i18n("Reload the current graph from file")); + redisplayAct->setShortcut(Qt::Key_F5); + + QAction *zoomInAct = actionCollection()->addAction(KStandardAction::ZoomIn, "view_zoom_in", d->m_widget, SLOT(zoomIn())); + // xgettext: no-c-format + zoomInAct->setWhatsThis(i18n("Zoom in by 10% on the currently viewed graph")); + zoomInAct->setShortcut(Qt::Key_F7); + + QAction *zoomOutAct = actionCollection()->addAction(KStandardAction::ZoomOut, "view_zoom_out", d->m_widget, SLOT(zoomOut())); + // xgettext: no-c-format + zoomOutAct->setWhatsThis(i18n("Zoom out by 10% from the currently viewed graph")); + zoomOutAct->setShortcut(Qt::Key_F8); } /*DotGraph* KGraphViewerPart::graph() @@ -158,260 +136,256 @@ } */ -void KGraphViewerPart::setBackgroundColor(const QColor& color) +void KGraphViewerPart::setBackgroundColor(const QColor &color) { - d->m_widget->setBackgroundColor(color); + d->m_widget->setBackgroundColor(color); } bool KGraphViewerPart::closeUrl() { - return d->m_widget->initEmpty(); + return d->m_widget->initEmpty(); } -bool KGraphViewerPart::slotLoadLibrary(graph_t* graph) -{ - bool res = d->m_widget->slotLoadLibrary(graph); - if (res) - d->m_widget->show(); - return res; +bool KGraphViewerPart::slotLoadLibrary(graph_t *graph) +{ + bool res = d->m_widget->slotLoadLibrary(graph); + if (res) + d->m_widget->show(); + return res; } KGraphViewerPart::~KGraphViewerPart() { - delete d; + delete d; } bool KGraphViewerPart::openFile() { - qCDebug(KGRAPHVIEWERLIB_LOG) << " " << localFilePath(); - // d->m_widget->loadedDot( localFilePath() ); - switch (d->m_layoutMethod) - { + qCDebug(KGRAPHVIEWERLIB_LOG) << " " << localFilePath(); + // d->m_widget->loadedDot( localFilePath() ); + switch (d->m_layoutMethod) { case ExternalProgram: - if (!d->m_widget->loadDot(localFilePath())) - return false; - break; + if (!d->m_widget->loadDot(localFilePath())) + return false; + break; case InternalLibrary: - // kpart expects loading to be done sync in this method - if (!d->m_widget->loadLibrarySync(localFilePath())) - return false; - break; + // kpart expects loading to be done sync in this method + if (!d->m_widget->loadLibrarySync(localFilePath())) + return false; + break; default: - qCWarning(KGRAPHVIEWERLIB_LOG) << "Unsupported layout method " << d->m_layoutMethod; - } - - // deletes the existing file watcher because we have no way know here the name of the - // previously watched file and thus we cannot use removeFile... :-( - delete d->m_watch; - d->m_watch = new KDirWatch(); - - // qCDebug(KGRAPHVIEWERLIB_LOG) << "Watching file " << localFilePath(); - d->m_watch->addFile(localFilePath()); - connect(d->m_watch, &KDirWatch::dirty, d->m_widget, &DotGraphView::dirty); - QString label = localFilePath().section('/',-1,-1); - - d->m_widget->show(); - return true; -} - -void KGraphViewerPart::slotHide(KParts::Part* part) -{ - if (part == this) - { - d->m_widget->hideToolsWindows(); - } + qCWarning(KGRAPHVIEWERLIB_LOG) << "Unsupported layout method " << d->m_layoutMethod; + } + + // deletes the existing file watcher because we have no way know here the name of the + // previously watched file and thus we cannot use removeFile... :-( + delete d->m_watch; + d->m_watch = new KDirWatch(); + + // qCDebug(KGRAPHVIEWERLIB_LOG) << "Watching file " << localFilePath(); + d->m_watch->addFile(localFilePath()); + connect(d->m_watch, &KDirWatch::dirty, d->m_widget, &DotGraphView::dirty); + QString label = localFilePath().section('/', -1, -1); + + d->m_widget->show(); + return true; +} + +void KGraphViewerPart::slotHide(KParts::Part *part) +{ + if (part == this) { + d->m_widget->hideToolsWindows(); + } } void KGraphViewerPart::slotUpdate() { - d->m_widget->slotUpdate(); + d->m_widget->slotUpdate(); } -void KGraphViewerPart::prepareAddNewElement(const QMap& attribs) +void KGraphViewerPart::prepareAddNewElement(const QMap &attribs) { - d->m_widget->prepareAddNewElement(attribs); + d->m_widget->prepareAddNewElement(attribs); } -void KGraphViewerPart::slotSetGraphAttributes(const QMap& attribs) +void KGraphViewerPart::slotSetGraphAttributes(const QMap &attribs) { - d->m_widget->graph()->setGraphAttributes(attribs); + d->m_widget->graph()->setGraphAttributes(attribs); } -void KGraphViewerPart::slotAddNewNode(const QMap& attribs) +void KGraphViewerPart::slotAddNewNode(const QMap &attribs) { - d->m_widget->graph()->addNewNode(attribs); + d->m_widget->graph()->addNewNode(attribs); } -void KGraphViewerPart::slotAddNewSubgraph(const QMap& attribs) +void KGraphViewerPart::slotAddNewSubgraph(const QMap &attribs) { - d->m_widget->graph()->addNewSubgraph(attribs); + d->m_widget->graph()->addNewSubgraph(attribs); } -void KGraphViewerPart::slotAddNewNodeToSubgraph(const QMap& attribs, - const QString& subgraph) +void KGraphViewerPart::slotAddNewNodeToSubgraph(const QMap &attribs, const QString &subgraph) { - d->m_widget->graph()->addNewNodeToSubgraph(attribs, subgraph); + d->m_widget->graph()->addNewNodeToSubgraph(attribs, subgraph); } -void KGraphViewerPart::slotAddExistingNodeToSubgraph(const QMap& attribs,const QString& subgraph) +void KGraphViewerPart::slotAddExistingNodeToSubgraph(const QMap &attribs, const QString &subgraph) { - d->m_widget->graph()->addExistingNodeToSubgraph(attribs, subgraph); + d->m_widget->graph()->addExistingNodeToSubgraph(attribs, subgraph); } -void KGraphViewerPart::slotMoveExistingNodeToMainGraph(const QMap& attribs) +void KGraphViewerPart::slotMoveExistingNodeToMainGraph(const QMap &attribs) { - d->m_widget->graph()->moveExistingNodeToMainGraph(attribs); + d->m_widget->graph()->moveExistingNodeToMainGraph(attribs); } -void KGraphViewerPart::slotAddNewEdge(const QString& src, const QString& tgt, const QMap& attribs) +void KGraphViewerPart::slotAddNewEdge(const QString &src, const QString &tgt, const QMap &attribs) { - d->m_widget->graph()->addNewEdge(src,tgt,attribs); + d->m_widget->graph()->addNewEdge(src, tgt, attribs); } -void KGraphViewerPart::prepareAddNewEdge(const QMap& attribs) +void KGraphViewerPart::prepareAddNewEdge(const QMap &attribs) { - d->m_widget->prepareAddNewEdge(attribs); + d->m_widget->prepareAddNewEdge(attribs); } void KGraphViewerPart::setReadOnly() { - d->m_widget->setReadOnly(); + d->m_widget->setReadOnly(); } void KGraphViewerPart::setReadWrite() { - d->m_widget->setReadWrite(); + d->m_widget->setReadWrite(); } -void KGraphViewerPart::saveTo(const QString& fileName) +void KGraphViewerPart::saveTo(const QString &fileName) { - d->m_widget->graph()->saveTo(fileName); + d->m_widget->graph()->saveTo(fileName); } -void KGraphViewerPart::slotRemoveNode(const QString& nodeName) +void KGraphViewerPart::slotRemoveNode(const QString &nodeName) { - d->m_widget->graph()->removeNodeNamed(nodeName); + d->m_widget->graph()->removeNodeNamed(nodeName); } -void KGraphViewerPart::slotRemoveNodeFromSubgraph(const QString& nodeName, const QString& subgraphName) +void KGraphViewerPart::slotRemoveNodeFromSubgraph(const QString &nodeName, const QString &subgraphName) { - d->m_widget->graph()->removeNodeFromSubgraph(nodeName, subgraphName); + d->m_widget->graph()->removeNodeFromSubgraph(nodeName, subgraphName); } -void KGraphViewerPart::slotRemoveSubgraph(const QString& subgraphName) +void KGraphViewerPart::slotRemoveSubgraph(const QString &subgraphName) { - d->m_widget->graph()->removeSubgraphNamed(subgraphName); + d->m_widget->graph()->removeSubgraphNamed(subgraphName); } -void KGraphViewerPart::slotSelectNode(const QString& nodeName) +void KGraphViewerPart::slotSelectNode(const QString &nodeName) { - d->m_widget->slotSelectNode(nodeName); + d->m_widget->slotSelectNode(nodeName); } -void KGraphViewerPart::slotAddAttribute(const QString&) +void KGraphViewerPart::slotAddAttribute(const QString &) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "NOT IMPLEMENTED"; + qCDebug(KGRAPHVIEWERLIB_LOG) << "NOT IMPLEMENTED"; } -void KGraphViewerPart::slotSetAttribute(const QString& elementId, const QString& attributeName, const QString& attributeValue) +void KGraphViewerPart::slotSetAttribute(const QString &elementId, const QString &attributeName, const QString &attributeValue) { - d->m_widget->graph()->setAttribute(elementId,attributeName,attributeValue); + d->m_widget->graph()->setAttribute(elementId, attributeName, attributeValue); } -void KGraphViewerPart::slotRemoveAttribute(const QString& nodeName, const QString& attribName) +void KGraphViewerPart::slotRemoveAttribute(const QString &nodeName, const QString &attribName) { - d->m_widget->graph()->removeAttribute(nodeName, attribName); + d->m_widget->graph()->removeAttribute(nodeName, attribName); } -void KGraphViewerPart::slotRemoveEdge(const QString& id) +void KGraphViewerPart::slotRemoveEdge(const QString &id) { - d->m_widget->graph()->removeEdge(id); + d->m_widget->graph()->removeEdge(id); } -void KGraphViewerPart::slotRemoveElement(const QString& id) +void KGraphViewerPart::slotRemoveElement(const QString &id) { - d->m_widget->graph()->removeElement(id); + d->m_widget->graph()->removeElement(id); } void KGraphViewerPart::slotSetHighlighting(bool highlightingValue) { - d->m_widget->setHighlighting(highlightingValue); + d->m_widget->setHighlighting(highlightingValue); } - void KGraphViewerPart::slotPrepareToSelect() { - d->m_widget->prepareSelectElements(); + d->m_widget->prepareSelectElements(); } -void KGraphViewerPart::slotSetCursor(const QCursor& cursor) +void KGraphViewerPart::slotSetCursor(const QCursor &cursor) { - d->m_widget->setCursor(cursor); + d->m_widget->setCursor(cursor); } void KGraphViewerPart::slotUnsetCursor() { - d->m_widget->unsetCursor(); + d->m_widget->unsetCursor(); } void KGraphViewerPart::slotSetLayoutMethod(LayoutMethod method) { - setLayoutMethod(method); + setLayoutMethod(method); } void KGraphViewerPart::setLayoutMethod(LayoutMethod method) { - d->m_layoutMethod = method; + d->m_layoutMethod = method; } -void KGraphViewerPart::centerOnNode(const QString& nodeId) +void KGraphViewerPart::centerOnNode(const QString &nodeId) { - d->m_widget->centerOnNode(nodeId); + d->m_widget->centerOnNode(nodeId); } -void KGraphViewerPart::selectNode(const QString& nodeId) +void KGraphViewerPart::selectNode(const QString &nodeId) { - slotSelectNode(nodeId); + slotSelectNode(nodeId); } -void KGraphViewerPart::setLayoutCommand(const QString& command) +void KGraphViewerPart::setLayoutCommand(const QString &command) { - d->m_widget->setLayoutCommand(command); + d->m_widget->setLayoutCommand(command); } void KGraphViewerPart::setPannerPosition(KGraphViewerInterface::PannerPosition position) { - d->m_widget->viewBevActivated(position); + d->m_widget->viewBevActivated(position); } void KGraphViewerPart::setPannerEnabled(bool enabled) { - d->m_widget->setPannerEnabled(enabled); + d->m_widget->setPannerEnabled(enabled); } void KGraphViewerPart::setZoomFactor(double factor) { - d->m_widget->setZoomFactor(factor); + d->m_widget->setZoomFactor(factor); } void KGraphViewerPart::zoomBy(double factor) { - d->m_widget->applyZoom(factor); + d->m_widget->applyZoom(factor); } void KGraphViewerPart::zoomIn() { - d->m_widget->zoomIn(); + d->m_widget->zoomIn(); } void KGraphViewerPart::zoomOut() { - d->m_widget->zoomOut(); + d->m_widget->zoomOut(); } -void KGraphViewerPart::slotRenameNode(const QString& oldNodeName, const QString& newNodeName) +void KGraphViewerPart::slotRenameNode(const QString &oldNodeName, const QString &newNodeName) { - d->m_widget->graph()->renameNode(oldNodeName,newNodeName); + d->m_widget->graph()->renameNode(oldNodeName, newNodeName); } } diff --git a/src/part/layoutagraphthread.h b/src/part/layoutagraphthread.h --- a/src/part/layoutagraphthread.h +++ b/src/part/layoutagraphthread.h @@ -20,34 +20,46 @@ #ifndef LAYOUTAGRAPHTHREAD_H #define LAYOUTAGRAPHTHREAD_H -#include #include +#include #include int threadsafe_wrap_gvLayout(GVC_t *gvc, graph_t *g, const char *engine); int threadsafe_wrap_gvRender(GVC_t *gvc, graph_t *g, const char *format, FILE *out); class LayoutAGraphThread : public QThread { - Q_OBJECT + Q_OBJECT public: - LayoutAGraphThread(); - ~LayoutAGraphThread() override; - void layoutGraph(graph_t* graph, const QString& layoutCommand); - inline graph_t* g() {return m_g;} - inline GVC_t* gvc() {return m_gvc;} - inline const QString& layoutCommand() const {return m_layoutCommand;} - void processed_finished() { sem.release(); } - + LayoutAGraphThread(); + ~LayoutAGraphThread() override; + void layoutGraph(graph_t *graph, const QString &layoutCommand); + inline graph_t *g() + { + return m_g; + } + inline GVC_t *gvc() + { + return m_gvc; + } + inline const QString &layoutCommand() const + { + return m_layoutCommand; + } + void processed_finished() + { + sem.release(); + } + protected: - void run() override; + void run() override; private: - QSemaphore sem; - QString m_layoutCommand; - graph_t* m_g; - GVC_t *m_gvc; + QSemaphore sem; + QString m_layoutCommand; + graph_t *m_g; + GVC_t *m_gvc; }; #endif // LAYOUTAGRAPHTHREAD_H diff --git a/src/part/layoutagraphthread.cpp b/src/part/layoutagraphthread.cpp --- a/src/part/layoutagraphthread.cpp +++ b/src/part/layoutagraphthread.cpp @@ -17,8 +17,8 @@ */ -#include "kgraphviewerlib_debug.h" #include "layoutagraphthread.h" +#include "kgraphviewerlib_debug.h" #include @@ -31,42 +31,41 @@ int threadsafe_wrap_gvLayout(GVC_t *gvc, graph_t *g, const char *engine) { - QMutexLocker locker(&gv_mutex); - return gvLayout(gvc, g, engine); + QMutexLocker locker(&gv_mutex); + return gvLayout(gvc, g, engine); } int threadsafe_wrap_gvRender(GVC_t *gvc, graph_t *g, const char *format, FILE *out) { - QMutexLocker locker(&gv_mutex); - return gvRender(gvc, g, format, out); + QMutexLocker locker(&gv_mutex); + return gvRender(gvc, g, format, out); } -LayoutAGraphThread::LayoutAGraphThread() : sem(1) +LayoutAGraphThread::LayoutAGraphThread() + : sem(1) { - m_gvc = gvContext(); + m_gvc = gvContext(); } LayoutAGraphThread::~LayoutAGraphThread() { - gvFreeContext(m_gvc); + gvFreeContext(m_gvc); } void LayoutAGraphThread::run() { - if (!m_g) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "No graph loaded, skipping layout"; - return; - } - threadsafe_wrap_gvLayout(m_gvc, m_g, m_layoutCommand.toUtf8().data()); - threadsafe_wrap_gvRender(m_gvc, m_g, "xdot", nullptr); + if (!m_g) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "No graph loaded, skipping layout"; + return; + } + threadsafe_wrap_gvLayout(m_gvc, m_g, m_layoutCommand.toUtf8().data()); + threadsafe_wrap_gvRender(m_gvc, m_g, "xdot", nullptr); } -void LayoutAGraphThread::layoutGraph(graph_t* graph, const QString& layoutCommand) +void LayoutAGraphThread::layoutGraph(graph_t *graph, const QString &layoutCommand) { - sem.acquire(); - m_g = graph; - m_layoutCommand = layoutCommand; - start(); + sem.acquire(); + m_g = graph; + m_layoutCommand = layoutCommand; + start(); } - diff --git a/src/part/loadagraphthread.h b/src/part/loadagraphthread.h --- a/src/part/loadagraphthread.h +++ b/src/part/loadagraphthread.h @@ -25,28 +25,42 @@ #include - class LoadAGraphThread : public QThread { - Q_OBJECT + Q_OBJECT public: - LoadAGraphThread() : sem(1) {} - void loadFile(const QString& dotFileName); - inline graph_t* g() {return m_g;} - inline const QString& dotFileName() {return m_dotFileName;} - void processed_finished() { sem.release(); } + LoadAGraphThread() + : sem(1) + { + } + void loadFile(const QString &dotFileName); + inline graph_t *g() + { + return m_g; + } + inline const QString &dotFileName() + { + return m_dotFileName; + } + void processed_finished() + { + sem.release(); + } - // helper method only for DotGraphView::loadLibrarySync() - // see notes next to the call there - void setDotFileName(const QString& dotFileName) { m_dotFileName = dotFileName; } + // helper method only for DotGraphView::loadLibrarySync() + // see notes next to the call there + void setDotFileName(const QString &dotFileName) + { + m_dotFileName = dotFileName; + } protected: - void run() override; + void run() override; private: - QSemaphore sem; - QString m_dotFileName; - graph_t *m_g; + QSemaphore sem; + QString m_dotFileName; + graph_t *m_g; }; #endif // LOADAGRAPHTHREAD_H diff --git a/src/part/loadagraphthread.cpp b/src/part/loadagraphthread.cpp --- a/src/part/loadagraphthread.cpp +++ b/src/part/loadagraphthread.cpp @@ -24,42 +24,39 @@ void LoadAGraphThread::run() { - qCDebug(KGRAPHVIEWERLIB_LOG) << m_dotFileName; - FILE* fp = fopen(m_dotFileName.toUtf8().data(), "r"); - if (!fp) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to open file " << m_dotFileName; - return; - } - m_g = agread(fp, nullptr); - if (!m_g) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file, retrying to work around graphviz bug(?)"; - rewind(fp); - m_g = agread(fp, nullptr); - } - if (m_g == nullptr) - { - qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file " << m_dotFileName; - } - fclose(fp); + qCDebug(KGRAPHVIEWERLIB_LOG) << m_dotFileName; + FILE *fp = fopen(m_dotFileName.toUtf8().data(), "r"); + if (!fp) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to open file " << m_dotFileName; + return; + } + m_g = agread(fp, nullptr); + if (!m_g) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file, retrying to work around graphviz bug(?)"; + rewind(fp); + m_g = agread(fp, nullptr); + } + if (m_g == nullptr) { + qCWarning(KGRAPHVIEWERLIB_LOG) << "Failed to read file " << m_dotFileName; + } + fclose(fp); } -void LoadAGraphThread::loadFile(const QString& dotFileName) +void LoadAGraphThread::loadFile(const QString &dotFileName) { - // FIXME: deadlock possible - // if thread is still running or queued finished signal of the thread has not - // yet been delivered so its handler who would release the semaphore, - // then the semaphore can not be acquired and this will block the (main) thread - // which called LoadAGraphThread::loadFile(). - // That one though very much might have also been the one which before invoked this - // method and thus the still running thread or yet-to-be delivered finished signal. - // But being blocked now, it will not reach its event loop where the queued finished - // signal of the thread would be processed and delivered, so in the further processing - // by the signal handler this semaphore would be released - // -> blocked ourselves without any escape - sem.acquire(); - m_dotFileName = dotFileName; - m_g = nullptr; - start(); + // FIXME: deadlock possible + // if thread is still running or queued finished signal of the thread has not + // yet been delivered so its handler who would release the semaphore, + // then the semaphore can not be acquired and this will block the (main) thread + // which called LoadAGraphThread::loadFile(). + // That one though very much might have also been the one which before invoked this + // method and thus the still running thread or yet-to-be delivered finished signal. + // But being blocked now, it will not reach its event loop where the queued finished + // signal of the thread would be processed and delivered, so in the further processing + // by the signal handler this semaphore would be released + // -> blocked ourselves without any escape + sem.acquire(); + m_dotFileName = dotFileName; + m_g = nullptr; + start(); } diff --git a/src/part/pannerview.h b/src/part/pannerview.h --- a/src/part/pannerview.h +++ b/src/part/pannerview.h @@ -24,7 +24,6 @@ License as published by the Free Software Foundation, version 2. */ - /* * Callgraph View */ @@ -34,51 +33,50 @@ #include #include -//Added by qt3to4: +// Added by qt3to4: #include namespace KGraphViewer { - class DotGraphView; /** * A panner laid over a QCanvas */ -class PannerView: public QGraphicsView +class PannerView : public QGraphicsView { - Q_OBJECT + Q_OBJECT public: - explicit PannerView(DotGraphView * parent); + explicit PannerView(DotGraphView *parent); - inline void setDrawingEnabled(bool val) {m_drawContents = val;} + inline void setDrawingEnabled(bool val) + { + m_drawContents = val; + } public Q_SLOTS: - void setZoomRect(QRectF r); - void moveZoomRectTo(const QPointF& newPos, const bool notify = true); + void setZoomRect(QRectF r); + void moveZoomRectTo(const QPointF &newPos, const bool notify = true); Q_SIGNALS: - void zoomRectMovedTo(QPointF newPos); - void zoomRectMoveFinished(); + void zoomRectMovedTo(QPointF newPos); + void zoomRectMoveFinished(); protected: - void mousePressEvent(QMouseEvent*) override; - void mouseMoveEvent(QMouseEvent*) override; - void mouseReleaseEvent(QMouseEvent*) override; - void drawForeground(QPainter* p, const QRectF& rect) override; - void contextMenuEvent(QContextMenuEvent* event) override; - - QRectF m_zoomRect; - bool m_movingZoomRect; - QPointF m_lastPos; - bool m_drawContents; - DotGraphView* m_parent; + void mousePressEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + void drawForeground(QPainter *p, const QRectF &rect) override; + void contextMenuEvent(QContextMenuEvent *event) override; + + QRectF m_zoomRect; + bool m_movingZoomRect; + QPointF m_lastPos; + bool m_drawContents; + DotGraphView *m_parent; }; } #endif - - - diff --git a/src/part/pannerview.cpp b/src/part/pannerview.cpp --- a/src/part/pannerview.cpp +++ b/src/part/pannerview.cpp @@ -24,161 +24,154 @@ License as published by the Free Software Foundation, version 2. */ - /* * Callgraph View */ -#include "dotgraphview.h" #include "pannerview.h" +#include "dotgraphview.h" #include "kgraphviewerlib_debug.h" -#include -#include #include +#include +#include +#include #include -#include #include -#include +#include #include namespace KGraphViewer { // // PannerView // -PannerView::PannerView(DotGraphView * parent) - : QGraphicsView(parent), m_drawContents(true), m_parent(parent) +PannerView::PannerView(DotGraphView *parent) + : QGraphicsView(parent) + , m_drawContents(true) + , m_parent(parent) { - m_movingZoomRect = false; + m_movingZoomRect = false; - // why doesn't this avoid flicker ? - // viewport()->setBackgroundMode(Qt::NoBackground); + // why doesn't this avoid flicker ? + // viewport()->setBackgroundMode(Qt::NoBackground); - // if there are ever graphic glitches to be found, remove this again - setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing | QGraphicsView::DontClipPainter | - QGraphicsView::DontSavePainterState); + // if there are ever graphic glitches to be found, remove this again + setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing | QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); - setToolTip(i18n("View of the complete graph. Click and drag to move the visible part.")); - setWhatsThis(i18n("

View of the Complete Graph

" - "

Single clicking somewhere without the red square will move the center of the " - "view to where the mouse was clicked.

Clicking and dragging within the red square " - "will cause the view to follow the movement.

")); + setToolTip(i18n("View of the complete graph. Click and drag to move the visible part.")); + setWhatsThis( + i18n("

View of the Complete Graph

" + "

Single clicking somewhere without the red square will move the center of the " + "view to where the mouse was clicked.

Clicking and dragging within the red square " + "will cause the view to follow the movement.

")); } void PannerView::setZoomRect(QRectF r) { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::setZoomRect " << r; - if (r == m_zoomRect) { - return; - } - scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); - // get new zoom rect - m_zoomRect = r; - qreal q = mapToScene(15,0).x(); - if (!m_zoomRect.isValid() || m_zoomRect.width() < q || m_zoomRect.height() < q) - { - double factor = ((double)m_zoomRect.width())/m_zoomRect.height(); - qreal newWidth, newHeight; - if (factor < 1.0) - { - newWidth = q; - newHeight = newWidth/factor; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::setZoomRect " << r; + if (r == m_zoomRect) { + return; } - else - { - newHeight = q; - newWidth = newHeight*factor; + scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); + // get new zoom rect + m_zoomRect = r; + qreal q = mapToScene(15, 0).x(); + if (!m_zoomRect.isValid() || m_zoomRect.width() < q || m_zoomRect.height() < q) { + double factor = ((double)m_zoomRect.width()) / m_zoomRect.height(); + qreal newWidth, newHeight; + if (factor < 1.0) { + newWidth = q; + newHeight = newWidth / factor; + } else { + newHeight = q; + newWidth = newHeight * factor; + } + qreal newXPos = m_zoomRect.x() + (m_zoomRect.width() - newWidth) / 2; + qreal newYPos = m_zoomRect.y() + (m_zoomRect.height() - newHeight) / 2; + m_zoomRect.setX(newXPos); + m_zoomRect.setY(newYPos); + m_zoomRect.setWidth(newWidth); + m_zoomRect.setHeight(newHeight); } - qreal newXPos = m_zoomRect.x() + (m_zoomRect.width() - newWidth)/2; - qreal newYPos = m_zoomRect.y() + (m_zoomRect.height() - newHeight)/2; - m_zoomRect.setX(newXPos); - m_zoomRect.setY(newYPos); - m_zoomRect.setWidth(newWidth); - m_zoomRect.setHeight(newHeight); - } - scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); + scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); } -void PannerView::moveZoomRectTo(const QPointF& newPos, bool notify) +void PannerView::moveZoomRectTo(const QPointF &newPos, bool notify) { - if (!m_zoomRect.isValid()) { - return; - } - - if (m_zoomRect.center() == newPos) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "same pos, don't do anything"; - return; - } - - scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); - m_zoomRect.moveCenter(newPos); - scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); - - if (m_zoomRect.isValid() && notify) { - emit zoomRectMovedTo(newPos); - m_lastPos = newPos; - } + if (!m_zoomRect.isValid()) { + return; + } + + if (m_zoomRect.center() == newPos) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "same pos, don't do anything"; + return; + } + + scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); + m_zoomRect.moveCenter(newPos); + scene()->invalidate(m_zoomRect, QGraphicsScene::ForegroundLayer); + + if (m_zoomRect.isValid() && notify) { + emit zoomRectMovedTo(newPos); + m_lastPos = newPos; + } } -void PannerView::drawForeground(QPainter * p, const QRectF & rect ) +void PannerView::drawForeground(QPainter *p, const QRectF &rect) { - if (m_zoomRect.isValid() && rect.intersects(m_zoomRect)) - { - p->save(); - if (m_zoomRect.width() > 10 && m_zoomRect.height() > 10) - { - p->setPen(Qt::red); - // subtract pen width, i.e. draw inside - qreal penWidth = p->pen().widthF(); - p->drawRect(m_zoomRect.adjusted(-penWidth, -penWidth, -penWidth, -penWidth)); - } - else - { - QBrush brush(Qt::red); - p->fillRect(m_zoomRect, brush); + if (m_zoomRect.isValid() && rect.intersects(m_zoomRect)) { + p->save(); + if (m_zoomRect.width() > 10 && m_zoomRect.height() > 10) { + p->setPen(Qt::red); + // subtract pen width, i.e. draw inside + qreal penWidth = p->pen().widthF(); + p->drawRect(m_zoomRect.adjusted(-penWidth, -penWidth, -penWidth, -penWidth)); + } else { + QBrush brush(Qt::red); + p->fillRect(m_zoomRect, brush); + } + p->restore(); } - p->restore(); - } } -void PannerView::mousePressEvent(QMouseEvent* e) +void PannerView::mousePressEvent(QMouseEvent *e) { - if (e->button() != Qt::LeftButton) { - return; - } -/* qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mousePressEvent " - << mapToScene(e->pos()) << " / " << m_zoomRect << " / " << m_zoomRect.center() <pos())); - m_movingZoomRect = true; + if (e->button() != Qt::LeftButton) { + return; + } + /* qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mousePressEvent " + << mapToScene(e->pos()) << " / " << m_zoomRect << " / " << m_zoomRect.center() <pos())); + m_movingZoomRect = true; } -void PannerView::mouseMoveEvent(QMouseEvent* e) +void PannerView::mouseMoveEvent(QMouseEvent *e) { - if (!m_movingZoomRect) { - return; - } + if (!m_movingZoomRect) { + return; + } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mouseMoveEvent " << pos; - moveZoomRectTo(mapToScene(e->pos())); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mouseMoveEvent " << pos; + moveZoomRectTo(mapToScene(e->pos())); } -void PannerView::mouseReleaseEvent(QMouseEvent* e) +void PannerView::mouseReleaseEvent(QMouseEvent *e) { - if (e->button() != Qt::LeftButton) { - return; - } - moveZoomRectTo(mapToScene(e->pos())); -// qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mouseReleaseEvent " << pos; - m_movingZoomRect = false; - emit zoomRectMoveFinished(); + if (e->button() != Qt::LeftButton) { + return; + } + moveZoomRectTo(mapToScene(e->pos())); + // qCDebug(KGRAPHVIEWERLIB_LOG) << "PannerView::mouseReleaseEvent " << pos; + m_movingZoomRect = false; + emit zoomRectMoveFinished(); } -void PannerView::contextMenuEvent(QContextMenuEvent* event) +void PannerView::contextMenuEvent(QContextMenuEvent *event) { - m_parent->contextMenuEvent(event); + m_parent->contextMenuEvent(event); } } diff --git a/src/part/simpleprintingcommand.h b/src/part/simpleprintingcommand.h --- a/src/part/simpleprintingcommand.h +++ b/src/part/simpleprintingcommand.h @@ -36,50 +36,52 @@ { class KGVSimplePrintPreviewWindow; -/*! @short A command for simple printing and print preview. +/*! @short A command for simple printing and print preview. This class is instantiated in KGVMainWindowImpl so there's: - a single print preview window per part item regardless of a way how user invoked - the 'print preview' command (using 'File->Print Preview' command or 'Print Preview' button + the 'print preview' command (using 'File->Print Preview' command or 'Print Preview' button of the 'Page Setup' dialog) - a single printing engine per part item regardless of a way how user started (using 'File->Print' command or 'Print' button of the 'Page Setup' dialog) */ class KGVSimplePrintingCommand : public QObject { -Q_OBJECT + Q_OBJECT public: - KGVSimplePrintingCommand(DotGraphView* mainWin, int objectId, - QObject* parent = nullptr); - ~KGVSimplePrintingCommand(); + KGVSimplePrintingCommand(DotGraphView *mainWin, int objectId, QObject *parent = nullptr); + ~KGVSimplePrintingCommand(); - inline KGVSimplePrintingEngine* engine() {return m_previewEngine;} + inline KGVSimplePrintingEngine *engine() + { + return m_previewEngine; + } - void hidePageSetup(); - void hidePrintPreview(); + void hidePageSetup(); + void hidePrintPreview(); public Q_SLOTS: - bool print(const QString& aTitleText = QString()); - bool showPrintPreview(const QString& aTitleText = QString(), bool reload = false); - void showPageSetup(const QString& aTitleText = QString()); + bool print(const QString &aTitleText = QString()); + bool showPrintPreview(const QString &aTitleText = QString(), bool reload = false); + void showPageSetup(const QString &aTitleText = QString()); Q_SIGNALS: - //! connected to KGV Main Window - void showPageSetupRequested(); + //! connected to KGV Main Window + void showPageSetupRequested(); protected Q_SLOTS: - void slotShowPageSetupRequested(); + void slotShowPageSetupRequested(); protected: - bool init(const QString& aTitleText = QString()); - - KGVSimplePrintingEngine* m_previewEngine; - DotGraphView* m_graphView; - int m_objectId; - KGVSimplePrintingSettings* m_settings; - KGVSimplePrintPreviewWindow *m_previewWindow; - bool m_printPreviewNeedsReloading : 1; - QDialog* m_pageSetupDialog; + bool init(const QString &aTitleText = QString()); + + KGVSimplePrintingEngine *m_previewEngine; + DotGraphView *m_graphView; + int m_objectId; + KGVSimplePrintingSettings *m_settings; + KGVSimplePrintPreviewWindow *m_previewWindow; + bool m_printPreviewNeedsReloading : 1; + QDialog *m_pageSetupDialog; }; } diff --git a/src/part/simpleprintingcommand.cpp b/src/part/simpleprintingcommand.cpp --- a/src/part/simpleprintingcommand.cpp +++ b/src/part/simpleprintingcommand.cpp @@ -26,271 +26,244 @@ */ #include "simpleprintingcommand.h" -#include "simpleprintingsettings.h" +#include "kgraphviewerlib_debug.h" #include "simpleprintingpagesetup.h" +#include "simpleprintingsettings.h" #include "simpleprintpreviewwindow.h" -#include "kgraphviewerlib_debug.h" // #include // #include // #include #include -#include -#include #include -#include +#include +#include #include -#include #include -#include #include +#include +#include +#include -#include #include +#include +#include #include -#include #include #include -#include -#include #include -//Added by qt3to4: +#include +#include +// Added by qt3to4: #include -#include #include -#include +#include #include +#include namespace KGraphViewer { -KGVSimplePrintingCommand::KGVSimplePrintingCommand( - DotGraphView* mainWin, int objectId, QObject* parent) - : QObject(parent) - , m_previewEngine(nullptr) - , m_graphView(mainWin) - , m_objectId(objectId) - , m_settings(new KGVSimplePrintingSettings(KGVSimplePrintingSettings::load())) - , m_previewWindow(nullptr) - , m_printPreviewNeedsReloading(true) - , m_pageSetupDialog(nullptr) +KGVSimplePrintingCommand::KGVSimplePrintingCommand(DotGraphView *mainWin, int objectId, QObject *parent) + : QObject(parent) + , m_previewEngine(nullptr) + , m_graphView(mainWin) + , m_objectId(objectId) + , m_settings(new KGVSimplePrintingSettings(KGVSimplePrintingSettings::load())) + , m_previewWindow(nullptr) + , m_printPreviewNeedsReloading(true) + , m_pageSetupDialog(nullptr) { - setObjectName("KGVSimplePrintCommand"); - connect(this, &KGVSimplePrintingCommand::showPageSetupRequested, - this, &KGVSimplePrintingCommand::slotShowPageSetupRequested); + setObjectName("KGVSimplePrintCommand"); + connect(this, &KGVSimplePrintingCommand::showPageSetupRequested, this, &KGVSimplePrintingCommand::slotShowPageSetupRequested); } KGVSimplePrintingCommand::~KGVSimplePrintingCommand() { - delete m_previewWindow; - delete m_previewEngine; - delete m_settings; + delete m_previewWindow; + delete m_previewEngine; + delete m_settings; } -bool KGVSimplePrintingCommand::init(const QString& aTitleText) +bool KGVSimplePrintingCommand::init(const QString &aTitleText) { - if (!m_previewEngine) - m_previewEngine = new KGVSimplePrintingEngine(m_settings, this); - - QString titleText(aTitleText.trimmed()); - if (!m_previewWindow) - { - QString errorMessage; - if (!m_previewEngine->init( - *m_graphView, titleText, errorMessage)) { - if (!errorMessage.isEmpty()) - QMessageBox::warning(m_graphView, i18n("Print Preview"), errorMessage); - return false; + if (!m_previewEngine) + m_previewEngine = new KGVSimplePrintingEngine(m_settings, this); + + QString titleText(aTitleText.trimmed()); + if (!m_previewWindow) { + QString errorMessage; + if (!m_previewEngine->init(*m_graphView, titleText, errorMessage)) { + if (!errorMessage.isEmpty()) + QMessageBox::warning(m_graphView, i18n("Print Preview"), errorMessage); + return false; + } + m_previewWindow = new KGVSimplePrintPreviewWindow(*m_previewEngine, QString(), nullptr); + connect(m_previewWindow, &KGVSimplePrintPreviewWindow::printRequested, this, [&]() { print(); }); + connect(m_previewWindow, &KGVSimplePrintPreviewWindow::pageSetupRequested, this, &KGVSimplePrintingCommand::slotShowPageSetupRequested); + // KDialog::centerOnScreen(m_previewWindow); + m_printPreviewNeedsReloading = false; } - m_previewWindow = new KGVSimplePrintPreviewWindow( - *m_previewEngine, QString(), nullptr); - connect(m_previewWindow, &KGVSimplePrintPreviewWindow::printRequested, - this, [&] () { print(); } ); - connect(m_previewWindow, &KGVSimplePrintPreviewWindow::pageSetupRequested, - this, &KGVSimplePrintingCommand::slotShowPageSetupRequested); -// KDialog::centerOnScreen(m_previewWindow); - m_printPreviewNeedsReloading = false; - } - return true; + return true; } -bool KGVSimplePrintingCommand::print(const QString& aTitleText) +bool KGVSimplePrintingCommand::print(const QString &aTitleText) { - init(aTitleText); - m_previewEngine->clear(); - - //setup printing - QPrinter printer; - printer.setOrientation( m_settings->pageLayout.orientation == PG_PORTRAIT - ? QPrinter::Portrait : QPrinter::Landscape ); - printer.setPageSize( - QPageSize( (QPageSize::PageSizeId)KgvPageFormat::printerPageSize( m_settings->pageLayout.format ) ) ); -// #endif - - printer.setFullPage(true); - QString docName( aTitleText ); - printer.setDocName( docName ); - printer.setCreator("kgraphviewer"); - QPointer dlg = new QPrintDialog(&printer, m_graphView); - if (dlg->exec() != QDialog::Accepted) { - return true; - } - - // now we have final settings - - //! @todo get printer.pageOrder() (for reversed order requires improved engine) - QPainter painter; - - if (!painter.begin(&printer)) - { - //! @todo msg - return false; - } - m_previewEngine->calculatePagesCount(painter); - - uint loops, loopsPerPage; - QList pagesToPrint; - int fromPage = 0; - // on !win32 print QPrinter::numCopies() times (the OS does not perform buffering) -// pagesToPrint = printer.pageList(); -// qCDebug(KGRAPHVIEWERLIB_LOG) << pagesToPrint; - if (pagesToPrint.isEmpty()) - { - fromPage = 0; - for (int i = 0; i<(int)m_previewEngine->pagesCount(); i++) - { -// std::cerr << "Page " << i << " has to be printed" << std::endl; - pagesToPrint.append(i); + init(aTitleText); + m_previewEngine->clear(); + + // setup printing + QPrinter printer; + printer.setOrientation(m_settings->pageLayout.orientation == PG_PORTRAIT ? QPrinter::Portrait : QPrinter::Landscape); + printer.setPageSize(QPageSize((QPageSize::PageSizeId)KgvPageFormat::printerPageSize(m_settings->pageLayout.format))); + // #endif + + printer.setFullPage(true); + QString docName(aTitleText); + printer.setDocName(docName); + printer.setCreator("kgraphviewer"); + QPointer dlg = new QPrintDialog(&printer, m_graphView); + if (dlg->exec() != QDialog::Accepted) { + return true; } - } - else - fromPage = pagesToPrint.first(); - if (printer.collateCopies()) - { - //collation: p1, p2,..pn; p1, p2,..pn; ......; p1, p2,..pn - loops = printer.numCopies(); - loopsPerPage = 1; - } - else - { - //no collation: p1, p1, ..., p1; p2, p2, ..., p2; ......; pn, pn,..pn - loops = 1; - loopsPerPage = printer.numCopies(); - } - //! @todo also look at printer.pageSet() option : all/odd/even pages -// #endif - // now, total number of printed pages is printer.numCopies()*printer.pageList().count() - -// qCDebug(KGRAPHVIEWERLIB_LOG) << "printing..."; - bool firstPage = true; - for (uint copy = 0;copy < loops; copy++) - { -// qCDebug(KGRAPHVIEWERLIB_LOG) << "copy " << (copy+1) << " of " << loops; -// std::cerr << "fromPage = " << fromPage << " ; eof = " << m_previewEngine->eof() << std::endl; - uint pageNumber = fromPage; - QList::ConstIterator pagesIt = pagesToPrint.constBegin(); - for(;(int)pageNumber == fromPage || !m_previewEngine->eof(); ++pageNumber) - { -// std::cerr << "printing..." << std::endl; - if (pagesIt == pagesToPrint.constEnd()) //no more pages to print - break; - if ((int)pageNumber < *pagesIt) - { //skip pages without printing (needed for computation) - m_previewEngine->paintPage(pageNumber, painter, false); - continue; - } - if (*pagesIt < (int)pageNumber) - { //sanity - ++pagesIt; - continue; - } - for (uint onePageCounter = 0; onePageCounter < loopsPerPage; onePageCounter++) - { - if (!firstPage) - printer.newPage(); - else - firstPage = false; -// std::cerr << "page #" << pageNumber << std::endl; - m_previewEngine->paintPage(pageNumber, painter); - } - ++pagesIt; + + // now we have final settings + + //! @todo get printer.pageOrder() (for reversed order requires improved engine) + QPainter painter; + + if (!painter.begin(&printer)) { + //! @todo msg + return false; } - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "end of printing."; + m_previewEngine->calculatePagesCount(painter); - // stop painting, this will automatically send the print data to the printer - if (!painter.end()) - return false; + uint loops, loopsPerPage; + QList pagesToPrint; + int fromPage = 0; + // on !win32 print QPrinter::numCopies() times (the OS does not perform buffering) + // pagesToPrint = printer.pageList(); + // qCDebug(KGRAPHVIEWERLIB_LOG) << pagesToPrint; + if (pagesToPrint.isEmpty()) { + fromPage = 0; + for (int i = 0; i < (int)m_previewEngine->pagesCount(); i++) { + // std::cerr << "Page " << i << " has to be printed" << std::endl; + pagesToPrint.append(i); + } + } else + fromPage = pagesToPrint.first(); + if (printer.collateCopies()) { + // collation: p1, p2,..pn; p1, p2,..pn; ......; p1, p2,..pn + loops = printer.numCopies(); + loopsPerPage = 1; + } else { + // no collation: p1, p1, ..., p1; p2, p2, ..., p2; ......; pn, pn,..pn + loops = 1; + loopsPerPage = printer.numCopies(); + } + //! @todo also look at printer.pageSet() option : all/odd/even pages + // #endif + // now, total number of printed pages is printer.numCopies()*printer.pageList().count() -// if (!m_previewEngine->done()) -// return false; + // qCDebug(KGRAPHVIEWERLIB_LOG) << "printing..."; + bool firstPage = true; + for (uint copy = 0; copy < loops; copy++) { + // qCDebug(KGRAPHVIEWERLIB_LOG) << "copy " << (copy+1) << " of " << loops; + // std::cerr << "fromPage = " << fromPage << " ; eof = " << m_previewEngine->eof() << std::endl; + uint pageNumber = fromPage; + QList::ConstIterator pagesIt = pagesToPrint.constBegin(); + for (; (int)pageNumber == fromPage || !m_previewEngine->eof(); ++pageNumber) { + // std::cerr << "printing..." << std::endl; + if (pagesIt == pagesToPrint.constEnd()) // no more pages to print + break; + if ((int)pageNumber < *pagesIt) { // skip pages without printing (needed for computation) + m_previewEngine->paintPage(pageNumber, painter, false); + continue; + } + if (*pagesIt < (int)pageNumber) { // sanity + ++pagesIt; + continue; + } + for (uint onePageCounter = 0; onePageCounter < loopsPerPage; onePageCounter++) { + if (!firstPage) + printer.newPage(); + else + firstPage = false; + // std::cerr << "page #" << pageNumber << std::endl; + m_previewEngine->paintPage(pageNumber, painter); + } + ++pagesIt; + } + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "end of printing."; + + // stop painting, this will automatically send the print data to the printer + if (!painter.end()) + return false; + + // if (!m_previewEngine->done()) + // return false; - return true; + return true; } -bool KGVSimplePrintingCommand::showPrintPreview(const QString& aTitleText, bool reload) +bool KGVSimplePrintingCommand::showPrintPreview(const QString &aTitleText, bool reload) { - init(aTitleText); - - if (reload) - m_printPreviewNeedsReloading = true; - - if (m_printPreviewNeedsReloading) - {//dirty - m_previewEngine->clear(); - //! @todo progress bar... - m_previewEngine->setTitleText( aTitleText ); - m_previewWindow->setFullWidth(); - m_previewWindow->updatePagesCount(); - m_printPreviewNeedsReloading = false; - m_previewWindow->goToPage(0); - } - m_previewWindow->show(); - m_previewWindow->raise(); - return true; + init(aTitleText); + + if (reload) + m_printPreviewNeedsReloading = true; + + if (m_printPreviewNeedsReloading) { // dirty + m_previewEngine->clear(); + //! @todo progress bar... + m_previewEngine->setTitleText(aTitleText); + m_previewWindow->setFullWidth(); + m_previewWindow->updatePagesCount(); + m_printPreviewNeedsReloading = false; + m_previewWindow->goToPage(0); + } + m_previewWindow->show(); + m_previewWindow->raise(); + return true; } void KGVSimplePrintingCommand::hidePageSetup() { - if (m_pageSetupDialog) - { - m_pageSetupDialog->hide(); - } + if (m_pageSetupDialog) { + m_pageSetupDialog->hide(); + } } void KGVSimplePrintingCommand::hidePrintPreview() { - if (m_previewWindow) - { - m_previewWindow->hide(); - } + if (m_previewWindow) { + m_previewWindow->hide(); + } } void KGVSimplePrintingCommand::slotShowPageSetupRequested() { - if (m_pageSetupDialog == nullptr) - { - m_pageSetupDialog = new QDialog(nullptr); - QMap map; - map["action"]="pageSetup"; - map["title"]=m_graphView->dotFileName(); - QVBoxLayout *lyr = new QVBoxLayout(m_pageSetupDialog); - KGVSimplePrintingPageSetup* sppsb = new KGVSimplePrintingPageSetup(this, m_graphView, m_pageSetupDialog, &map); - if (m_previewWindow) - { - connect(sppsb, &KGVSimplePrintingPageSetup::needsRedraw, - m_previewWindow, &KGVSimplePrintPreviewWindow::slotRedraw); + if (m_pageSetupDialog == nullptr) { + m_pageSetupDialog = new QDialog(nullptr); + QMap map; + map["action"] = "pageSetup"; + map["title"] = m_graphView->dotFileName(); + QVBoxLayout *lyr = new QVBoxLayout(m_pageSetupDialog); + KGVSimplePrintingPageSetup *sppsb = new KGVSimplePrintingPageSetup(this, m_graphView, m_pageSetupDialog, &map); + if (m_previewWindow) { + connect(sppsb, &KGVSimplePrintingPageSetup::needsRedraw, m_previewWindow, &KGVSimplePrintPreviewWindow::slotRedraw); + } + lyr->addWidget(sppsb); } - lyr->addWidget(sppsb); - } - m_pageSetupDialog->show(); - m_pageSetupDialog->raise(); + m_pageSetupDialog->show(); + m_pageSetupDialog->raise(); } -void KGVSimplePrintingCommand::showPageSetup(const QString& aTitleText) +void KGVSimplePrintingCommand::showPageSetup(const QString &aTitleText) { - init(aTitleText); - emit showPageSetupRequested(); + init(aTitleText); + emit showPageSetupRequested(); } } diff --git a/src/part/simpleprintingengine.h b/src/part/simpleprintingengine.h --- a/src/part/simpleprintingengine.h +++ b/src/part/simpleprintingengine.h @@ -30,9 +30,9 @@ #include "KgvPageLayoutDia.h" -#include #include -//Added by qt3to4: +#include +// Added by qt3to4: #include class QPaintDevice; @@ -47,66 +47,76 @@ The engine allows for random access to any page. */ class KGVSimplePrintingEngine : public QObject { -Q_OBJECT + Q_OBJECT public: - KGVSimplePrintingEngine( KGVSimplePrintingSettings* settings, QObject* parent ); - ~KGVSimplePrintingEngine(); - - bool init(DotGraphView& data, - const QString& titleText, QString& errorMessage); + KGVSimplePrintingEngine(KGVSimplePrintingSettings *settings, QObject *parent); + ~KGVSimplePrintingEngine(); - void setTitleText(const QString& titleText); + bool init(DotGraphView &data, const QString &titleText, QString &errorMessage); - //! Calculates page count that can be later obtained using pagesCount(). - //! Page count can depend on \a painter (printer/screen) and on printing settings. - void calculatePagesCount(QPainter& painter); + void setTitleText(const QString &titleText); - bool done(); - void clear(); - KGVSimplePrintingSettings* settings() { return m_settings; } + //! Calculates page count that can be later obtained using pagesCount(). + //! Page count can depend on \a painter (printer/screen) and on printing settings. + void calculatePagesCount(QPainter &painter); - //! \return true when all records has been painted - bool eof() const { return m_eof; } + bool done(); + void clear(); + KGVSimplePrintingSettings *settings() + { + return m_settings; + } - //! \return number of pages. Can be used after calculatePagesCount(). - uint pagesCount() { return m_pagesCount; } + //! \return true when all records has been painted + bool eof() const + { + return m_eof; + } - uint maxHorizFit() const; - uint maxVertFit() const; + //! \return number of pages. Can be used after calculatePagesCount(). + uint pagesCount() + { + return m_pagesCount; + } - inline DotGraphView* data() {return m_data;} + uint maxHorizFit() const; + uint maxVertFit() const; + inline DotGraphView *data() + { + return m_data; + } public Q_SLOTS: - /*! Paints a page number \a pageNumber (counted from 0) on \a painter. - If \a paint is false, drawings are only computed but not painted, - so this can be used for calculating page number before printing or previewing. */ - void paintPage(int pageNumber, QPainter& painter, bool paint = true); + /*! Paints a page number \a pageNumber (counted from 0) on \a painter. + If \a paint is false, drawings are only computed but not painted, + so this can be used for calculating page number before printing or previewing. */ + void paintPage(int pageNumber, QPainter &painter, bool paint = true); protected: - KGVSimplePrintingSettings* m_settings; - - QFont m_mainFont; - int m_dpiX, m_dpiY; - uint m_pageWidth, m_pageHeight; - //QFontMetrics m_headerFM, m_mainFM; - DotGraphView* m_data; - QString m_headerText; - QString m_dateTimeText; - uint m_dateTimeWidth; - QRect m_headerTextRect; - int m_mainLineSpacing; - uint m_pagesCount; - bool m_eof; - bool m_paintInitialized; //!< used by paintPage() - double leftMargin; - double rightMargin; - double topMargin; - double bottomMargin; - double m_fx, m_fy; - - QPixmap m_painting; + KGVSimplePrintingSettings *m_settings; + + QFont m_mainFont; + int m_dpiX, m_dpiY; + uint m_pageWidth, m_pageHeight; + // QFontMetrics m_headerFM, m_mainFM; + DotGraphView *m_data; + QString m_headerText; + QString m_dateTimeText; + uint m_dateTimeWidth; + QRect m_headerTextRect; + int m_mainLineSpacing; + uint m_pagesCount; + bool m_eof; + bool m_paintInitialized; //!< used by paintPage() + double leftMargin; + double rightMargin; + double topMargin; + double bottomMargin; + double m_fx, m_fy; + + QPixmap m_painting; }; } diff --git a/src/part/simpleprintingengine.cpp b/src/part/simpleprintingengine.cpp --- a/src/part/simpleprintingengine.cpp +++ b/src/part/simpleprintingengine.cpp @@ -26,390 +26,334 @@ */ #include "simpleprintingengine.h" -#include "simpleprintingsettings.h" #include "kgraphviewerlib_debug.h" +#include "simpleprintingsettings.h" #include -#include -#include -#include #include +#include +#include #include +#include +#include #include #include #include #include -#include -#include #include #include #include +#include #include #include namespace KGraphViewer { -KGVSimplePrintingEngine::KGVSimplePrintingEngine( - KGVSimplePrintingSettings* settings, - QObject* parent) : - QObject(parent), m_settings(settings), - m_data(nullptr) +KGVSimplePrintingEngine::KGVSimplePrintingEngine(KGVSimplePrintingSettings *settings, QObject *parent) + : QObject(parent) + , m_settings(settings) + , m_data(nullptr) { - setObjectName("KGVSimplePrintingEngine"); - clear(); + setObjectName("KGVSimplePrintingEngine"); + clear(); } KGVSimplePrintingEngine::~KGVSimplePrintingEngine() { - done(); + done(); } -bool KGVSimplePrintingEngine::init(DotGraphView& data, const QString& titleText, QString& errorMessage) +bool KGVSimplePrintingEngine::init(DotGraphView &data, const QString &titleText, QString &errorMessage) { - errorMessage.clear(); - done(); - m_headerText = titleText; - - m_data = &data; - m_eof = false; - - m_painting = QPixmap(m_data->scene()->sceneRect().size().toSize()); - QPainter p(&m_painting); - m_data->scene()->render( &p ); - - return true; + errorMessage.clear(); + done(); + m_headerText = titleText; + + m_data = &data; + m_eof = false; + + m_painting = QPixmap(m_data->scene()->sceneRect().size().toSize()); + QPainter p(&m_painting); + m_data->scene()->render(&p); + + return true; } bool KGVSimplePrintingEngine::done() { - bool result = true; - m_data = nullptr; - m_pagesCount = 0; - m_paintInitialized = false; - return result; + bool result = true; + m_data = nullptr; + m_pagesCount = 0; + m_paintInitialized = false; + return result; } void KGVSimplePrintingEngine::clear() { - m_eof = false; - m_pagesCount = 0; - m_paintInitialized = false; + m_eof = false; + m_pagesCount = 0; + m_paintInitialized = false; } -void KGVSimplePrintingEngine::paintPage(int pageNumber, QPainter& painter, bool paint) +void KGVSimplePrintingEngine::paintPage(int pageNumber, QPainter &painter, bool paint) { qCDebug(KGRAPHVIEWERLIB_LOG) << pageNumber << "/" << m_pagesCount << paint; - uint y = 0; + uint y = 0; - if (pageNumber <= m_pagesCount) - { - m_eof = false; - } - int w = 0, h = 0; - QPaintDevice *pdm = painter.device(); - const bool printer = pdm->devType() == QInternal::Printer; - qCDebug(KGRAPHVIEWERLIB_LOG) << "printer:"<< printer; - - if (!printer) { - w = pdm->width(); - h = pdm->height(); - } - else {//QPrinter... - w = pdm->widthMM(); - h = pdm->heightMM(); - } - - if (!m_paintInitialized) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "initializing"; - // HACK: some functions here do not work properly if were - // are not in a paint event, so repeat this until we actually paint. - m_paintInitialized = paint; - - double widthMM = KgvPageFormat::width( - m_settings->pageLayout.format, m_settings->pageLayout.orientation); - double heightMM = KgvPageFormat::height( - m_settings->pageLayout.format, m_settings->pageLayout.orientation); - - m_dpiY = pdm->logicalDpiY(); - m_dpiX = pdm->logicalDpiX(); -#ifdef Q_WS_WIN //fix for 120dpi - if (!printer) - { -// m_dpiY = 96; -// m_dpiX = 96; - m_dpiY = 86; - m_dpiX = 86; - } -#endif - int pdWidthMM = pdm->widthMM(); - int pdHeightMM = pdm->heightMM(); - - double screenF; -// if (printer) - screenF = 1.0; -// else -// screenF = (double)96.0/120.0; - - leftMargin = POINT_TO_INCH(m_settings->pageLayout.ptLeft)*m_dpiX* screenF; - rightMargin = POINT_TO_INCH(m_settings->pageLayout.ptRight)*m_dpiX* screenF; - topMargin = POINT_TO_INCH(m_settings->pageLayout.ptTop)*m_dpiY* screenF; - bottomMargin = POINT_TO_INCH(m_settings->pageLayout.ptBottom)*m_dpiY* screenF; - - m_fx = widthMM / (pdWidthMM * screenF); - m_fy = heightMM / (pdHeightMM * screenF); - - //screen only - // painter.fillRect(QRect(0,0,w,h), QBrush(white)); - m_pageWidth = int( m_fx*(double)pdm->width() - leftMargin - rightMargin); - m_pageHeight = int( m_fy*(double)pdm->height() - topMargin - bottomMargin); - -//! @todo add setting - m_mainFont = m_settings->pageTitleFont; - if(!printer) - { - int pixelSize = int( POINT_TO_INCH(m_mainFont.pointSizeF())*m_dpiX ); - m_mainFont.setPixelSize(pixelSize); - } - painter.setFont(m_mainFont); - - m_dateTimeText = QLocale().toString(QDateTime::currentDateTime()); - m_dateTimeWidth = 0; - if (m_settings->addDateAndTime) - { - m_dateTimeWidth = painter.boundingRect(leftMargin, topMargin, m_pageWidth, m_pageHeight, Qt::AlignRight, m_dateTimeText+" ").width(); - } - m_mainLineSpacing = painter.fontMetrics().lineSpacing(); - m_headerTextRect = painter.boundingRect( - (int)leftMargin, (int)topMargin, - m_pageWidth - m_dateTimeWidth, - m_pageHeight, Qt::AlignLeft|Qt::TextWordWrap, m_headerText); - m_headerTextRect.setRight(m_headerTextRect.right()+10); - m_headerTextRect.setWidth( - qMin(int(m_pageWidth - m_dateTimeWidth), m_headerTextRect.width())); - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "after initialization"; - - //screen only - if(!printer) - { - painter.setWindow(0, 0, int((double)w*m_fx), int((double)h*m_fy)); - } - - painter.setFont(m_mainFont); - if (paint) - { - //paint header - painter.drawText(m_headerTextRect, Qt::AlignLeft|Qt::TextWordWrap, m_headerText); - if (m_settings->addDateAndTime) - { - painter.drawText( - (int)leftMargin + m_pageWidth - m_dateTimeWidth, (int)topMargin, - m_dateTimeWidth, m_headerTextRect.height(), - Qt::AlignRight, m_dateTimeText); - } - - //footer - if (m_settings->addPageNumbers) - { - QString pageNumString; - if (m_pagesCount>0) - { - pageNumString = i18nc("Page (number) of (total)", "Page %1 of %2",pageNumber+1,m_pagesCount); - } - else - { - pageNumString = i18n("Page %1",pageNumber+1); - } - painter.drawText((int)leftMargin, - (int)topMargin + m_pageHeight - m_mainLineSpacing, - m_pageWidth, m_mainLineSpacing, - Qt::AlignRight | Qt::AlignBottom, pageNumString); - } - } - - w = m_pageWidth; - h = m_pageHeight; - y = (int)topMargin ; - h -= (m_headerTextRect.height() + 1); - y += (m_headerTextRect.height() ); - if (m_settings->addTableBorders) - { - w -= 2; h -= 2; - } - if (m_settings->addPageNumbers) - { - h -= (m_mainLineSpacing*3/2 + 1); - } - - qCDebug(KGRAPHVIEWERLIB_LOG) << "(w, h) = (" << w << ", " << h <<")"; - if ( ( (m_settings->fitToOnePage) || - (m_painting.width()<=w && m_painting.height()<=h) ) - && !m_eof) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "single-page printing"; - if (paint) - { - QPixmap pix = m_painting.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation); - qCDebug(KGRAPHVIEWERLIB_LOG) << "drawPixmap"; - painter.drawPixmap((int)leftMargin, y, pix); + if (pageNumber <= m_pagesCount) { + m_eof = false; } - m_eof = true; - } - else if (m_settings->horizFitting != 0 || m_settings->vertFitting != 0) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "fitted multi-pages printing page " << pageNumber; - int nbTilesByRow = (int)(ceil((double)m_painting.width())/w) + 1; - qCDebug(KGRAPHVIEWERLIB_LOG) << " nb tiles by row = " << nbTilesByRow; - - int tileWidth = w; - int tileHeight = h; - - if (m_settings->horizFitting != 0) - { - tileWidth = int(ceil(((double)m_painting.width())/m_settings->horizFitting)); - nbTilesByRow = m_settings->horizFitting; + int w = 0, h = 0; + QPaintDevice *pdm = painter.device(); + const bool printer = pdm->devType() == QInternal::Printer; + qCDebug(KGRAPHVIEWERLIB_LOG) << "printer:" << printer; + + if (!printer) { + w = pdm->width(); + h = pdm->height(); + } else { // QPrinter... + w = pdm->widthMM(); + h = pdm->heightMM(); } - if (m_settings->vertFitting != 0) - { - tileHeight = int(ceil(((double)m_painting.height())/m_settings->vertFitting)); + + if (!m_paintInitialized) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "initializing"; + // HACK: some functions here do not work properly if were + // are not in a paint event, so repeat this until we actually paint. + m_paintInitialized = paint; + + double widthMM = KgvPageFormat::width(m_settings->pageLayout.format, m_settings->pageLayout.orientation); + double heightMM = KgvPageFormat::height(m_settings->pageLayout.format, m_settings->pageLayout.orientation); + + m_dpiY = pdm->logicalDpiY(); + m_dpiX = pdm->logicalDpiX(); +#ifdef Q_WS_WIN // fix for 120dpi + if (!printer) { + // m_dpiY = 96; + // m_dpiX = 96; + m_dpiY = 86; + m_dpiX = 86; + } +#endif + int pdWidthMM = pdm->widthMM(); + int pdHeightMM = pdm->heightMM(); + + double screenF; + // if (printer) + screenF = 1.0; + // else + // screenF = (double)96.0/120.0; + + leftMargin = POINT_TO_INCH(m_settings->pageLayout.ptLeft) * m_dpiX * screenF; + rightMargin = POINT_TO_INCH(m_settings->pageLayout.ptRight) * m_dpiX * screenF; + topMargin = POINT_TO_INCH(m_settings->pageLayout.ptTop) * m_dpiY * screenF; + bottomMargin = POINT_TO_INCH(m_settings->pageLayout.ptBottom) * m_dpiY * screenF; + + m_fx = widthMM / (pdWidthMM * screenF); + m_fy = heightMM / (pdHeightMM * screenF); + + // screen only + // painter.fillRect(QRect(0,0,w,h), QBrush(white)); + m_pageWidth = int(m_fx * (double)pdm->width() - leftMargin - rightMargin); + m_pageHeight = int(m_fy * (double)pdm->height() - topMargin - bottomMargin); + + //! @todo add setting + m_mainFont = m_settings->pageTitleFont; + if (!printer) { + int pixelSize = int(POINT_TO_INCH(m_mainFont.pointSizeF()) * m_dpiX); + m_mainFont.setPixelSize(pixelSize); + } + painter.setFont(m_mainFont); + + m_dateTimeText = QLocale().toString(QDateTime::currentDateTime()); + m_dateTimeWidth = 0; + if (m_settings->addDateAndTime) { + m_dateTimeWidth = painter.boundingRect(leftMargin, topMargin, m_pageWidth, m_pageHeight, Qt::AlignRight, m_dateTimeText + " ").width(); + } + m_mainLineSpacing = painter.fontMetrics().lineSpacing(); + m_headerTextRect = painter.boundingRect((int)leftMargin, (int)topMargin, m_pageWidth - m_dateTimeWidth, m_pageHeight, Qt::AlignLeft | Qt::TextWordWrap, m_headerText); + m_headerTextRect.setRight(m_headerTextRect.right() + 10); + m_headerTextRect.setWidth(qMin(int(m_pageWidth - m_dateTimeWidth), m_headerTextRect.width())); } - qCDebug(KGRAPHVIEWERLIB_LOG) << " tile size = "<chainedFittings) - { - scaleMode = Qt::KeepAspectRatio; - } - QPixmap pix = m_painting.copy(x1, y1, x2-x1+1, y2-y1+1); - if (m_settings->horizFitting == 0) - { - pix = pix.scaled(pix.width(), h, scaleMode, Qt::SmoothTransformation); - } - else if (m_settings->vertFitting == 0) - { - pix = pix.scaled(w, pix.height(), scaleMode, Qt::SmoothTransformation); - } - else - { - pix = pix.scaled(w, h, scaleMode, Qt::SmoothTransformation); - } - painter.drawPixmap((int)leftMargin, y, pix); + qCDebug(KGRAPHVIEWERLIB_LOG) << "after initialization"; + + // screen only + if (!printer) { + painter.setWindow(0, 0, int((double)w * m_fx), int((double)h * m_fy)); } - if ( x2 >= m_painting.width() && y2 >= m_painting.height() ) - { - m_eof = true; + + painter.setFont(m_mainFont); + if (paint) { + // paint header + painter.drawText(m_headerTextRect, Qt::AlignLeft | Qt::TextWordWrap, m_headerText); + if (m_settings->addDateAndTime) { + painter.drawText((int)leftMargin + m_pageWidth - m_dateTimeWidth, (int)topMargin, m_dateTimeWidth, m_headerTextRect.height(), Qt::AlignRight, m_dateTimeText); + } + + // footer + if (m_settings->addPageNumbers) { + QString pageNumString; + if (m_pagesCount > 0) { + pageNumString = i18nc("Page (number) of (total)", "Page %1 of %2", pageNumber + 1, m_pagesCount); + } else { + pageNumString = i18n("Page %1", pageNumber + 1); + } + painter.drawText((int)leftMargin, (int)topMargin + m_pageHeight - m_mainLineSpacing, m_pageWidth, m_mainLineSpacing, Qt::AlignRight | Qt::AlignBottom, pageNumString); + } } - } - else - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "multi-pages printing page " << pageNumber; - int nbTilesByRow = (int)(((double)m_painting.width())/w) + 1; - int rowNum = pageNumber / nbTilesByRow; - int columnNum = pageNumber % nbTilesByRow; - int x1, y1, x2, y2; - x1 = int(w * columnNum); - x2 = int(w * (columnNum+1)); - y1 = int(h * rowNum); - y2 = int(h * (rowNum+1)); - qCDebug(KGRAPHVIEWERLIB_LOG) << "(x1, y1, x2, 2) = ("<addTableBorders) { + w -= 2; + h -= 2; } - if ( x2 >= m_painting.width() && y2 >= m_painting.height() ) - { - m_eof = true; + if (m_settings->addPageNumbers) { + h -= (m_mainLineSpacing * 3 / 2 + 1); } - } - - if (m_settings->addTableBorders) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding table borders"; - int y1 = (int)topMargin ; - y1 += (m_headerTextRect.height()); - int y2 = (int)topMargin + m_pageHeight; - if (m_settings->addPageNumbers) - { - y2 -= (m_headerTextRect.height() /*+ m_mainLineSpacing*3/2*/ + 1); + + qCDebug(KGRAPHVIEWERLIB_LOG) << "(w, h) = (" << w << ", " << h << ")"; + if (((m_settings->fitToOnePage) || (m_painting.width() <= w && m_painting.height() <= h)) && !m_eof) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "single-page printing"; + if (paint) { + QPixmap pix = m_painting.scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation); + qCDebug(KGRAPHVIEWERLIB_LOG) << "drawPixmap"; + painter.drawPixmap((int)leftMargin, y, pix); + } + m_eof = true; + } else if (m_settings->horizFitting != 0 || m_settings->vertFitting != 0) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "fitted multi-pages printing page " << pageNumber; + int nbTilesByRow = (int)(ceil((double)m_painting.width()) / w) + 1; + qCDebug(KGRAPHVIEWERLIB_LOG) << " nb tiles by row = " << nbTilesByRow; + + int tileWidth = w; + int tileHeight = h; + + if (m_settings->horizFitting != 0) { + tileWidth = int(ceil(((double)m_painting.width()) / m_settings->horizFitting)); + nbTilesByRow = m_settings->horizFitting; + } + if (m_settings->vertFitting != 0) { + tileHeight = int(ceil(((double)m_painting.height()) / m_settings->vertFitting)); + } + qCDebug(KGRAPHVIEWERLIB_LOG) << " tile size = " << tileWidth << "/" << tileHeight; + int rowNum = pageNumber / nbTilesByRow; + int columnNum = pageNumber % nbTilesByRow; + int x1, y1, x2, y2; + x1 = int(tileWidth * columnNum); + x2 = int(tileWidth * (columnNum + 1)); + y1 = int(tileHeight * rowNum); + y2 = int(tileHeight * (rowNum + 1)); + qCDebug(KGRAPHVIEWERLIB_LOG) << "(x1, y1, x2, 2) = (" << x1 << "," << y1 << "," << x2 << "," << y2 << ")"; + qCDebug(KGRAPHVIEWERLIB_LOG) << "painting size = (" << m_painting.width() << "/" << m_painting.height() << ")"; + if (paint) { + Qt::AspectRatioMode scaleMode = Qt::IgnoreAspectRatio; + if (m_settings->chainedFittings) { + scaleMode = Qt::KeepAspectRatio; + } + QPixmap pix = m_painting.copy(x1, y1, x2 - x1 + 1, y2 - y1 + 1); + if (m_settings->horizFitting == 0) { + pix = pix.scaled(pix.width(), h, scaleMode, Qt::SmoothTransformation); + } else if (m_settings->vertFitting == 0) { + pix = pix.scaled(w, pix.height(), scaleMode, Qt::SmoothTransformation); + } else { + pix = pix.scaled(w, h, scaleMode, Qt::SmoothTransformation); + } + painter.drawPixmap((int)leftMargin, y, pix); + } + if (x2 >= m_painting.width() && y2 >= m_painting.height()) { + m_eof = true; + } + } else { + qCDebug(KGRAPHVIEWERLIB_LOG) << "multi-pages printing page " << pageNumber; + int nbTilesByRow = (int)(((double)m_painting.width()) / w) + 1; + int rowNum = pageNumber / nbTilesByRow; + int columnNum = pageNumber % nbTilesByRow; + int x1, y1, x2, y2; + x1 = int(w * columnNum); + x2 = int(w * (columnNum + 1)); + y1 = int(h * rowNum); + y2 = int(h * (rowNum + 1)); + qCDebug(KGRAPHVIEWERLIB_LOG) << "(x1, y1, x2, 2) = (" << x1 << "," << y1 << "," << x2 << "," << y2 << ")"; + if (paint) { + painter.drawPixmap((int)leftMargin, y, m_painting.copy(x1, y1, x2 - x1 + 1, y2 - y1 + 1)); + } + if (x2 >= m_painting.width() && y2 >= m_painting.height()) { + m_eof = true; + } } - if (paint) - { - painter.drawLine((int)leftMargin, y1, (int)leftMargin + m_pageWidth-1, y1); - painter.drawLine((int)leftMargin + m_pageWidth-1, y1, (int)leftMargin + m_pageWidth-1, y2); - painter.drawLine((int)leftMargin + m_pageWidth-1, y2, (int)leftMargin, y2); - painter.drawLine((int)leftMargin, y2, (int)leftMargin, y1); + + if (m_settings->addTableBorders) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "Adding table borders"; + int y1 = (int)topMargin; + y1 += (m_headerTextRect.height()); + int y2 = (int)topMargin + m_pageHeight; + if (m_settings->addPageNumbers) { + y2 -= (m_headerTextRect.height() /*+ m_mainLineSpacing*3/2*/ + 1); + } + if (paint) { + painter.drawLine((int)leftMargin, y1, (int)leftMargin + m_pageWidth - 1, y1); + painter.drawLine((int)leftMargin + m_pageWidth - 1, y1, (int)leftMargin + m_pageWidth - 1, y2); + painter.drawLine((int)leftMargin + m_pageWidth - 1, y2, (int)leftMargin, y2); + painter.drawLine((int)leftMargin, y2, (int)leftMargin, y1); + } } - } - qCDebug(KGRAPHVIEWERLIB_LOG) << "paintPage done"; + qCDebug(KGRAPHVIEWERLIB_LOG) << "paintPage done"; } -void KGVSimplePrintingEngine::calculatePagesCount(QPainter& painter) +void KGVSimplePrintingEngine::calculatePagesCount(QPainter &painter) { - if (m_eof || !m_data) { - m_pagesCount = 0; - return; - } - - uint pageNumber = 0; - if (m_settings->fitToOnePage) - { - m_pagesCount = 1; - } - else - { - for(;!m_eof; ++pageNumber) { - paintPage(pageNumber, painter, false /* !paint */); + if (m_eof || !m_data) { + m_pagesCount = 0; + return; + } + + uint pageNumber = 0; + if (m_settings->fitToOnePage) { + m_pagesCount = 1; + } else { + for (; !m_eof; ++pageNumber) { + paintPage(pageNumber, painter, false /* !paint */); + } + m_pagesCount = pageNumber; } - m_pagesCount = pageNumber; - } } -void KGVSimplePrintingEngine::setTitleText(const QString& titleText) +void KGVSimplePrintingEngine::setTitleText(const QString &titleText) { - m_headerText = titleText; + m_headerText = titleText; } uint KGVSimplePrintingEngine::maxHorizFit() const { - uint w = m_pageWidth; - if (m_settings->addTableBorders) - { - w -= 2; - } -// () << "maxHorizFit: " << m_painting.width() << " / " << w -// << " = " << m_painting.width()/w; - return (uint)ceil(((double)m_painting.width())/w) + 1; + uint w = m_pageWidth; + if (m_settings->addTableBorders) { + w -= 2; + } + // () << "maxHorizFit: " << m_painting.width() << " / " << w + // << " = " << m_painting.width()/w; + return (uint)ceil(((double)m_painting.width()) / w) + 1; } uint KGVSimplePrintingEngine::maxVertFit() const { - uint h = m_pageHeight; - h -= (m_headerTextRect.height() + 1); - if (m_settings->addTableBorders) - { - h -= 2; - } - if (m_settings->addPageNumbers) - { - h -= (m_mainLineSpacing*3/2 + 1); - } -// qCDebug(KGRAPHVIEWERLIB_LOG) << "maxVertFit: " << m_painting.height() << " / " << h -// << " = " << m_painting.height()/h; - return (uint)ceil(((double)m_painting.height()))/h + 1; + uint h = m_pageHeight; + h -= (m_headerTextRect.height() + 1); + if (m_settings->addTableBorders) { + h -= 2; + } + if (m_settings->addPageNumbers) { + h -= (m_mainLineSpacing * 3 / 2 + 1); + } + // qCDebug(KGRAPHVIEWERLIB_LOG) << "maxVertFit: " << m_painting.height() << " / " << h + // << " = " << m_painting.height()/h; + return (uint)ceil(((double)m_painting.height())) / h + 1; } } diff --git a/src/part/simpleprintingpagesetup.h b/src/part/simpleprintingpagesetup.h --- a/src/part/simpleprintingpagesetup.h +++ b/src/part/simpleprintingpagesetup.h @@ -32,68 +32,67 @@ #include -namespace Ui { - class KGVSimplePrintingPageSetupBase; +namespace Ui +{ +class KGVSimplePrintingPageSetupBase; } namespace KGraphViewer { - class DotGraphView; class KGVSimplePrintingCommand; class KgvPageLayoutSize; //! @short A window for displaying settings for simple printing. class KGVSimplePrintingPageSetup : public QWidget { - Q_OBJECT - - public: - KGVSimplePrintingPageSetup(KGVSimplePrintingCommand* command, - DotGraphView *mainWin, QWidget *parent, QMap* args ); - ~KGVSimplePrintingPageSetup(); - - public Q_SLOTS: - void slotPrint(); - void slotPrintPreview(); - - Q_SIGNALS: - void print(KGVSimplePrintingSettings* settings, const QString& titleText); - void printPreview(KGVSimplePrintingSettings* settings, const QString& titleText, bool reload); - void print(); - void printPreview(); + Q_OBJECT + +public: + KGVSimplePrintingPageSetup(KGVSimplePrintingCommand *command, DotGraphView *mainWin, QWidget *parent, QMap *args); + ~KGVSimplePrintingPageSetup(); + +public Q_SLOTS: + void slotPrint(); + void slotPrintPreview(); + +Q_SIGNALS: + void print(KGVSimplePrintingSettings *settings, const QString &titleText); + void printPreview(KGVSimplePrintingSettings *settings, const QString &titleText, bool reload); + void print(); + void printPreview(); void needsRedraw(); - protected Q_SLOTS: - void slotSaveSetup(); - void slotChangeTitleFont(); - void slotChangePageSizeAndMargins(); - void slotAddPageNumbersCheckboxToggled(bool set); - void slotAddDateTimeCheckboxToggled(bool set); - void slotAddTableBordersCheckboxToggled(bool set); - void slotTitleTextChanged(const QString&); +protected Q_SLOTS: + void slotSaveSetup(); + void slotChangeTitleFont(); + void slotChangePageSizeAndMargins(); + void slotAddPageNumbersCheckboxToggled(bool set); + void slotAddDateTimeCheckboxToggled(bool set); + void slotAddTableBordersCheckboxToggled(bool set); + void slotTitleTextChanged(const QString &); void slotClose(); void slotFittingButtonClicked(int id); void slotHorizFitChanged(int newValue); void slotVertFitChanged(int newValue); void slotMaintainAspectButtonToggled(); - protected: - void setupPrintingCommand(); - void updatePageLayoutAndUnitInfo(); - void setDirty(bool set); +protected: + void setupPrintingCommand(); + void updatePageLayoutAndUnitInfo(); + void setDirty(bool set); + + KGVSimplePrintingSettings *m_settings; - KGVSimplePrintingSettings* m_settings; + // KGVSimplePrintingEngine *m_engine; + // get engine with m_command->engine() -// KGVSimplePrintingEngine *m_engine; -// get engine with m_command->engine() + KgvUnit::Unit m_unit; + Ui::KGVSimplePrintingPageSetupBase *m_contents; + KgvPageLayoutSize *m_pageLayoutWidget; + DotGraphView *m_graphView; + KGVSimplePrintingCommand *m_command; + bool m_printPreviewNeedsReloading : 1; - KgvUnit::Unit m_unit; - Ui::KGVSimplePrintingPageSetupBase *m_contents; - KgvPageLayoutSize *m_pageLayoutWidget; - DotGraphView *m_graphView; - KGVSimplePrintingCommand *m_command; - bool m_printPreviewNeedsReloading : 1; - QButtonGroup m_fittingModeButtons; }; diff --git a/src/part/simpleprintingpagesetup.cpp b/src/part/simpleprintingpagesetup.cpp --- a/src/part/simpleprintingpagesetup.cpp +++ b/src/part/simpleprintingpagesetup.cpp @@ -26,379 +26,330 @@ */ #include "simpleprintingpagesetup.h" -#include "ui_simpleprintingpagesetupbase.h" -#include "simpleprintingsettings.h" -#include "simpleprintingcommand.h" -#include "simpleprintpreviewwindow.h" #include "dotgraphview.h" #include "kgraphviewerlib_debug.h" +#include "simpleprintingcommand.h" +#include "simpleprintingsettings.h" +#include "simpleprintpreviewwindow.h" +#include "ui_simpleprintingpagesetupbase.h" #include -#include -#include +#include #include +#include #include -#include #include -#include #include +#include #include +#include #include +#include +#include #include -#include #include #include -#include -#include #include -#include -//Added by qt3to4: +#include +#include +// Added by qt3to4: +#include #include #include -#include -#include #include +#include namespace KGraphViewer { - - -KGVSimplePrintingPageSetup::KGVSimplePrintingPageSetup( - KGVSimplePrintingCommand* command, DotGraphView *mainWin, QWidget *parent, - QMap* args ) - : QWidget(parent) - , m_settings( command->engine()->settings() ) - , m_command(command) +KGVSimplePrintingPageSetup::KGVSimplePrintingPageSetup(KGVSimplePrintingCommand *command, DotGraphView *mainWin, QWidget *parent, QMap *args) + : QWidget(parent) + , m_settings(command->engine()->settings()) + , m_command(command) { - setObjectName("KGVSimplePrintingPageSetup"); - // object to print - bool ok = args; + setObjectName("KGVSimplePrintingPageSetup"); + // object to print + bool ok = args; m_graphView = mainWin; - ok = m_graphView; - - bool printPreview = false; - bool print = false; - bool pageSetup = false; - if (ok) { - printPreview = (*args)["action"]=="printPreview"; - print = (*args)["action"]=="print"; - pageSetup = (*args)["action"]=="pageSetup"; - ok = printPreview || print || pageSetup; - } - - - // settings -//! @todo default? - m_unit = QLocale().measurementSystem() == QLocale::MetricSystem ? KgvUnit::U_CM : KgvUnit::U_INCH; - - // GUI - m_contents = new Ui::KGVSimplePrintingPageSetupBase(); - m_contents->setupUi(this); - layout()->setMargin(0); - - setFocusPolicy(Qt::WheelFocus); -// m_contents->setFocusProxy(m_contents->headerTitleLineEdit); - - m_contents->printButton->setIcon( QIcon::fromTheme("printer") ); - connect(m_contents->printButton, &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotPrint); - - m_contents->printPreviewButton->setIcon( QIcon::fromTheme("document-print-preview") ); - m_contents->printPreviewButton->setText( i18n("Print Preview...") ); - connect(m_contents->printPreviewButton, &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotPrintPreview); - - m_contents->iconLabel->setFixedWidth(32+6); + ok = m_graphView; + + bool printPreview = false; + bool print = false; + bool pageSetup = false; + if (ok) { + printPreview = (*args)["action"] == "printPreview"; + print = (*args)["action"] == "print"; + pageSetup = (*args)["action"] == "pageSetup"; + ok = printPreview || print || pageSetup; + } + + // settings + //! @todo default? + m_unit = QLocale().measurementSystem() == QLocale::MetricSystem ? KgvUnit::U_CM : KgvUnit::U_INCH; + + // GUI + m_contents = new Ui::KGVSimplePrintingPageSetupBase(); + m_contents->setupUi(this); + layout()->setMargin(0); + + setFocusPolicy(Qt::WheelFocus); + // m_contents->setFocusProxy(m_contents->headerTitleLineEdit); + + m_contents->printButton->setIcon(QIcon::fromTheme("printer")); + connect(m_contents->printButton, &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotPrint); + + m_contents->printPreviewButton->setIcon(QIcon::fromTheme("document-print-preview")); + m_contents->printPreviewButton->setText(i18n("Print Preview...")); + connect(m_contents->printPreviewButton, &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotPrintPreview); + + m_contents->iconLabel->setFixedWidth(32 + 6); const int iconSize = KIconTheme(KIconTheme::current()).defaultSize(KIconLoader::Small); - m_contents->iconLabel->setPixmap(QIcon::fromTheme("distribute-horizontal-page").pixmap(iconSize, iconSize)); - m_contents->headerTitleFontButton->setText(i18n("Font...")); - m_contents->headerTitleFontButton->setWhatsThis(i18n("Changes font for title text.")); - connect(m_contents->headerTitleFontButton, &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotChangeTitleFont); - - if (m_graphView) - { - m_contents->headerTitleLineEdit->setText((*args)["title"]); - QString origCaptionLabelText = m_contents->captionLabel->text(); - m_contents->captionLabel->setText( i18n("

Page Setup for Printing Graph \"%1\"

", - QUrl::fromLocalFile(m_graphView->dotFileName()).fileName() - ) ); - } - connect(m_contents->headerTitleLineEdit, &QLineEdit::textChanged, - this, &KGVSimplePrintingPageSetup::slotTitleTextChanged); - m_contents->headerTitleLineEdit->setFont( m_settings->pageTitleFont ); - - m_contents->saveSetupLink->setWhatsThis(i18n("Saves settings for this setup as default.")); - connect(m_contents->saveSetupLink, static_cast(&KUrlLabel::leftClickedUrl), - this, &KGVSimplePrintingPageSetup::slotSaveSetup); - - m_contents->addDateTimeCheckbox->setWhatsThis(i18n("Adds date and time to the header.")); - m_contents->addPageNumbersCheckbox->setWhatsThis(i18n("Adds page numbers to the footer.")); - m_contents->addTableBordersCheckbox->setWhatsThis(i18n("Adds table borders.")); - -#ifdef KGV_NO_UNFINISHED - m_contents->addDateTimeCheckbox->hide(); - m_contents->addPageNumbersCheckbox->hide(); + m_contents->iconLabel->setPixmap(QIcon::fromTheme("distribute-horizontal-page").pixmap(iconSize, iconSize)); + m_contents->headerTitleFontButton->setText(i18n("Font...")); + m_contents->headerTitleFontButton->setWhatsThis(i18n("Changes font for title text.")); + connect(m_contents->headerTitleFontButton, &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotChangeTitleFont); + + if (m_graphView) { + m_contents->headerTitleLineEdit->setText((*args)["title"]); + QString origCaptionLabelText = m_contents->captionLabel->text(); + m_contents->captionLabel->setText(i18n("

Page Setup for Printing Graph \"%1\"

", QUrl::fromLocalFile(m_graphView->dotFileName()).fileName())); + } + connect(m_contents->headerTitleLineEdit, &QLineEdit::textChanged, this, &KGVSimplePrintingPageSetup::slotTitleTextChanged); + m_contents->headerTitleLineEdit->setFont(m_settings->pageTitleFont); + + m_contents->saveSetupLink->setWhatsThis(i18n("Saves settings for this setup as default.")); + connect(m_contents->saveSetupLink, static_cast(&KUrlLabel::leftClickedUrl), this, &KGVSimplePrintingPageSetup::slotSaveSetup); + + m_contents->addDateTimeCheckbox->setWhatsThis(i18n("Adds date and time to the header.")); + m_contents->addPageNumbersCheckbox->setWhatsThis(i18n("Adds page numbers to the footer.")); + m_contents->addTableBordersCheckbox->setWhatsThis(i18n("Adds table borders.")); + +#ifdef KGV_NO_UNFINISHED + m_contents->addDateTimeCheckbox->hide(); + m_contents->addPageNumbersCheckbox->hide(); #endif - updatePageLayoutAndUnitInfo(); - m_contents->changePageSizeAndMarginsButton->setText(i18n("Change Page Size and Margins...")); - m_contents->changePageSizeAndMarginsButton->setWhatsThis(i18n("Changes page size and margins.")); - connect(m_contents->changePageSizeAndMarginsButton, &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotChangePageSizeAndMargins); - - connect(m_contents->addPageNumbersCheckbox, &QCheckBox::toggled, - this, &KGVSimplePrintingPageSetup::slotAddPageNumbersCheckboxToggled); - connect(m_contents->addDateTimeCheckbox, &QCheckBox::toggled, - this, &KGVSimplePrintingPageSetup::slotAddDateTimeCheckboxToggled); - connect(m_contents->addTableBordersCheckbox, &QCheckBox::toggled, - this, &KGVSimplePrintingPageSetup::slotAddTableBordersCheckboxToggled); - - -// - m_contents->addPageNumbersCheckbox->setChecked( m_settings->addPageNumbers ); - m_contents->addDateTimeCheckbox->setChecked( m_settings->addDateAndTime ); - m_contents->addTableBordersCheckbox->setChecked( m_settings->addTableBorders ); - setDirty(false); - - // clear it back to false after widgets initialization - m_printPreviewNeedsReloading = false; - - if (printPreview) - QTimer::singleShot(50, this, SLOT(printPreview())); - else if (print) - QTimer::singleShot(50, this, SLOT(print())); - connect(this, static_cast(&KGVSimplePrintingPageSetup::print), - m_graphView, &DotGraphView::print); - connect(this, static_cast(&KGVSimplePrintingPageSetup::printPreview), - m_graphView, &DotGraphView::printPreview); - - connect(m_contents->buttonBox->button(QDialogButtonBox::Close), &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotClose); - - - m_contents->horizFitNumInput->setRange(1,m_command->engine()->maxHorizFit()); - m_contents->vertFitNumInput->setRange(1,m_command->engine()->maxVertFit()); - m_settings->horizFitting = m_command->engine()->maxHorizFit(); - m_settings->vertFitting = m_command->engine()->maxVertFit(); - m_contents->horizFitNumInput->setValue(m_settings->horizFitting); - m_contents->vertFitNumInput->setValue(m_settings->vertFitting); - connect(m_contents->maintainAspectButton, &QPushButton::clicked, - this, &KGVSimplePrintingPageSetup::slotMaintainAspectButtonToggled); - connect(m_contents->horizFitNumInput, static_cast(&QSpinBox::valueChanged), - this, &KGVSimplePrintingPageSetup::slotHorizFitChanged); - connect(m_contents->vertFitNumInput, static_cast(&QSpinBox::valueChanged), - this, &KGVSimplePrintingPageSetup::slotVertFitChanged); - - - m_fittingModeButtons.addButton(m_contents->naturalSizeRadioButton, NaturalSize); - m_fittingModeButtons.addButton(m_contents->fitToOnePageRadioButton, FitToOnePage); - m_fittingModeButtons.addButton(m_contents->fitToSeveralPagesRadioButton, FitToSeveralPages); - connect(&m_fittingModeButtons, static_cast(&QButtonGroup::buttonClicked), - this, &KGVSimplePrintingPageSetup::slotFittingButtonClicked); - - m_fittingModeButtons.button(m_settings->fittingMode)->setChecked(true); - if (m_settings->fittingMode != FitToSeveralPages) - { - m_contents->horizFitNumInput->setEnabled(false); - m_contents->vertFitNumInput->setEnabled(false); - m_contents->maintainAspectButton->setEnabled(false); - } - - QString chainStatePixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain.png"); - if (!m_settings->chainedFittings) - { - chainStatePixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain-broken.png"); - } - if (chainStatePixString.isNull()) - { - std::cerr << "chain state pixmap not found !" << std::endl; - } - m_contents->maintainAspectButton->setIcon(QPixmap(chainStatePixString)); - - // hides currently unused title label - m_contents->headerTitleLineEdit->setText(i18n("Chosen font looks like this")); - m_contents->headerTitleLineEdit->setReadOnly(true); + updatePageLayoutAndUnitInfo(); + m_contents->changePageSizeAndMarginsButton->setText(i18n("Change Page Size and Margins...")); + m_contents->changePageSizeAndMarginsButton->setWhatsThis(i18n("Changes page size and margins.")); + connect(m_contents->changePageSizeAndMarginsButton, &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotChangePageSizeAndMargins); + + connect(m_contents->addPageNumbersCheckbox, &QCheckBox::toggled, this, &KGVSimplePrintingPageSetup::slotAddPageNumbersCheckboxToggled); + connect(m_contents->addDateTimeCheckbox, &QCheckBox::toggled, this, &KGVSimplePrintingPageSetup::slotAddDateTimeCheckboxToggled); + connect(m_contents->addTableBordersCheckbox, &QCheckBox::toggled, this, &KGVSimplePrintingPageSetup::slotAddTableBordersCheckboxToggled); + + // + m_contents->addPageNumbersCheckbox->setChecked(m_settings->addPageNumbers); + m_contents->addDateTimeCheckbox->setChecked(m_settings->addDateAndTime); + m_contents->addTableBordersCheckbox->setChecked(m_settings->addTableBorders); + setDirty(false); + + // clear it back to false after widgets initialization + m_printPreviewNeedsReloading = false; + + if (printPreview) + QTimer::singleShot(50, this, SLOT(printPreview())); + else if (print) + QTimer::singleShot(50, this, SLOT(print())); + connect(this, static_cast(&KGVSimplePrintingPageSetup::print), m_graphView, &DotGraphView::print); + connect(this, static_cast(&KGVSimplePrintingPageSetup::printPreview), m_graphView, &DotGraphView::printPreview); + + connect(m_contents->buttonBox->button(QDialogButtonBox::Close), &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotClose); + + m_contents->horizFitNumInput->setRange(1, m_command->engine()->maxHorizFit()); + m_contents->vertFitNumInput->setRange(1, m_command->engine()->maxVertFit()); + m_settings->horizFitting = m_command->engine()->maxHorizFit(); + m_settings->vertFitting = m_command->engine()->maxVertFit(); + m_contents->horizFitNumInput->setValue(m_settings->horizFitting); + m_contents->vertFitNumInput->setValue(m_settings->vertFitting); + connect(m_contents->maintainAspectButton, &QPushButton::clicked, this, &KGVSimplePrintingPageSetup::slotMaintainAspectButtonToggled); + connect(m_contents->horizFitNumInput, static_cast(&QSpinBox::valueChanged), this, &KGVSimplePrintingPageSetup::slotHorizFitChanged); + connect(m_contents->vertFitNumInput, static_cast(&QSpinBox::valueChanged), this, &KGVSimplePrintingPageSetup::slotVertFitChanged); + + m_fittingModeButtons.addButton(m_contents->naturalSizeRadioButton, NaturalSize); + m_fittingModeButtons.addButton(m_contents->fitToOnePageRadioButton, FitToOnePage); + m_fittingModeButtons.addButton(m_contents->fitToSeveralPagesRadioButton, FitToSeveralPages); + connect(&m_fittingModeButtons, static_cast(&QButtonGroup::buttonClicked), this, &KGVSimplePrintingPageSetup::slotFittingButtonClicked); + + m_fittingModeButtons.button(m_settings->fittingMode)->setChecked(true); + if (m_settings->fittingMode != FitToSeveralPages) { + m_contents->horizFitNumInput->setEnabled(false); + m_contents->vertFitNumInput->setEnabled(false); + m_contents->maintainAspectButton->setEnabled(false); + } + + QString chainStatePixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain.png"); + if (!m_settings->chainedFittings) { + chainStatePixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain-broken.png"); + } + if (chainStatePixString.isNull()) { + std::cerr << "chain state pixmap not found !" << std::endl; + } + m_contents->maintainAspectButton->setIcon(QPixmap(chainStatePixString)); + + // hides currently unused title label + m_contents->headerTitleLineEdit->setText(i18n("Chosen font looks like this")); + m_contents->headerTitleLineEdit->setReadOnly(true); } KGVSimplePrintingPageSetup::~KGVSimplePrintingPageSetup() { - delete m_contents; + delete m_contents; } void KGVSimplePrintingPageSetup::updatePageLayoutAndUnitInfo() { - QString s; - if (m_settings->pageLayout.format == PG_CUSTOM) { - s += QString(" (%1 %2 x %3 %4)") - .arg(m_settings->pageLayout.ptWidth).arg(KgvUnit::unitName(m_unit)) - .arg(m_settings->pageLayout.ptHeight).arg(KgvUnit::unitName(m_unit)); - } - else - s += KgvPageFormat::name(m_settings->pageLayout.format); - s += QString(", ") - + (m_settings->pageLayout.orientation == PG_PORTRAIT ? i18n("Portrait") : i18n("Landscape")) - + ", " + i18n("margins:") - + ' ' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptLeft, m_unit) - + '/' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptRight, m_unit) - + '/' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptTop, m_unit) - + '/' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptBottom, m_unit) - + ' ' + KgvUnit::unitName(m_unit); - m_contents->pageSizeAndMarginsLabel->setText( s ); - m_contents->horizFitNumInput->setRange(1,m_command->engine()->maxHorizFit()); - m_contents->vertFitNumInput->setRange(1,m_command->engine()->maxVertFit()); + QString s; + if (m_settings->pageLayout.format == PG_CUSTOM) { + s += QString(" (%1 %2 x %3 %4)").arg(m_settings->pageLayout.ptWidth).arg(KgvUnit::unitName(m_unit)).arg(m_settings->pageLayout.ptHeight).arg(KgvUnit::unitName(m_unit)); + } else + s += KgvPageFormat::name(m_settings->pageLayout.format); + s += QString(", ") + (m_settings->pageLayout.orientation == PG_PORTRAIT ? i18n("Portrait") : i18n("Landscape")) + ", " + i18n("margins:") + ' ' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptLeft, m_unit) + '/' + + KgvUnit::toUserStringValue(m_settings->pageLayout.ptRight, m_unit) + '/' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptTop, m_unit) + '/' + KgvUnit::toUserStringValue(m_settings->pageLayout.ptBottom, m_unit) + ' ' + + KgvUnit::unitName(m_unit); + m_contents->pageSizeAndMarginsLabel->setText(s); + m_contents->horizFitNumInput->setRange(1, m_command->engine()->maxHorizFit()); + m_contents->vertFitNumInput->setRange(1, m_command->engine()->maxVertFit()); } void KGVSimplePrintingPageSetup::setDirty(bool set) { - m_contents->saveSetupLink->setEnabled(set); - if (set) - { - m_printPreviewNeedsReloading = true; - m_command->engine()->clear(); - emit needsRedraw(); - } + m_contents->saveSetupLink->setEnabled(set); + if (set) { + m_printPreviewNeedsReloading = true; + m_command->engine()->clear(); + emit needsRedraw(); + } } void KGVSimplePrintingPageSetup::slotSaveSetup() { - m_settings->save(); - setDirty(false); + m_settings->save(); + setDirty(false); } void KGVSimplePrintingPageSetup::slotPrint() { - emit print(); + emit print(); } void KGVSimplePrintingPageSetup::slotPrintPreview() { - emit printPreview(); - m_printPreviewNeedsReloading = false; + emit printPreview(); + m_printPreviewNeedsReloading = false; } -void KGVSimplePrintingPageSetup::slotTitleTextChanged(const QString&) +void KGVSimplePrintingPageSetup::slotTitleTextChanged(const QString &) { - if (m_contents->headerTitleLineEdit->isModified()) { - m_printPreviewNeedsReloading = true; - } - - m_contents->headerTitleLineEdit->setModified(false); - setDirty(true); + if (m_contents->headerTitleLineEdit->isModified()) { + m_printPreviewNeedsReloading = true; + } + + m_contents->headerTitleLineEdit->setModified(false); + setDirty(true); } void KGVSimplePrintingPageSetup::slotChangeTitleFont() { bool ok; QFont font = QFontDialog::getFont(&ok, m_settings->pageTitleFont, this); - if (!ok) return; + if (!ok) + return; m_settings->pageTitleFont = font; - m_contents->headerTitleLineEdit->setFont( m_settings->pageTitleFont ); - setDirty(true); + m_contents->headerTitleLineEdit->setFont(m_settings->pageTitleFont); + setDirty(true); } void KGVSimplePrintingPageSetup::slotChangePageSizeAndMargins() { - KgvHeadFoot headfoot; //dummy -// std::cerr << "PageLayout before: " << m_settings->pageLayout.orientation << std::endl; - if (int(QDialog::Accepted) != KgvPageLayoutDia::pageLayout( - m_settings->pageLayout, headfoot, FORMAT_AND_BORDERS | DISABLE_UNIT, m_unit, this )) - return; - -// std::cerr << "PageLayout after: " << m_settings->pageLayout.orientation << std::endl; - //update - updatePageLayoutAndUnitInfo(); - setDirty(true); + KgvHeadFoot headfoot; // dummy + // std::cerr << "PageLayout before: " << m_settings->pageLayout.orientation << std::endl; + if (int(QDialog::Accepted) != KgvPageLayoutDia::pageLayout(m_settings->pageLayout, headfoot, FORMAT_AND_BORDERS | DISABLE_UNIT, m_unit, this)) + return; + + // std::cerr << "PageLayout after: " << m_settings->pageLayout.orientation << std::endl; + // update + updatePageLayoutAndUnitInfo(); + setDirty(true); } void KGVSimplePrintingPageSetup::slotAddPageNumbersCheckboxToggled(bool set) { - m_settings->addPageNumbers = set; - setDirty(true); + m_settings->addPageNumbers = set; + setDirty(true); } void KGVSimplePrintingPageSetup::slotAddDateTimeCheckboxToggled(bool set) { - m_settings->addDateAndTime = set; - setDirty(true); + m_settings->addDateAndTime = set; + setDirty(true); } void KGVSimplePrintingPageSetup::slotAddTableBordersCheckboxToggled(bool set) { - m_settings->addTableBorders = set; - setDirty(true); + m_settings->addTableBorders = set; + setDirty(true); } void KGVSimplePrintingPageSetup::slotFittingButtonClicked(int id) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "KGVSimplePrintingPageSetup::slotFittingButtonClicked " << id; - if (id == NaturalSize) - { - m_settings->fitToOnePage = false; - m_contents->horizFitNumInput->setEnabled(false); - m_contents->vertFitNumInput->setEnabled(false); - m_contents->maintainAspectButton->setEnabled(false); - } - else if (id == FitToOnePage) - { - m_settings->fitToOnePage = true; - m_contents->horizFitNumInput->setEnabled(false); - m_contents->vertFitNumInput->setEnabled(false); - m_contents->maintainAspectButton->setEnabled(false); - } - else if (id == FitToSeveralPages) - { - m_settings->fitToOnePage = false; - m_contents->horizFitNumInput->setEnabled(true); - m_contents->vertFitNumInput->setEnabled(true); - m_contents->maintainAspectButton->setEnabled(true); - } - setDirty(true); + qCDebug(KGRAPHVIEWERLIB_LOG) << "KGVSimplePrintingPageSetup::slotFittingButtonClicked " << id; + if (id == NaturalSize) { + m_settings->fitToOnePage = false; + m_contents->horizFitNumInput->setEnabled(false); + m_contents->vertFitNumInput->setEnabled(false); + m_contents->maintainAspectButton->setEnabled(false); + } else if (id == FitToOnePage) { + m_settings->fitToOnePage = true; + m_contents->horizFitNumInput->setEnabled(false); + m_contents->vertFitNumInput->setEnabled(false); + m_contents->maintainAspectButton->setEnabled(false); + } else if (id == FitToSeveralPages) { + m_settings->fitToOnePage = false; + m_contents->horizFitNumInput->setEnabled(true); + m_contents->vertFitNumInput->setEnabled(true); + m_contents->maintainAspectButton->setEnabled(true); + } + setDirty(true); } void KGVSimplePrintingPageSetup::slotMaintainAspectButtonToggled() { - if (m_settings->chainedFittings) - { - QString chainBreakPixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain-broken.png"); - if (chainBreakPixString.isNull()) - { - std::cerr << "chain break pixmap not found !" << std::endl; - } - m_contents->maintainAspectButton->setIcon(QPixmap(chainBreakPixString)); - m_settings->chainedFittings = false; - } - else - { - QString chainPixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain.png"); - if (chainPixString.isNull()) - { - std::cerr << "chain pixmap not found !" << std::endl; + if (m_settings->chainedFittings) { + QString chainBreakPixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain-broken.png"); + if (chainBreakPixString.isNull()) { + std::cerr << "chain break pixmap not found !" << std::endl; + } + m_contents->maintainAspectButton->setIcon(QPixmap(chainBreakPixString)); + m_settings->chainedFittings = false; + } else { + QString chainPixString = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kgraphviewerpart/pics/chain.png"); + if (chainPixString.isNull()) { + std::cerr << "chain pixmap not found !" << std::endl; + } + m_contents->maintainAspectButton->setIcon(QPixmap(chainPixString)); + m_settings->chainedFittings = true; } - m_contents->maintainAspectButton->setIcon(QPixmap(chainPixString)); - m_settings->chainedFittings = true; - } - emit needsRedraw(); + emit needsRedraw(); } void KGVSimplePrintingPageSetup::slotClose() { - parentWidget()->hide(); + parentWidget()->hide(); } void KGVSimplePrintingPageSetup::slotHorizFitChanged(int newValue) { - m_settings->horizFitting = newValue; - m_printPreviewNeedsReloading = true; - emit needsRedraw(); + m_settings->horizFitting = newValue; + m_printPreviewNeedsReloading = true; + emit needsRedraw(); } void KGVSimplePrintingPageSetup::slotVertFitChanged(int newValue) { - m_settings->vertFitting = newValue; - m_printPreviewNeedsReloading = true; - emit needsRedraw(); + m_settings->vertFitting = newValue; + m_printPreviewNeedsReloading = true; + emit needsRedraw(); } } diff --git a/src/part/simpleprintingsettings.h b/src/part/simpleprintingsettings.h --- a/src/part/simpleprintingsettings.h +++ b/src/part/simpleprintingsettings.h @@ -32,35 +32,29 @@ namespace KGraphViewer { - -enum FittingModes -{ - NaturalSize = 0, - FitToOnePage, - FitToSeveralPages -}; +enum FittingModes { NaturalSize = 0, FitToOnePage, FitToSeveralPages }; //! @short Settings data for simple printing engine. class KGVSimplePrintingSettings { public: - KGVSimplePrintingSettings(); - ~KGVSimplePrintingSettings(); - - static KGVSimplePrintingSettings load(); - void save(); - - KgvPageLayout pageLayout; - KgvUnit::Unit unit; - QFont pageTitleFont; - bool addPageNumbers; - bool addDateAndTime; - bool addTableBorders; - FittingModes fittingMode; - bool fitToOnePage; - unsigned int horizFitting; - unsigned int vertFitting; - bool chainedFittings; + KGVSimplePrintingSettings(); + ~KGVSimplePrintingSettings(); + + static KGVSimplePrintingSettings load(); + void save(); + + KgvPageLayout pageLayout; + KgvUnit::Unit unit; + QFont pageTitleFont; + bool addPageNumbers; + bool addDateAndTime; + bool addTableBorders; + FittingModes fittingMode; + bool fitToOnePage; + unsigned int horizFitting; + unsigned int vertFitting; + bool chainedFittings; }; } diff --git a/src/part/simpleprintingsettings.cpp b/src/part/simpleprintingsettings.cpp --- a/src/part/simpleprintingsettings.cpp +++ b/src/part/simpleprintingsettings.cpp @@ -30,8 +30,8 @@ // #include // #include -#include #include +#include // #include // #include // #include @@ -51,91 +51,88 @@ namespace KGraphViewer { - KGVSimplePrintingSettings::KGVSimplePrintingSettings() { - pageLayout = KgvPageLayout::standardLayout(); - addPageNumbers = true; - addDateAndTime = true; - addTableBorders = false; - pageTitleFont = qApp->font(); - pageTitleFont.setPointSizeF( (double)QFontInfo(pageTitleFont).pointSize()*1.5 ); - pageTitleFont.setBold(true); - fittingMode = FitToOnePage; - fitToOnePage = true; - horizFitting = 0; - vertFitting = 0; - chainedFittings = true; + pageLayout = KgvPageLayout::standardLayout(); + addPageNumbers = true; + addDateAndTime = true; + addTableBorders = false; + pageTitleFont = qApp->font(); + pageTitleFont.setPointSizeF((double)QFontInfo(pageTitleFont).pointSize() * 1.5); + pageTitleFont.setBold(true); + fittingMode = FitToOnePage; + fitToOnePage = true; + horizFitting = 0; + vertFitting = 0; + chainedFittings = true; } KGVSimplePrintingSettings::~KGVSimplePrintingSettings() { } KGVSimplePrintingSettings KGVSimplePrintingSettings::load() { - KGVSimplePrintingSettings settings; //this will set defaults - - KConfigGroup simplegroup(KSharedConfig::openConfig(), "Simple Printing"); - -// if (simplegroup.hasKey("pageTitleFont")) -// settings.pageTitleFont = simplegroup.readFontEntry("pageTitleFont"); -//! @todo system default? - if (simplegroup.hasKey("pageFormat")) - settings.pageLayout.format = KgvPageFormat::formatFromString( - simplegroup.readEntry("pageFormat" ) ); - if (simplegroup.readEntry("pageOrientation", "portrait").toLower()=="landscape") - settings.pageLayout.orientation = PG_LANDSCAPE; - else - settings.pageLayout.orientation = PG_PORTRAIT; - if (simplegroup.hasKey("pageWidth")) - settings.pageLayout.ptWidth = simplegroup.readEntry("pageWidth",0.0); - if (simplegroup.hasKey("pageHeight")) - settings.pageLayout.ptHeight = simplegroup.readEntry("pageHeight",0.0); - if (simplegroup.hasKey("pageLeftMargin")) - settings.pageLayout.ptLeft = simplegroup.readEntry("pageLeftMargin",0.0); - if (simplegroup.hasKey("pageRightMargin")) - settings.pageLayout.ptRight = simplegroup.readEntry("pageRightMargin",0.0); - if (simplegroup.hasKey("pageTopMargin")) - settings.pageLayout.ptTop = simplegroup.readEntry("pageTopMargin",0.0); - if (simplegroup.hasKey("pageBottomMargin")) - settings.pageLayout.ptBottom = simplegroup.readEntry("pageBottomMargin", 0.0); - settings.addPageNumbers = simplegroup.readEntry("addPageNumbersToPage", true); - settings.addDateAndTime = simplegroup.readEntry("addDateAndTimePage", true); - settings.addTableBorders = simplegroup.readEntry("addTableBorders", false); - if (simplegroup.hasKey("fittingMode") && simplegroup.readEntry("fittingMode",0) <= FitToSeveralPages) - settings.fittingMode = FittingModes(simplegroup.readEntry("fittingMode",0)); -// std::cerr << "fittingMode after loading: " << settings.fittingMode << std::endl; - settings.fitToOnePage = settings.fittingMode==FitToOnePage?true:false; - if (simplegroup.hasKey("horizFitting")) - settings.horizFitting = simplegroup.readEntry("horizFitting",0); - if (simplegroup.hasKey("vertFitting")) - settings.vertFitting = simplegroup.readEntry("vertFitting",0); - settings.chainedFittings = simplegroup.readEntry("chainedFittings", true); - return settings; + KGVSimplePrintingSettings settings; // this will set defaults + + KConfigGroup simplegroup(KSharedConfig::openConfig(), "Simple Printing"); + + // if (simplegroup.hasKey("pageTitleFont")) + // settings.pageTitleFont = simplegroup.readFontEntry("pageTitleFont"); + //! @todo system default? + if (simplegroup.hasKey("pageFormat")) + settings.pageLayout.format = KgvPageFormat::formatFromString(simplegroup.readEntry("pageFormat")); + if (simplegroup.readEntry("pageOrientation", "portrait").toLower() == "landscape") + settings.pageLayout.orientation = PG_LANDSCAPE; + else + settings.pageLayout.orientation = PG_PORTRAIT; + if (simplegroup.hasKey("pageWidth")) + settings.pageLayout.ptWidth = simplegroup.readEntry("pageWidth", 0.0); + if (simplegroup.hasKey("pageHeight")) + settings.pageLayout.ptHeight = simplegroup.readEntry("pageHeight", 0.0); + if (simplegroup.hasKey("pageLeftMargin")) + settings.pageLayout.ptLeft = simplegroup.readEntry("pageLeftMargin", 0.0); + if (simplegroup.hasKey("pageRightMargin")) + settings.pageLayout.ptRight = simplegroup.readEntry("pageRightMargin", 0.0); + if (simplegroup.hasKey("pageTopMargin")) + settings.pageLayout.ptTop = simplegroup.readEntry("pageTopMargin", 0.0); + if (simplegroup.hasKey("pageBottomMargin")) + settings.pageLayout.ptBottom = simplegroup.readEntry("pageBottomMargin", 0.0); + settings.addPageNumbers = simplegroup.readEntry("addPageNumbersToPage", true); + settings.addDateAndTime = simplegroup.readEntry("addDateAndTimePage", true); + settings.addTableBorders = simplegroup.readEntry("addTableBorders", false); + if (simplegroup.hasKey("fittingMode") && simplegroup.readEntry("fittingMode", 0) <= FitToSeveralPages) + settings.fittingMode = FittingModes(simplegroup.readEntry("fittingMode", 0)); + // std::cerr << "fittingMode after loading: " << settings.fittingMode << std::endl; + settings.fitToOnePage = settings.fittingMode == FitToOnePage ? true : false; + if (simplegroup.hasKey("horizFitting")) + settings.horizFitting = simplegroup.readEntry("horizFitting", 0); + if (simplegroup.hasKey("vertFitting")) + settings.vertFitting = simplegroup.readEntry("vertFitting", 0); + settings.chainedFittings = simplegroup.readEntry("chainedFittings", true); + return settings; } void KGVSimplePrintingSettings::save() { - KConfigGroup simplegroup(KSharedConfig::openConfig(), "Simple Printing"); - - simplegroup.writeEntry( "pageTitleFont", pageTitleFont ); - simplegroup.writeEntry( "pageFormat", KgvPageFormat::formatString( pageLayout.format ) ); - simplegroup.writeEntry("pageOrientation", - pageLayout.orientation == PG_PORTRAIT ? "portrait" : "landscape"); - simplegroup.writeEntry("pageWidth", pageLayout.ptWidth); - simplegroup.writeEntry("pageHeight", pageLayout.ptHeight); - simplegroup.writeEntry("pageLeftMargin", pageLayout.ptLeft); - simplegroup.writeEntry("pageRightMargin", pageLayout.ptRight); - simplegroup.writeEntry("pageTopMargin", pageLayout.ptTop); - simplegroup.writeEntry("pageBottomMargin", pageLayout.ptBottom); - simplegroup.writeEntry("addPageNumbersToPage", addPageNumbers); - simplegroup.writeEntry("addDateAndTimePage", addDateAndTime); - simplegroup.writeEntry("addTableBorders", addTableBorders); - simplegroup.writeEntry("fittingMode", (int)fittingMode); - simplegroup.writeEntry("horizFitting", horizFitting); - simplegroup.writeEntry("vertFitting", vertFitting); - simplegroup.writeEntry("chainedFittings", chainedFittings); + KConfigGroup simplegroup(KSharedConfig::openConfig(), "Simple Printing"); + + simplegroup.writeEntry("pageTitleFont", pageTitleFont); + simplegroup.writeEntry("pageFormat", KgvPageFormat::formatString(pageLayout.format)); + simplegroup.writeEntry("pageOrientation", pageLayout.orientation == PG_PORTRAIT ? "portrait" : "landscape"); + simplegroup.writeEntry("pageWidth", pageLayout.ptWidth); + simplegroup.writeEntry("pageHeight", pageLayout.ptHeight); + simplegroup.writeEntry("pageLeftMargin", pageLayout.ptLeft); + simplegroup.writeEntry("pageRightMargin", pageLayout.ptRight); + simplegroup.writeEntry("pageTopMargin", pageLayout.ptTop); + simplegroup.writeEntry("pageBottomMargin", pageLayout.ptBottom); + simplegroup.writeEntry("addPageNumbersToPage", addPageNumbers); + simplegroup.writeEntry("addDateAndTimePage", addDateAndTime); + simplegroup.writeEntry("addTableBorders", addTableBorders); + simplegroup.writeEntry("fittingMode", (int)fittingMode); + simplegroup.writeEntry("horizFitting", horizFitting); + simplegroup.writeEntry("vertFitting", vertFitting); + simplegroup.writeEntry("chainedFittings", chainedFittings); } } diff --git a/src/part/simpleprintpreviewwindow.h b/src/part/simpleprintpreviewwindow.h --- a/src/part/simpleprintpreviewwindow.h +++ b/src/part/simpleprintpreviewwindow.h @@ -29,74 +29,78 @@ #define KGVSIMPLEPRINTPREVIEWWINDOW_H #include -//Added by qt3to4: +// Added by qt3to4: +#include #include -#include #include -#include +#include class QLabel; class QScrollArea; namespace KGraphViewer { - class KGVSimplePrintPreviewScrollView; class KGVSimplePrintPreviewView; class KGVSimplePrintingSettings; class KGVSimplePrintingEngine; //! @short A window for displaying print preview for simple printing. class KGVSimplePrintPreviewWindow : public QWidget { - Q_OBJECT - - public: - KGVSimplePrintPreviewWindow(KGVSimplePrintingEngine &engine, - const QString& previewName, QWidget *parent); - ~KGVSimplePrintPreviewWindow(); - - int currentPage() const { return m_pageNumber; } - - KGVSimplePrintingSettings* settings() const { return m_settings; } - - public Q_SLOTS: - void updatePagesCount(); -// void setPagesCount(int pagesCount); - void goToPage(int pageNumber); + Q_OBJECT + +public: + KGVSimplePrintPreviewWindow(KGVSimplePrintingEngine &engine, const QString &previewName, QWidget *parent); + ~KGVSimplePrintPreviewWindow(); + + int currentPage() const + { + return m_pageNumber; + } + + KGVSimplePrintingSettings *settings() const + { + return m_settings; + } + +public Q_SLOTS: + void updatePagesCount(); + // void setPagesCount(int pagesCount); + void goToPage(int pageNumber); void setFullWidth(); void slotRedraw(); - Q_SIGNALS: - void printRequested(); - void pageSetupRequested(); - - protected Q_SLOTS: - void slotPageSetup(); - void slotPrintClicked(); - void slotZoomInClicked(); - void slotZoomOutClicked(); - void slotFirstClicked(); - void slotPreviousClicked(); - void slotNextClicked(); - void slotLastClicked(); - void initLater(); - - protected: - bool event(QEvent* e) override; - - KGVSimplePrintingEngine &m_engine; - KGVSimplePrintingSettings* m_settings; - KToolBar *m_toolbar, *m_navToolbar; - int m_pageNumber;//, m_pagesCount; - int m_idFirst, m_idLast, m_idPrevious, m_idNext; - QLabel* m_pageNumberLabel; -// QScrollArea* m_scrollView; - KGVSimplePrintPreviewScrollView *m_scrollView; - KGVSimplePrintPreviewView *m_view; +Q_SIGNALS: + void printRequested(); + void pageSetupRequested(); + +protected Q_SLOTS: + void slotPageSetup(); + void slotPrintClicked(); + void slotZoomInClicked(); + void slotZoomOutClicked(); + void slotFirstClicked(); + void slotPreviousClicked(); + void slotNextClicked(); + void slotLastClicked(); + void initLater(); + +protected: + bool event(QEvent *e) override; + + KGVSimplePrintingEngine &m_engine; + KGVSimplePrintingSettings *m_settings; + KToolBar *m_toolbar, *m_navToolbar; + int m_pageNumber; //, m_pagesCount; + int m_idFirst, m_idLast, m_idPrevious, m_idNext; + QLabel *m_pageNumberLabel; + // QScrollArea* m_scrollView; + KGVSimplePrintPreviewScrollView *m_scrollView; + KGVSimplePrintPreviewView *m_view; KActionCollection m_actions; - friend class KGVSimplePrintPreviewView; + friend class KGVSimplePrintPreviewView; }; } diff --git a/src/part/simpleprintpreviewwindow.cpp b/src/part/simpleprintpreviewwindow.cpp --- a/src/part/simpleprintpreviewwindow.cpp +++ b/src/part/simpleprintpreviewwindow.cpp @@ -26,291 +26,270 @@ */ #include "simpleprintpreviewwindow.h" -#include "simpleprintpreviewwindow_p.h" -#include "simpleprintingengine.h" #include "kgraphviewerlib_debug.h" +#include "simpleprintingengine.h" +#include "simpleprintpreviewwindow_p.h" // #include +#include #include #include -#include -//Added by qt3to4: -#include -#include +// Added by qt3to4: +#include #include +#include +#include #include -#include +#include +#include +#include #include -#include #include -#include #include -#include -#include -#include +#include #include +#include #include #include namespace KGraphViewer { - - -KGVSimplePrintPreviewWindow::KGVSimplePrintPreviewWindow( - KGVSimplePrintingEngine &engine, const QString& previewName, - QWidget *parent) - : QWidget(parent) - , m_engine(engine) - , m_settings(m_engine.settings()) - , m_pageNumber(-1), - m_actions(this) +KGVSimplePrintPreviewWindow::KGVSimplePrintPreviewWindow(KGVSimplePrintingEngine &engine, const QString &previewName, QWidget *parent) + : QWidget(parent) + , m_engine(engine) + , m_settings(m_engine.settings()) + , m_pageNumber(-1) + , m_actions(this) { - setObjectName("KGVSimplePrintPreviewWindow"); -// m_pagesCount = INT_MAX; - - setWindowTitle(i18n("%1 - Print Preview - %2",previewName,QString(""))); - setWindowIcon(QIcon::fromTheme(QLatin1String("document-print-preview"))); - QVBoxLayout *lyr = new QVBoxLayout(); - - m_toolbar = new KToolBar(this); - m_toolbar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - lyr->addWidget(m_toolbar); - - QAction* printAction = KStandardAction::print(this, SLOT(slotPrintClicked()), - &m_actions); - m_toolbar->addAction((QAction*)printAction); -/// @todo handle the accelerator -// static_cast(m_toolbar->getWidget(id))->setAccel(Qt::CTRL|Qt::Key_P); -/// @todo add the separator -// m_toolbar->addSeparator(); - - QAction *pageSetupAction = new QAction(i18n("&Page setup"), this); -// &m_actions, "file_page_setup"); - connect(pageSetupAction, &QAction::triggered, - this, &KGVSimplePrintPreviewWindow::slotPageSetup); - m_toolbar->addAction((QAction*)pageSetupAction); - -// id = m_toolbar->insertWidget(-1, 0, new KPushButton(i18n("Page Set&up..."), m_toolbar)); -/// @todo handle the accelerator -// m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotPageSetup())); -/// @todo add the separator -// m_toolbar->addSeparator(); - - -#ifndef KGV_NO_UNFINISHED + setObjectName("KGVSimplePrintPreviewWindow"); + // m_pagesCount = INT_MAX; + + setWindowTitle(i18n("%1 - Print Preview - %2", previewName, QString(""))); + setWindowIcon(QIcon::fromTheme(QLatin1String("document-print-preview"))); + QVBoxLayout *lyr = new QVBoxLayout(); + + m_toolbar = new KToolBar(this); + m_toolbar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + lyr->addWidget(m_toolbar); + + QAction *printAction = KStandardAction::print(this, SLOT(slotPrintClicked()), &m_actions); + m_toolbar->addAction((QAction *)printAction); + /// @todo handle the accelerator + // static_cast(m_toolbar->getWidget(id))->setAccel(Qt::CTRL|Qt::Key_P); + /// @todo add the separator + // m_toolbar->addSeparator(); + + QAction *pageSetupAction = new QAction(i18n("&Page setup"), this); + // &m_actions, "file_page_setup"); + connect(pageSetupAction, &QAction::triggered, this, &KGVSimplePrintPreviewWindow::slotPageSetup); + m_toolbar->addAction((QAction *)pageSetupAction); + + // id = m_toolbar->insertWidget(-1, 0, new KPushButton(i18n("Page Set&up..."), m_toolbar)); + /// @todo handle the accelerator + // m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotPageSetup())); + /// @todo add the separator + // m_toolbar->addSeparator(); + +#ifndef KGV_NO_UNFINISHED //! @todo unfinished /* id = m_toolbar->insertWidget( -1, 0, new KPushButton(BarIconSet("viewmag+"), i18n("Zoom In"), m_toolbar)); - m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotZoomInClicked())); - m_toolbar->addSeparator(); + m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotZoomInClicked())); + m_toolbar->addSeparator(); - id = m_toolbar->insertWidget( -1, 0, new KPushButton(BarIconSet("viewmag-"), i18n("Zoom Out"), m_toolbar)); - m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotZoomOutClicked())); - m_toolbar->addSeparator();*/ + id = m_toolbar->insertWidget( -1, 0, new KPushButton(BarIconSet("viewmag-"), i18n("Zoom Out"), m_toolbar)); + m_toolbar->addConnection(id, SIGNAL(clicked()), this, SLOT(slotZoomOutClicked())); + m_toolbar->addSeparator();*/ #endif - QAction* closeAction = KStandardAction::close(this, SLOT(close()), - &m_actions); - m_toolbar->addAction((QAction*)closeAction); - - m_scrollView = new KGVSimplePrintPreviewScrollView(this); - m_scrollView->setUpdatesEnabled(true); - m_view = (KGVSimplePrintPreviewView*)m_scrollView->widget(); - m_scrollView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - lyr->addWidget(m_scrollView); - - m_navToolbar = new KToolBar(this); - m_navToolbar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - lyr->addWidget(m_navToolbar); - - QAction* firstPageAction = KStandardAction::firstPage(this, SLOT(slotFirstClicked()), - &m_actions); - m_navToolbar->addAction((QAction*)firstPageAction); - m_navToolbar->addSeparator(); - - QAction *previousAction = new QAction(i18n("Previous Page"),this); -// &m_actions, "prevpage"); - connect(previousAction, &QAction::triggered, - this, &KGVSimplePrintPreviewWindow::slotPreviousClicked); - m_navToolbar->addAction((QAction*)previousAction); - m_navToolbar->addSeparator(); - - - m_pageNumberLabel = new QLabel(m_navToolbar); - m_navToolbar->addWidget( m_pageNumberLabel); - m_navToolbar->addSeparator(); - - QAction *nextAction = new QAction(i18n("Next Page"), this);//&m_actions, "nextpage"); - connect(nextAction, &QAction::triggered, - this, &KGVSimplePrintPreviewWindow::slotNextClicked); - m_navToolbar->addAction((QAction*)nextAction); - m_navToolbar->addSeparator(); - - QAction* lastPageAction = KStandardAction::lastPage(this, SLOT(slotLastClicked()),this); -// &m_actions); - m_navToolbar->addAction((QAction*)lastPageAction); - m_navToolbar->addSeparator(); - - resize(width(), qApp->desktop()->height()*4/5); - - this->setLayout(lyr); -//! @todo progress bar... - - QTimer::singleShot(50, this, SLOT(initLater())); + QAction *closeAction = KStandardAction::close(this, SLOT(close()), &m_actions); + m_toolbar->addAction((QAction *)closeAction); + + m_scrollView = new KGVSimplePrintPreviewScrollView(this); + m_scrollView->setUpdatesEnabled(true); + m_view = (KGVSimplePrintPreviewView *)m_scrollView->widget(); + m_scrollView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + lyr->addWidget(m_scrollView); + + m_navToolbar = new KToolBar(this); + m_navToolbar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + lyr->addWidget(m_navToolbar); + + QAction *firstPageAction = KStandardAction::firstPage(this, SLOT(slotFirstClicked()), &m_actions); + m_navToolbar->addAction((QAction *)firstPageAction); + m_navToolbar->addSeparator(); + + QAction *previousAction = new QAction(i18n("Previous Page"), this); + // &m_actions, "prevpage"); + connect(previousAction, &QAction::triggered, this, &KGVSimplePrintPreviewWindow::slotPreviousClicked); + m_navToolbar->addAction((QAction *)previousAction); + m_navToolbar->addSeparator(); + + m_pageNumberLabel = new QLabel(m_navToolbar); + m_navToolbar->addWidget(m_pageNumberLabel); + m_navToolbar->addSeparator(); + + QAction *nextAction = new QAction(i18n("Next Page"), this); //&m_actions, "nextpage"); + connect(nextAction, &QAction::triggered, this, &KGVSimplePrintPreviewWindow::slotNextClicked); + m_navToolbar->addAction((QAction *)nextAction); + m_navToolbar->addSeparator(); + + QAction *lastPageAction = KStandardAction::lastPage(this, SLOT(slotLastClicked()), this); + // &m_actions); + m_navToolbar->addAction((QAction *)lastPageAction); + m_navToolbar->addSeparator(); + + resize(width(), qApp->desktop()->height() * 4 / 5); + + this->setLayout(lyr); + //! @todo progress bar... + + QTimer::singleShot(50, this, SLOT(initLater())); } void KGVSimplePrintPreviewWindow::initLater() { - qCDebug(KGRAPHVIEWERLIB_LOG) ; - setFullWidth(); - updatePagesCount(); - goToPage(0); + qCDebug(KGRAPHVIEWERLIB_LOG); + setFullWidth(); + updatePagesCount(); + goToPage(0); } KGVSimplePrintPreviewWindow::~KGVSimplePrintPreviewWindow() { } void KGVSimplePrintPreviewWindow::slotPrintClicked() { - hide(); - emit printRequested(); - show(); - raise(); + hide(); + emit printRequested(); + show(); + raise(); } void KGVSimplePrintPreviewWindow::slotPageSetup() { - lower(); - emit pageSetupRequested(); + lower(); + emit pageSetupRequested(); } void KGVSimplePrintPreviewWindow::slotZoomInClicked() { - //! @todo + //! @todo } void KGVSimplePrintPreviewWindow::slotZoomOutClicked() { - //! @todo + //! @todo } void KGVSimplePrintPreviewWindow::slotFirstClicked() { - goToPage(0); + goToPage(0); } void KGVSimplePrintPreviewWindow::slotPreviousClicked() { - goToPage(m_pageNumber-1); + goToPage(m_pageNumber - 1); } void KGVSimplePrintPreviewWindow::slotNextClicked() { - goToPage(m_pageNumber+1); + goToPage(m_pageNumber + 1); } void KGVSimplePrintPreviewWindow::slotLastClicked() { - goToPage(m_engine.pagesCount()-1); + goToPage(m_engine.pagesCount() - 1); } void KGVSimplePrintPreviewWindow::slotRedraw() { - - m_engine.clear(); - setFullWidth(); - updatePagesCount(); - m_pageNumber = 0; - m_view->repaint(); //this will automatically paint a new page - -// m_navToolbar->setItemEnabled(m_idNext, m_pageNumber < ((int)m_engine.pagesCount()-1)); -// m_navToolbar->setItemEnabled(m_idLast, m_pageNumber < ((int)m_engine.pagesCount()-1)); -// m_navToolbar->setItemEnabled(m_idPrevious, m_pageNumber > 0); -// m_navToolbar->setItemEnabled(m_idFirst, m_pageNumber > 0); - m_pageNumberLabel->setText( - i18nc("Page (number) of (total)", "Page %1 of %2", m_pageNumber+1, m_engine.pagesCount())); + m_engine.clear(); + setFullWidth(); + updatePagesCount(); + m_pageNumber = 0; + m_view->repaint(); // this will automatically paint a new page + + // m_navToolbar->setItemEnabled(m_idNext, m_pageNumber < ((int)m_engine.pagesCount()-1)); + // m_navToolbar->setItemEnabled(m_idLast, m_pageNumber < ((int)m_engine.pagesCount()-1)); + // m_navToolbar->setItemEnabled(m_idPrevious, m_pageNumber > 0); + // m_navToolbar->setItemEnabled(m_idFirst, m_pageNumber > 0); + m_pageNumberLabel->setText(i18nc("Page (number) of (total)", "Page %1 of %2", m_pageNumber + 1, m_engine.pagesCount())); } void KGVSimplePrintPreviewWindow::goToPage(int pageNumber) { - qCDebug(KGRAPHVIEWERLIB_LOG) << pageNumber; - if (pageNumber==m_pageNumber || pageNumber < 0 || pageNumber > ((int)m_engine.pagesCount()-1)) - return; - m_pageNumber = pageNumber; - - m_view->repaint(); //this will automatically paint a new page -// if (m_engine.eof()) -// m_pagesCount = pageNumber+1; - -// m_navToolbar->setItemEnabled(m_idNext, pageNumber < ((int)m_engine.pagesCount()-1)); -// m_navToolbar->setItemEnabled(m_idLast, pageNumber < ((int)m_engine.pagesCount()-1)); -// m_navToolbar->setItemEnabled(m_idPrevious, pageNumber > 0); -// m_navToolbar->setItemEnabled(m_idFirst, pageNumber > 0); - m_pageNumberLabel->setText( - i18nc("Page (number) of (total)", "Page %1 of %2", - m_pageNumber+1, - m_engine.pagesCount())); + qCDebug(KGRAPHVIEWERLIB_LOG) << pageNumber; + if (pageNumber == m_pageNumber || pageNumber < 0 || pageNumber > ((int)m_engine.pagesCount() - 1)) + return; + m_pageNumber = pageNumber; + + m_view->repaint(); // this will automatically paint a new page + // if (m_engine.eof()) + // m_pagesCount = pageNumber+1; + + // m_navToolbar->setItemEnabled(m_idNext, pageNumber < ((int)m_engine.pagesCount()-1)); + // m_navToolbar->setItemEnabled(m_idLast, pageNumber < ((int)m_engine.pagesCount()-1)); + // m_navToolbar->setItemEnabled(m_idPrevious, pageNumber > 0); + // m_navToolbar->setItemEnabled(m_idFirst, pageNumber > 0); + m_pageNumberLabel->setText(i18nc("Page (number) of (total)", "Page %1 of %2", m_pageNumber + 1, m_engine.pagesCount())); } void KGVSimplePrintPreviewWindow::setFullWidth() { - m_scrollView->setFullWidth(); + m_scrollView->setFullWidth(); } void KGVSimplePrintPreviewWindow::updatePagesCount() { - QPainter p(this); -// QPainter p(m_view); -// p.begin(this); - m_engine.calculatePagesCount(p); -// p.end(); + QPainter p(this); + // QPainter p(m_view); + // p.begin(this); + m_engine.calculatePagesCount(p); + // p.end(); } -bool KGVSimplePrintPreviewWindow::event( QEvent * e ) +bool KGVSimplePrintPreviewWindow::event(QEvent *e) { - QEvent::Type t = e->type(); - if (t==QEvent::KeyPress) - { - QKeyEvent *ke = static_cast(e); - const int k = ke->key(); - bool ok = true; - if (k==Qt::Key_Equal || k==Qt::Key_Plus) + QEvent::Type t = e->type(); + if (t == QEvent::KeyPress) { + QKeyEvent *ke = static_cast(e); + const int k = ke->key(); + bool ok = true; + if (k == Qt::Key_Equal || k == Qt::Key_Plus) slotZoomInClicked(); - else if (k==Qt::Key_Minus) + else if (k == Qt::Key_Minus) slotZoomOutClicked(); - else if (k==Qt::Key_Home) + else if (k == Qt::Key_Home) slotFirstClicked(); - else if (k==Qt::Key_End) + else if (k == Qt::Key_End) slotLastClicked(); - else + else ok = false; - if (ok) - { - ke->accept(); - return true; - } - } - else if (t==QEvent::ShortcutOverride) - { - QKeyEvent *ke = static_cast(e); - const int k = ke->key(); - bool ok = true; - if (k==Qt::Key_PageUp) + if (ok) { + ke->accept(); + return true; + } + } else if (t == QEvent::ShortcutOverride) { + QKeyEvent *ke = static_cast(e); + const int k = ke->key(); + bool ok = true; + if (k == Qt::Key_PageUp) slotPreviousClicked(); - else if (k==Qt::Key_PageDown) + else if (k == Qt::Key_PageDown) slotNextClicked(); - else + else ok = false; - if (ok) { + if (ok) { ke->accept(); return true; + } } - } - return QWidget::event(e); + return QWidget::event(e); } } diff --git a/src/part/simpleprintpreviewwindow_p.h b/src/part/simpleprintpreviewwindow_p.h --- a/src/part/simpleprintpreviewwindow_p.h +++ b/src/part/simpleprintpreviewwindow_p.h @@ -29,43 +29,43 @@ #define KGVSIMPLEPRINTPREVIEWWINDOW_P_H #include "simpleprintpreviewwindow.h" -//Added by qt3to4: +// Added by qt3to4: #include #include #include namespace KGraphViewer { - class KGVSimplePrintPreviewView : public QWidget { - Q_OBJECT - public: - explicit KGVSimplePrintPreviewView(KGVSimplePrintPreviewWindow *window); + Q_OBJECT +public: + explicit KGVSimplePrintPreviewView(KGVSimplePrintPreviewWindow *window); + + void paintEvent(QPaintEvent *pe) override; - void paintEvent(QPaintEvent* pe) override; - protected: - KGVSimplePrintPreviewWindow *m_window; +protected: + KGVSimplePrintPreviewWindow *m_window; }; class KGVSimplePrintPreviewScrollView : public QScrollArea { - Q_OBJECT + Q_OBJECT + +public: + explicit KGVSimplePrintPreviewScrollView(KGVSimplePrintPreviewWindow *window); - public: - explicit KGVSimplePrintPreviewScrollView(KGVSimplePrintPreviewWindow *window); + KGVSimplePrintPreviewView *m_view; - KGVSimplePrintPreviewView *m_view; +public Q_SLOTS: + void setFullWidth(); + // void setContentsPos(int x, int y); - public Q_SLOTS: - void setFullWidth(); -// void setContentsPos(int x, int y); +protected: + void paintEvent(QPaintEvent *pe) override; - protected: - void paintEvent(QPaintEvent* pe) override; - -// virtual void resizeEvent( QResizeEvent *re ); - KGVSimplePrintPreviewWindow *m_window; + // virtual void resizeEvent( QResizeEvent *re ); + KGVSimplePrintPreviewWindow *m_window; }; } diff --git a/src/part/simpleprintpreviewwindow_p.cpp b/src/part/simpleprintpreviewwindow_p.cpp --- a/src/part/simpleprintpreviewwindow_p.cpp +++ b/src/part/simpleprintpreviewwindow_p.cpp @@ -26,76 +26,74 @@ */ #include "simpleprintpreviewwindow_p.h" +#include "kgraphviewerlib_debug.h" #include "simpleprintingengine.h" #include "simpleprintingsettings.h" -#include "kgraphviewerlib_debug.h" +#include #include +#include #include #include -#include #include -#include namespace KGraphViewer { - -KGVSimplePrintPreviewView::KGVSimplePrintPreviewView( - KGVSimplePrintPreviewWindow *window) - : QWidget(), - m_window(window) +KGVSimplePrintPreviewView::KGVSimplePrintPreviewView(KGVSimplePrintPreviewWindow *window) + : QWidget() + , m_window(window) { - qCDebug(KGRAPHVIEWERLIB_LOG) << "KGVSimplePrintPreviewView"; -/* resize(300,400); - resizeContents(200, 400);*/ -//setAttribute(Qt::WA_PaintOutsidePaintEvent,true); + qCDebug(KGRAPHVIEWERLIB_LOG) << "KGVSimplePrintPreviewView"; + /* resize(300,400); + resizeContents(200, 400);*/ + // setAttribute(Qt::WA_PaintOutsidePaintEvent,true); } -void KGVSimplePrintPreviewView::paintEvent( QPaintEvent *pe ) +void KGVSimplePrintPreviewView::paintEvent(QPaintEvent *pe) { - qCDebug(KGRAPHVIEWERLIB_LOG) << pe; - Q_UNUSED(pe); - - QPainter p(this); -// QPainter p(m_window); - // p.begin(&pm); -// p.initFrom(this); -//! @todo only for screen! - qCDebug(KGRAPHVIEWERLIB_LOG) << "filling rect"; - p.fillRect(QRect(QPoint(0,0),m_window->size()), QBrush(Qt::white));//pe->rect(), QBrush(white)); - if (m_window->currentPage()>=0) - { - qCDebug(KGRAPHVIEWERLIB_LOG) << "painting page"; - m_window->m_engine.paintPage(m_window->currentPage(), p); - } -// emit m_window->paintingPageRequested(m_window->currentPage(), p); - p.end(); + qCDebug(KGRAPHVIEWERLIB_LOG) << pe; + Q_UNUSED(pe); + + QPainter p(this); + // QPainter p(m_window); + // p.begin(&pm); + // p.initFrom(this); + //! @todo only for screen! + qCDebug(KGRAPHVIEWERLIB_LOG) << "filling rect"; + p.fillRect(QRect(QPoint(0, 0), m_window->size()), QBrush(Qt::white)); // pe->rect(), QBrush(white)); + if (m_window->currentPage() >= 0) { + qCDebug(KGRAPHVIEWERLIB_LOG) << "painting page"; + m_window->m_engine.paintPage(m_window->currentPage(), p); + } + // emit m_window->paintingPageRequested(m_window->currentPage(), p); + p.end(); } // TODO: redo usages instead with QStyle::PM_Layout{Top,Left,Right,Bottom}Margin #define KGVSimplePrintPreviewScrollView_MARGIN QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing) -KGVSimplePrintPreviewScrollView::KGVSimplePrintPreviewScrollView( - KGVSimplePrintPreviewWindow *window) : QScrollArea(window), m_window(window) +KGVSimplePrintPreviewScrollView::KGVSimplePrintPreviewScrollView(KGVSimplePrintPreviewWindow *window) + : QScrollArea(window) + , m_window(window) { -// this->settings = settings; - m_view = new KGVSimplePrintPreviewView(m_window); - -/* int widthMM = KgvPageFormat::width( - settings.pageLayout.format, settings.pageLayout.orientation); - int heightMM = KgvPageFormat::height( - settings.pageLayout.format, settings.pageLayout.orientation); -// int constantHeight = 400; -// m_view->resize(constantHeight * widthMM / heightMM, constantHeight ); //keep aspect -*/ - setWidget(m_view); + // this->settings = settings; + m_view = new KGVSimplePrintPreviewView(m_window); + + /* int widthMM = KgvPageFormat::width( + settings.pageLayout.format, settings.pageLayout.orientation); + int heightMM = KgvPageFormat::height( + settings.pageLayout.format, settings.pageLayout.orientation); + // int constantHeight = 400; + // m_view->resize(constantHeight * widthMM / heightMM, constantHeight ); //keep aspect + */ + setWidget(m_view); } -void KGVSimplePrintPreviewScrollView::paintEvent( QPaintEvent *pe ) +void KGVSimplePrintPreviewScrollView::paintEvent(QPaintEvent *pe) { - qCDebug(KGRAPHVIEWERLIB_LOG) << widget(); - QScrollArea::paintEvent(pe); - ((KGVSimplePrintPreviewView*)widget())->paintEvent(pe); + qCDebug(KGRAPHVIEWERLIB_LOG) << widget(); + QScrollArea::paintEvent(pe); + ((KGVSimplePrintPreviewView *)widget())->paintEvent(pe); } // void KGVSimplePrintPreviewScrollView::resizeEvent( QResizeEvent *re ) @@ -106,41 +104,38 @@ // // qCDebug(KGRAPHVIEWERLIB_LOG) << m_view->width() << " " << m_view->height(); // setUpdatesEnabled(false); // if (re->size().width() > (m_view->width()+2*KGVSimplePrintPreviewScrollView_MARGIN) -// || re->size().height() > (m_view->height()+2*KGVSimplePrintPreviewScrollView_MARGIN)) +// || re->size().height() > (m_view->height()+2*KGVSimplePrintPreviewScrollView_MARGIN)) // { // resizeContents( // qMax(re->size().width(), m_view->width()+2*KGVSimplePrintPreviewScrollView_MARGIN), // qMax(re->size().height(), m_view->height()+2*KGVSimplePrintPreviewScrollView_MARGIN)); -// +// // int vscrbarWidth = verticalScrollBar()->isVisible() ? verticalScrollBar()->width() : 0; -// moveChild(m_view, (contentsWidth() - vscrbarWidth - m_view->width())/2, +// moveChild(m_view, (contentsWidth() - vscrbarWidth - m_view->width())/2, // (contentsHeight() - m_view->height())/2); // } // setUpdatesEnabled(true); // } void KGVSimplePrintPreviewScrollView::setFullWidth() { - viewport()->setUpdatesEnabled(false); - double widthMM = KgvPageFormat::width( - m_window->settings()->pageLayout.format, - m_window->settings()->pageLayout.orientation); - double heightMM = KgvPageFormat::height( - m_window->settings()->pageLayout.format, m_window->settings()->pageLayout.orientation); -// int constantWidth = m_window->width()- KGVSimplePrintPreviewScrollView_MARGIN*6; - double constantWidth = width() - KGVSimplePrintPreviewScrollView_MARGIN*6; - double heightForWidth = constantWidth * heightMM / widthMM; -// heightForWidth = qMin(kapp->desktop()->height()*4/5, heightForWidth); - constantWidth = heightForWidth * widthMM / heightMM; - m_view->resize((int)constantWidth, (int)heightForWidth); //keep aspect -/* resizeContents(int(m_view->width() + 2*KGVSimplePrintPreviewScrollView_MARGIN), - int(m_view->height() + 2*KGVSimplePrintPreviewScrollView_MARGIN));*/ -/* moveChild(m_view, (contentsWidth()-m_view->width())/2, - (contentsHeight()-m_view->height())/2);*/ - viewport()->setUpdatesEnabled(true); - resize(size()+QSize(1,1)); //to update pos. -// m_view->enablePainting = true; - m_view->repaint(); + viewport()->setUpdatesEnabled(false); + double widthMM = KgvPageFormat::width(m_window->settings()->pageLayout.format, m_window->settings()->pageLayout.orientation); + double heightMM = KgvPageFormat::height(m_window->settings()->pageLayout.format, m_window->settings()->pageLayout.orientation); + // int constantWidth = m_window->width()- KGVSimplePrintPreviewScrollView_MARGIN*6; + double constantWidth = width() - KGVSimplePrintPreviewScrollView_MARGIN * 6; + double heightForWidth = constantWidth * heightMM / widthMM; + // heightForWidth = qMin(kapp->desktop()->height()*4/5, heightForWidth); + constantWidth = heightForWidth * widthMM / heightMM; + m_view->resize((int)constantWidth, (int)heightForWidth); // keep aspect + /* resizeContents(int(m_view->width() + 2*KGVSimplePrintPreviewScrollView_MARGIN), + int(m_view->height() + 2*KGVSimplePrintPreviewScrollView_MARGIN));*/ + /* moveChild(m_view, (contentsWidth()-m_view->width())/2, + (contentsHeight()-m_view->height())/2);*/ + viewport()->setUpdatesEnabled(true); + resize(size() + QSize(1, 1)); // to update pos. + // m_view->enablePainting = true; + m_view->repaint(); } // void KGVSimplePrintPreviewScrollView::setContentsPos(int x, int y)