<commit_before>/***************************************************************************
 *   Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMenu>
# include <QMouseEvent>
# include <Inventor/nodes/SoCamera.h>
#endif
#include <Inventor/SbVec2s.h>
#include "View3DInventorViewer.h"

#include "Flag.h"

using namespace Gui;

/* TRANSLATOR Gui::Flag */

// TODO: Rename to Annotation
//       Support transparency
//       Embed complete widgets

Flag::Flag(QWidget* parent)
  : QtGLWidget(parent), coord(0.0f, 0.0f, 0.0f)
{
    this->setFixedHeight(20);
#if defined(HAVE_QT5_OPENGL)
    setAutoFillBackground(true);
#endif
}

Flag::~Flag()
{
}

void Flag::initializeGL()
{
    const QPalette& p = this->palette();
#if !defined(HAVE_QT5_OPENGL)
    qglClearColor(p.color(QPalette::Window));
#else
    QColor c(p.color(QPalette::Window));
    glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
#endif
}

void Flag::paintGL()
{
#if !defined(HAVE_QT5_OPENGL)
    const QPalette& p = this->palette();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    qglColor(p.color(QPalette::Text));
    renderText(10,15,this->text);
#else
    QOpenGLWidget::paintGL();
#endif
}

void Flag::paintEvent(QPaintEvent* e)
{
#if !defined(HAVE_QT5_OPENGL)
    QtGLWidget::paintEvent(e);
#else
    const QPalette& p = this->palette();
    QColor c(p.color(QPalette::Text));

    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(e->rect(), p.color(QPalette::Window));
    painter.setPen(c);
    painter.drawText(10, 15, this->text);
    painter.end();
#endif
}

void Flag::resizeGL(int width, int height)
{
    Q_UNUSED(width);
    Q_UNUSED(height);
}

void Flag::setOrigin(const SbVec3f& v)
{
    this->coord = v;
}

const SbVec3f& Flag::getOrigin() const
{
    return this->coord;
}

void Flag::drawLine (View3DInventorViewer* v, int tox, int toy)
{
    if (!isVisible())
        return;

    // Get position of line
    QSize s = parentWidget()->size();
    SbVec2s view(s.width(), s.height());
    int fromx = pos().x();
    int fromy = pos().y() + height()/2;
    if (false) fromx += width();

    GLPainter p;
    p.begin(v->getGLWidget());
#if !defined(HAVE_QT5_OPENGL)
    p.setDrawBuffer(GL_BACK);
#endif

    // the line
    p.setLineWidth(1.0f);
    p.drawLine(fromx, fromy, tox, toy);
    // the point
    p.setPointSize(3.0f);
    p.drawPoint(tox, toy);
    p.end();
}

void Flag::setText(const QString& t)
{
    this->text = t;
}

void Flag::resizeEvent(QResizeEvent* e)
{
    QtGLWidget::resizeEvent(e);
}

void Flag::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
        move(e->globalPos() - dragPosition);
        e->accept();
    }
}

void Flag::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
        dragPosition = e->globalPos() - frameGeometry().topLeft();
        e->accept();
    }
}

void Flag::contextMenuEvent(QContextMenuEvent * e)
{
    QMenu menu(this);

    QAction* topleft = menu.addAction(tr("Top left"));
    topleft->setCheckable(true);
    QAction* botleft = menu.addAction(tr("Bottom left"));
    botleft->setCheckable(true);
    QAction* topright = menu.addAction(tr("Top right"));
    topright->setCheckable(true);
    QAction* botright = menu.addAction(tr("Bottom right"));
    botright->setCheckable(true);
    menu.addSeparator();
    QAction* remove = menu.addAction(tr("Remove"));
    QAction* select = menu.exec(e->globalPos());
    if (remove == select)
        this->deleteLater();
}

QSize Flag::sizeHint() const
{
    int w = 100;
    int h = 20;
    QFontMetrics metric(this->font());
    QRect r = metric.boundingRect(text);
    w = std::max<int>(w, r.width()+20);
    h = std::max<int>(h, r.height());
    return QSize(w, h);
}

// ------------------------------------------------------------------------

FlagLayout::FlagLayout(QWidget *parent, int margin, int spacing)
    : QLayout(parent)
{
    setMargin(margin);
    setSpacing(spacing);
}

FlagLayout::FlagLayout(int spacing)
{
    setSpacing(spacing);
}

FlagLayout::~FlagLayout()
{
    QLayoutItem *l;
    while ((l = takeAt(0)))
        delete l;
}

void FlagLayout::addItem(QLayoutItem *item)
{
    add(item, TopLeft);
}

void FlagLayout::addWidget(QWidget *widget, Position position)
{
    add(new QWidgetItem(widget), position);
}

Qt::Orientations FlagLayout::expandingDirections() const
{
    return Qt::Horizontal | Qt::Vertical;
}

bool FlagLayout::hasHeightForWidth() const
{
    return false;
}

int FlagLayout::count() const
{
    return list.size();
}

QLayoutItem *FlagLayout::itemAt(int index) const
{
    ItemWrapper *wrapper = list.value(index);
    if (wrapper)
        return wrapper->item;
    else
        return 0;
}

QSize FlagLayout::minimumSize() const
{
    return calculateSize(MinimumSize);
}

void FlagLayout::setGeometry(const QRect &rect)
{
    int topHeight = 0;
    int bottomHeight = 0;

    QLayout::setGeometry(rect);

    // left side
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        if (position == TopLeft) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + spacing(), topHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomLeft) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + spacing(), rect.height() - bottomHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }

    // right side
    topHeight = 0;
    bottomHeight = 0;
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        int rightpos = item->sizeHint().width() + spacing();
        if (position == TopRight) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, topHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomRight) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, rect.height() - bottomHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }
}

QSize FlagLayout::sizeHint() const
{
    return calculateSize(SizeHint);
}

QLayoutItem *FlagLayout::takeAt(int index)
{
    if (index >= 0 && index < list.size()) {
        ItemWrapper *layoutStruct = list.takeAt(index);
        return layoutStruct->item;
    }
    return 0;
}

void FlagLayout::add(QLayoutItem *item, Position position)
{
    list.append(new ItemWrapper(item, position));
}

QSize FlagLayout::calculateSize(SizeType sizeType) const
{
    QSize totalSize;

    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QSize itemSize;

        if (sizeType == MinimumSize)
            itemSize = wrapper->item->minimumSize();
        else // (sizeType == SizeHint)
            itemSize = wrapper->item->sizeHint();

        totalSize.rheight() += itemSize.height();
        totalSize.rwidth() = qMax<int>(totalSize.width(),itemSize.width());
    }
    return totalSize;
}

TYPESYSTEM_SOURCE_ABSTRACT(Gui::GLFlagWindow, Gui::GLGraphicsItem);

GLFlagWindow::GLFlagWindow(View3DInventorViewer* view) : _viewer(view), _flagLayout(0)
{
}

GLFlagWindow::~GLFlagWindow()
{
    deleteFlags();
    if (_flagLayout)
        _flagLayout->deleteLater();
}

void GLFlagWindow::deleteFlags()
{
    if (_flagLayout) {
        int ct = _flagLayout->count();
        for (int i=0; i<ct;i++) {
            QWidget* flag = _flagLayout->itemAt(0)->widget();
            if (flag) {
                _flagLayout->removeWidget(flag);
                flag->deleteLater();
            }
        }
    }
}

void GLFlagWindow::addFlag(Flag* item, FlagLayout::Position pos)
{
    if (!_flagLayout) {
        _flagLayout = new FlagLayout(3);
        _viewer->setLayout(_flagLayout);
    }

    item->setParent(_viewer);
    _flagLayout->addWidget(item, pos);
    item->show();
    _viewer->getSoRenderManager()->scheduleRedraw();
}

void GLFlagWindow::removeFlag(Flag* item)
{
    if (_flagLayout) {
        _flagLayout->removeWidget(item);
    }
}

Flag* GLFlagWindow::getFlag(int index) const
{
    if (_flagLayout) {
        QWidget* flag = _flagLayout->itemAt(index)->widget();
        return qobject_cast<Flag*>(flag);
    }
    return 0;
}

int GLFlagWindow::countFlags() const
{
    if (_flagLayout) {
        return _flagLayout->count();
    }

    return 0;
}

void GLFlagWindow::paintGL()
{
    // draw lines for the flags
    if (_flagLayout) {
        // it can happen that the GL widget gets replaced internally (SoQt only, not with quarter) which
        // causes to destroy the FlagLayout instance
        int ct = _flagLayout->count();
        const SbViewportRegion vp = _viewer->getSoRenderManager()->getViewportRegion();
        SbVec2s size = vp.getViewportSizePixels();
        float aspectratio = float(size[0])/float(size[1]);
        SbViewVolume vv = _viewer->getSoRenderManager()->getCamera()->getViewVolume(aspectratio);
        for (int i=0; i<ct;i++) {
            Flag* flag = qobject_cast<Flag*>(_flagLayout->itemAt(i)->widget());
            if (flag) {
                SbVec3f pt = flag->getOrigin();
                vv.projectToScreen(pt, pt);
                int tox = (int)(pt[0] * size[0]);
                int toy = (int)((1.0f-pt[1]) * size[1]);
                flag->drawLine(_viewer, tox, toy);
            }
        }
    }
}

#include "moc_Flag.cpp"
<commit_msg>Qt5OpenGL: update flags when dragging or removing<commit_after>/***************************************************************************
 *   Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMenu>
# include <QMouseEvent>
# include <Inventor/nodes/SoCamera.h>
#endif
#include <Inventor/SbVec2s.h>
#include "View3DInventorViewer.h"

#include "Flag.h"

using namespace Gui;

/* TRANSLATOR Gui::Flag */

// TODO: Rename to Annotation
//       Support transparency
//       Embed complete widgets

Flag::Flag(QWidget* parent)
  : QtGLWidget(parent), coord(0.0f, 0.0f, 0.0f)
{
    this->setFixedHeight(20);
#if defined(HAVE_QT5_OPENGL)
    setAutoFillBackground(true);
#endif
}

Flag::~Flag()
{
}

void Flag::initializeGL()
{
    const QPalette& p = this->palette();
#if !defined(HAVE_QT5_OPENGL)
    qglClearColor(p.color(QPalette::Window));
#else
    QColor c(p.color(QPalette::Window));
    glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF());
#endif
}

void Flag::paintGL()
{
#if !defined(HAVE_QT5_OPENGL)
    const QPalette& p = this->palette();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    qglColor(p.color(QPalette::Text));
    renderText(10,15,this->text);
#else
    QOpenGLWidget::paintGL();
#endif
}

void Flag::paintEvent(QPaintEvent* e)
{
#if !defined(HAVE_QT5_OPENGL)
    QtGLWidget::paintEvent(e);
#else
    const QPalette& p = this->palette();
    QColor c(p.color(QPalette::Text));

    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(e->rect(), p.color(QPalette::Window));
    painter.setPen(c);
    painter.drawText(10, 15, this->text);
    painter.end();
#endif
}

void Flag::resizeGL(int width, int height)
{
    Q_UNUSED(width);
    Q_UNUSED(height);
}

void Flag::setOrigin(const SbVec3f& v)
{
    this->coord = v;
}

const SbVec3f& Flag::getOrigin() const
{
    return this->coord;
}

void Flag::drawLine (View3DInventorViewer* v, int tox, int toy)
{
    if (!isVisible())
        return;

    // Get position of line
    QSize s = parentWidget()->size();
    SbVec2s view(s.width(), s.height());
    int fromx = pos().x();
    int fromy = pos().y() + height()/2;
    if (false) fromx += width();

    GLPainter p;
    p.begin(v->getGLWidget());
#if !defined(HAVE_QT5_OPENGL)
    p.setDrawBuffer(GL_BACK);
#endif

    // the line
    p.setLineWidth(1.0f);
    p.drawLine(fromx, fromy, tox, toy);
    // the point
    p.setPointSize(3.0f);
    p.drawPoint(tox, toy);
    p.end();
}

void Flag::setText(const QString& t)
{
    this->text = t;
}

void Flag::resizeEvent(QResizeEvent* e)
{
    QtGLWidget::resizeEvent(e);
}

void Flag::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
        move(e->globalPos() - dragPosition);
        e->accept();
#if defined(HAVE_QT5_OPENGL)
        View3DInventorViewer* viewer = dynamic_cast<View3DInventorViewer*>(parentWidget());
        if (viewer)
            viewer->getSoRenderManager()->scheduleRedraw();
#endif
    }
}

void Flag::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
        dragPosition = e->globalPos() - frameGeometry().topLeft();
        e->accept();
    }
}

void Flag::contextMenuEvent(QContextMenuEvent * e)
{
    QMenu menu(this);

    QAction* topleft = menu.addAction(tr("Top left"));
    topleft->setCheckable(true);
    QAction* botleft = menu.addAction(tr("Bottom left"));
    botleft->setCheckable(true);
    QAction* topright = menu.addAction(tr("Top right"));
    topright->setCheckable(true);
    QAction* botright = menu.addAction(tr("Bottom right"));
    botright->setCheckable(true);
    menu.addSeparator();
    QAction* remove = menu.addAction(tr("Remove"));
    QAction* select = menu.exec(e->globalPos());
    if (remove == select)
        this->deleteLater();
}

QSize Flag::sizeHint() const
{
    int w = 100;
    int h = 20;
    QFontMetrics metric(this->font());
    QRect r = metric.boundingRect(text);
    w = std::max<int>(w, r.width()+20);
    h = std::max<int>(h, r.height());
    return QSize(w, h);
}

// ------------------------------------------------------------------------

FlagLayout::FlagLayout(QWidget *parent, int margin, int spacing)
    : QLayout(parent)
{
    setMargin(margin);
    setSpacing(spacing);
}

FlagLayout::FlagLayout(int spacing)
{
    setSpacing(spacing);
}

FlagLayout::~FlagLayout()
{
    QLayoutItem *l;
    while ((l = takeAt(0)))
        delete l;
}

void FlagLayout::addItem(QLayoutItem *item)
{
    add(item, TopLeft);
}

void FlagLayout::addWidget(QWidget *widget, Position position)
{
    add(new QWidgetItem(widget), position);
}

Qt::Orientations FlagLayout::expandingDirections() const
{
    return Qt::Horizontal | Qt::Vertical;
}

bool FlagLayout::hasHeightForWidth() const
{
    return false;
}

int FlagLayout::count() const
{
    return list.size();
}

QLayoutItem *FlagLayout::itemAt(int index) const
{
    ItemWrapper *wrapper = list.value(index);
    if (wrapper)
        return wrapper->item;
    else
        return 0;
}

QSize FlagLayout::minimumSize() const
{
    return calculateSize(MinimumSize);
}

void FlagLayout::setGeometry(const QRect &rect)
{
    int topHeight = 0;
    int bottomHeight = 0;

    QLayout::setGeometry(rect);

    // left side
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        if (position == TopLeft) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + spacing(), topHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomLeft) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + spacing(), rect.height() - bottomHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }

    // right side
    topHeight = 0;
    bottomHeight = 0;
    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QLayoutItem *item = wrapper->item;
        Position position = wrapper->position;

        int rightpos = item->sizeHint().width() + spacing();
        if (position == TopRight) {
            topHeight += spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, topHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));

            topHeight += item->geometry().height();
        } else if (position == BottomRight) {
            bottomHeight += item->geometry().height() + spacing();
            item->setGeometry(QRect(rect.x() + rect.width() - rightpos, rect.height() - bottomHeight,
                                    item->sizeHint().width(), item->sizeHint().height()));
        }
    }
}

QSize FlagLayout::sizeHint() const
{
    return calculateSize(SizeHint);
}

QLayoutItem *FlagLayout::takeAt(int index)
{
    if (index >= 0 && index < list.size()) {
        ItemWrapper *layoutStruct = list.takeAt(index);
        return layoutStruct->item;
    }
    return 0;
}

void FlagLayout::add(QLayoutItem *item, Position position)
{
    list.append(new ItemWrapper(item, position));
}

QSize FlagLayout::calculateSize(SizeType sizeType) const
{
    QSize totalSize;

    for (int i = 0; i < list.size(); ++i) {
        ItemWrapper *wrapper = list.at(i);
        QSize itemSize;

        if (sizeType == MinimumSize)
            itemSize = wrapper->item->minimumSize();
        else // (sizeType == SizeHint)
            itemSize = wrapper->item->sizeHint();

        totalSize.rheight() += itemSize.height();
        totalSize.rwidth() = qMax<int>(totalSize.width(),itemSize.width());
    }
    return totalSize;
}

TYPESYSTEM_SOURCE_ABSTRACT(Gui::GLFlagWindow, Gui::GLGraphicsItem);

GLFlagWindow::GLFlagWindow(View3DInventorViewer* view) : _viewer(view), _flagLayout(0)
{
}

GLFlagWindow::~GLFlagWindow()
{
    deleteFlags();
    if (_flagLayout)
        _flagLayout->deleteLater();
}

void GLFlagWindow::deleteFlags()
{
    if (_flagLayout) {
        int ct = _flagLayout->count();
        for (int i=0; i<ct;i++) {
            QWidget* flag = _flagLayout->itemAt(0)->widget();
            if (flag) {
                _flagLayout->removeWidget(flag);
                flag->deleteLater();
            }
        }
#if defined(HAVE_QT5_OPENGL)
        if (ct > 0)
            _viewer->getSoRenderManager()->scheduleRedraw();
#endif
    }
}

void GLFlagWindow::addFlag(Flag* item, FlagLayout::Position pos)
{
    if (!_flagLayout) {
        _flagLayout = new FlagLayout(3);
        _viewer->setLayout(_flagLayout);
    }

    item->setParent(_viewer);
    _flagLayout->addWidget(item, pos);
    item->show();
    _viewer->getSoRenderManager()->scheduleRedraw();
}

void GLFlagWindow::removeFlag(Flag* item)
{
    if (_flagLayout) {
        _flagLayout->removeWidget(item);
#if defined(HAVE_QT5_OPENGL)
        _viewer->getSoRenderManager()->scheduleRedraw();
#endif
    }
}

Flag* GLFlagWindow::getFlag(int index) const
{
    if (_flagLayout) {
        QWidget* flag = _flagLayout->itemAt(index)->widget();
        return qobject_cast<Flag*>(flag);
    }
    return 0;
}

int GLFlagWindow::countFlags() const
{
    if (_flagLayout) {
        return _flagLayout->count();
    }

    return 0;
}

void GLFlagWindow::paintGL()
{
    // draw lines for the flags
    if (_flagLayout) {
        // it can happen that the GL widget gets replaced internally (SoQt only, not with quarter) which
        // causes to destroy the FlagLayout instance
        int ct = _flagLayout->count();
        const SbViewportRegion vp = _viewer->getSoRenderManager()->getViewportRegion();
        SbVec2s size = vp.getViewportSizePixels();
        float aspectratio = float(size[0])/float(size[1]);
        SbViewVolume vv = _viewer->getSoRenderManager()->getCamera()->getViewVolume(aspectratio);
        for (int i=0; i<ct;i++) {
            Flag* flag = qobject_cast<Flag*>(_flagLayout->itemAt(i)->widget());
            if (flag) {
                SbVec3f pt = flag->getOrigin();
                vv.projectToScreen(pt, pt);
                int tox = (int)(pt[0] * size[0]);
                int toy = (int)((1.0f-pt[1]) * size[1]);
                flag->drawLine(_viewer, tox, toy);
            }
        }
    }
}

#include "moc_Flag.cpp"
<|endoftext|>


<commit_before>//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"

namespace clang {
namespace tidy {
namespace darwin {

class DarwinModule : public ClangTidyModule {
public:
  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
    CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
        "darwin-dispatch-once-nonstatic");
  }
};

} // namespace darwin

// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
    X("misc-module", "Adds miscellaneous lint checks.");

// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;

} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Fix module registry name and description for Darwin clang-tidy module.<commit_after>//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"

namespace clang {
namespace tidy {
namespace darwin {

class DarwinModule : public ClangTidyModule {
public:
  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
    CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
        "darwin-dispatch-once-nonstatic");
  }
};

} // namespace darwin

// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
    X("darwin-module", "Adds Darwin-specific lint checks.");

// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;

} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ka $ $Date: 2001-10-22 13:36:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
    SfxInPlaceClient(pSdViewShell, pWindow),
    pViewShell(pSdViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdClient::~SdClient()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
    Window* pWin = pViewShell->GetWindow();
    Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
                        pWin->PixelToLogic( rRect.GetSize() ) );

    SdView* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );

    if (!aWorkArea.IsInside(aObjRect))
    {
        // Position korrigieren
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);

        SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
                                              LogicToPixel(aObjRect) );
    }
    else
    {
        SfxInPlaceClient::RequestObjAreaPixel(rRect);
    }

    const SdrMarkList& rMarkList = pView->GetMarkList();

    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        Rectangle aOldRect( pObj->GetLogicRect() );

        if ( aObjRect != aOldRect )
        {
            // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
            // (getrennt fuer Position und Groesse)
            Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
            Size aLogicSize = aObjRect.GetSize();
            Rectangle aNewRect = aOldRect;
            Size aNewSize = aNewRect.GetSize();

            if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
                aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
            if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
                aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );

            if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
                aNewSize.Width() = aLogicSize.Width();
            if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
                aNewSize.Height() = aLogicSize.Height();

            aNewRect.SetSize( aNewSize );

            if ( aNewRect != aOldRect )     // veraendert nur, wenn mindestens 1 Pixel
                pObj->SetLogicRect( aNewRect );
        }
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void SdClient::ViewChanged(USHORT nAspect)
{
    // Eventuell neues MetaFile holen
    SfxInPlaceClient::ViewChanged(nAspect);

    if (pViewShell->GetActiveWindow())
    {
        SdView* pView = pViewShell->GetView();

        if (pView)
        {
            // Der sichtbare Ausschnitt hat sich eventuell geaendert
            SvEmbeddedObject*   pObj = GetEmbedObj();
            const MapMode       aMap100( MAP_100TH_MM );
            Rectangle           aObjVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(),
                                                                         pObj->GetMapUnit(),
                                                                         aMap100 ) );
            Size                aVisSize( aObjVisArea.GetSize() );
            SvClientData*       pClientData = GetEnv();

            if( pClientData )
            {
                Fraction aFractX( pClientData->GetScaleWidth() );
                Fraction aFractY( pClientData->GetScaleHeight() );

                aVisSize = Size( (long) ( aFractX *= aVisSize.Width() ), (long) ( aFractY *= aVisSize.Height() ) );

                Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() );
                Rectangle aObjArea( aLogicRect );

                aObjArea.SetSize( aObjVisArea.GetSize() );
                pClientData->SetObjArea( aObjArea );

                const Size aVisSizePix( Application::GetDefaultDevice()->LogicToPixel( aVisSize, aMap100 ) );
                const Size aObjSizePix( Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) );

                if( aVisSizePix != aObjSizePix )
                {
                    aLogicRect.SetSize(aVisSize);
                    pSdrOle2Obj->SetLogicRect(aLogicRect);
                    pSdrOle2Obj->SendRepaintBroadcast();
                }
            }
        }
    }
}

/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/

void SdClient::UIActivate(BOOL bActivate)
{
    SfxInPlaceClient::UIActivate(bActivate);

    if (!bActivate)
    {
#ifdef STARIMAGE_AVAILABLE
        if (pSdrGrafObj && pViewShell->GetActiveWindow())
        {
            // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
            pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
            SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
            pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
            SdView* pView = pViewShell->GetView();
            SdrPageView* pPV = pView->GetPageViewPvNum(0);
            SdrPage* pPg = pPV->GetPage();
            delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
            pSdrGrafObj = NULL;
        }
#endif
    }
}

/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/

void SdClient::MakeViewData()
{
    SfxInPlaceClient::MakeViewData();

    SvClientData* pCD = GetClientData();

    if (pCD)
    {
        SvEmbeddedObject* pObj = GetEmbedObj();
        Rectangle aObjVisArea = OutputDevice::LogicToLogic(
                                    pObj->GetVisArea(), pObj->GetMapUnit(),
                                    MAP_100TH_MM );
        Size aVisSize = aObjVisArea.GetSize();
        Fraction aFractX = pCD->GetScaleWidth();
        Fraction aFractY = pCD->GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        pCD->SetSizeScale(aFractX, aFractY);

        Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
        pCD->SetObjArea(aObjArea);
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void SdClient::MakeVisible()
{
    SfxInPlaceClient::MakeVisible();

    if (pViewShell->ISA(SdDrawViewShell))
    {
        ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
                                                     *pViewShell->GetActiveWindow());
    }
}

<commit_msg>#94774#: optimized OLE change handling<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdclient.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ka $ $Date: 2001-12-05 15:24:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif

#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#pragma hdrstop

#include "misc.hxx"

#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif

#include "strings.hrc"

#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
    SfxInPlaceClient(pSdViewShell, pWindow),
    pViewShell(pSdViewShell),
    pSdrOle2Obj(pObj),
    pSdrGrafObj(NULL),
    pOutlinerParaObj (NULL)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdClient::~SdClient()
{
}

/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/

void SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
    Window* pWin = pViewShell->GetWindow();
    Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
                        pWin->PixelToLogic( rRect.GetSize() ) );

    SdView* pView = pViewShell->GetView();
    Rectangle aWorkArea( pView->GetWorkArea() );

    if (!aWorkArea.IsInside(aObjRect))
    {
        // Position korrigieren
        Point aPos = aObjRect.TopLeft();
        Size  aSize = aObjRect.GetSize();
        Point aWorkAreaTL = aWorkArea.TopLeft();
        Point aWorkAreaBR = aWorkArea.BottomRight();

        aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
        aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
        aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
        aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());

        aObjRect.SetPos(aPos);

        SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
                                              LogicToPixel(aObjRect) );
    }
    else
    {
        SfxInPlaceClient::RequestObjAreaPixel(rRect);
    }

    const SdrMarkList& rMarkList = pView->GetMarkList();

    if (rMarkList.GetMarkCount() == 1)
    {
        SdrMark* pMark = rMarkList.GetMark(0);
        SdrObject* pObj = pMark->GetObj();

        Rectangle aOldRect( pObj->GetLogicRect() );

        if ( aObjRect != aOldRect )
        {
            // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
            // (getrennt fuer Position und Groesse)
            Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
            Size aLogicSize = aObjRect.GetSize();
            Rectangle aNewRect = aOldRect;
            Size aNewSize = aNewRect.GetSize();

            if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
                aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
            if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
                aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );

            if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
                aNewSize.Width() = aLogicSize.Width();
            if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
                aNewSize.Height() = aLogicSize.Height();

            aNewRect.SetSize( aNewSize );

            if ( aNewRect != aOldRect )     // veraendert nur, wenn mindestens 1 Pixel
                pObj->SetLogicRect( aNewRect );
        }
    }
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void SdClient::ViewChanged(USHORT nAspect)
{
    // Eventuell neues MetaFile holen
    SfxInPlaceClient::ViewChanged(nAspect);

    if (pViewShell->GetActiveWindow())
    {
        SdView* pView = pViewShell->GetView();

        if (pView)
        {
            SvClientData* pData = GetEnv();

            if( pData )
            {
                SvEmbeddedObject*   pObj = GetEmbedObj();
                MapMode             aMap100( MAP_100TH_MM );
                Rectangle           aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) );
                Rectangle           aLogicRect( pSdrOle2Obj->GetLogicRect() );
                Size                aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ),
                                                 static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) );

                if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) !=
                    Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) )
                {
                    const sal_Bool bOldLock = pView->GetModel()->isLocked();

                    pView->GetModel()->setLock( sal_True );
                    pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) );
                    pView->GetModel()->setLock( bOldLock );
                    pSdrOle2Obj->SendRepaintBroadcast();
                }
            }
        }
    }
}

/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/

void SdClient::UIActivate(BOOL bActivate)
{
    SfxInPlaceClient::UIActivate(bActivate);

    if (!bActivate)
    {
#ifdef STARIMAGE_AVAILABLE
        if (pSdrGrafObj && pViewShell->GetActiveWindow())
        {
            // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
            pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
            SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
            pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
            SdView* pView = pViewShell->GetView();
            SdrPageView* pPV = pView->GetPageViewPvNum(0);
            SdrPage* pPg = pPV->GetPage();
            delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
            pSdrGrafObj = NULL;
        }
#endif
    }
}

/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/

void SdClient::MakeViewData()
{
    SfxInPlaceClient::MakeViewData();

    SvClientData* pCD = GetClientData();

    if (pCD)
    {
        SvEmbeddedObject* pObj = GetEmbedObj();
        Rectangle aObjVisArea = OutputDevice::LogicToLogic(
                                    pObj->GetVisArea(), pObj->GetMapUnit(),
                                    MAP_100TH_MM );
        Size aVisSize = aObjVisArea.GetSize();
        Fraction aFractX = pCD->GetScaleWidth();
        Fraction aFractY = pCD->GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        pCD->SetSizeScale(aFractX, aFractY);

        Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
        pCD->SetObjArea(aObjArea);
    }
}

/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/

void SdClient::MakeVisible()
{
    SfxInPlaceClient::MakeVisible();

    if (pViewShell->ISA(SdDrawViewShell))
    {
        ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
                                                     *pViewShell->GetActiveWindow());
    }
}

<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexForth.cxx
 ** Lexer for FORTH
 **/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsAWordChar(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
		ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
		ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
		ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
		ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
		ch == ')' );
}

static inline bool IsAWordStart(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}

static inline bool IsANumChar(int ch) {
	return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}

static inline bool IsASpaceChar(int ch) {
	return (ch < 0x80) && isspace(ch);
}

static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
                            Accessor &styler) {

    WordList &control = *keywordLists[0];
    WordList &keyword = *keywordLists[1];
    WordList &defword = *keywordLists[2];
    WordList &preword1 = *keywordLists[3];
    WordList &preword2 = *keywordLists[4];
    WordList &strings = *keywordLists[5];

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward())
	{
		// Determine if the current state should terminate.
		if (sc.state == SCE_FORTH_COMMENT) {
			if (sc.atLineEnd) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_COMMENT_ML) {
			if (sc.ch == ')') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
			// handle numbers here too, because what we thought was a number might
			// turn out to be a keyword e.g. 2DUP
			if (IsASpaceChar(sc.ch) ) {
				char s[100];
				sc.GetCurrentLowered(s, sizeof(s));
				int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
				if (control.InList(s)) {
					sc.ChangeState(SCE_FORTH_CONTROL);
				} else if (keyword.InList(s)) {
					sc.ChangeState(SCE_FORTH_KEYWORD);
				} else if (defword.InList(s)) {
					sc.ChangeState(SCE_FORTH_DEFWORD);
				}  else if (preword1.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD1);
				} else if (preword2.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD2);
				} else if (strings.InList(s)) {
					sc.ChangeState(SCE_FORTH_STRING);
					newState = SCE_FORTH_STRING;
				}
				sc.SetState(newState);
			}
			if (sc.state == SCE_FORTH_NUMBER) {
				if (IsASpaceChar(sc.ch)) {
					sc.SetState(SCE_FORTH_DEFAULT);
				}
			}
		}else if (sc.state == SCE_FORTH_STRING) {
			if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_LOCALE) {
			if (sc.ch == '}') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_DEFWORD) {
			if (IsASpaceChar(sc.ch)) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_FORTH_DEFAULT) {
			if (sc.ch == '\\'){
				sc.SetState(SCE_FORTH_COMMENT);
			} else if (sc.ch == '(' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))) {
				sc.SetState(SCE_FORTH_COMMENT_ML);
			} else if (	(sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
				// number starting with $ is a hex number
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
					sc.Forward();
			} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
				// number starting with % is binary
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
					sc.Forward();
			} else if (	isascii(sc.ch) &&
						(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
					){
				sc.SetState(SCE_FORTH_NUMBER);
			} else if (IsAWordStart(sc.ch)) {
				sc.SetState(SCE_FORTH_IDENTIFIER);
			} else if (sc.ch == '{') {
				sc.SetState(SCE_FORTH_LOCALE);
			} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
				// highlight word definitions e.g.  : GCD ( n n -- n ) ..... ;
				//                                  ^ ^^^
				sc.SetState(SCE_FORTH_DEFWORD);
				while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
					sc.Forward();
			} else if (sc.ch == ';' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))	) {
				// mark the ';' that ends a word
				sc.SetState(SCE_FORTH_DEFWORD);
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}

	}
	sc.Complete();
}

static void FoldForthDoc(unsigned int, int, int, WordList *[],
						Accessor &) {
}

static const char * const forthWordLists[] = {
			"control keywords",
			"keywords",
			"definition words",
			"prewords with one argument",
			"prewords with two arguments",
			"string definition keywords",
			0,
		};

LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);

<commit_msg>Bug #2806565 FORTH lexer is too keen to mark things as numbers.<commit_after>// Scintilla source code edit control
/** @file LexForth.cxx
 ** Lexer for FORTH
 **/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsAWordChar(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
		ch == '_' || ch == '?' || ch == '"' || ch == '@' ||
		ch == '!' || ch == '[' || ch == ']' || ch == '/' ||
		ch == '+' || ch == '-' || ch == '*' || ch == '<' ||
		ch == '>' || ch == '=' || ch == ';' || ch == '(' ||
		ch == ')' );
}

static inline bool IsAWordStart(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}

static inline bool IsANumChar(int ch) {
	return (ch < 0x80) && (isxdigit(ch) || ch == '.' || ch == 'e' || ch == 'E' );
}

static inline bool IsASpaceChar(int ch) {
	return (ch < 0x80) && isspace(ch);
}

static void ColouriseForthDoc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[],
                            Accessor &styler) {

    WordList &control = *keywordLists[0];
    WordList &keyword = *keywordLists[1];
    WordList &defword = *keywordLists[2];
    WordList &preword1 = *keywordLists[3];
    WordList &preword2 = *keywordLists[4];
    WordList &strings = *keywordLists[5];

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward())
	{
		// Determine if the current state should terminate.
		if (sc.state == SCE_FORTH_COMMENT) {
			if (sc.atLineEnd) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_COMMENT_ML) {
			if (sc.ch == ')') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_IDENTIFIER || sc.state == SCE_FORTH_NUMBER) {
			// handle numbers here too, because what we thought was a number might
			// turn out to be a keyword e.g. 2DUP
			if (IsASpaceChar(sc.ch) ) {
				char s[100];
				sc.GetCurrentLowered(s, sizeof(s));
				int newState = sc.state == SCE_FORTH_NUMBER ? SCE_FORTH_NUMBER : SCE_FORTH_DEFAULT;
				if (control.InList(s)) {
					sc.ChangeState(SCE_FORTH_CONTROL);
				} else if (keyword.InList(s)) {
					sc.ChangeState(SCE_FORTH_KEYWORD);
				} else if (defword.InList(s)) {
					sc.ChangeState(SCE_FORTH_DEFWORD);
				}  else if (preword1.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD1);
				} else if (preword2.InList(s)) {
					sc.ChangeState(SCE_FORTH_PREWORD2);
				} else if (strings.InList(s)) {
					sc.ChangeState(SCE_FORTH_STRING);
					newState = SCE_FORTH_STRING;
				}
				sc.SetState(newState);
			}
			if (sc.state == SCE_FORTH_NUMBER) {
				if (IsASpaceChar(sc.ch)) {
					sc.SetState(SCE_FORTH_DEFAULT);
				} else if (!IsANumChar(sc.ch)) {
					sc.ChangeState(SCE_FORTH_IDENTIFIER);
				}
			}
		}else if (sc.state == SCE_FORTH_STRING) {
			if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_LOCALE) {
			if (sc.ch == '}') {
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}else if (sc.state == SCE_FORTH_DEFWORD) {
			if (IsASpaceChar(sc.ch)) {
				sc.SetState(SCE_FORTH_DEFAULT);
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_FORTH_DEFAULT) {
			if (sc.ch == '\\'){
				sc.SetState(SCE_FORTH_COMMENT);
			} else if (sc.ch == '(' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))) {
				sc.SetState(SCE_FORTH_COMMENT_ML);
			} else if (	(sc.ch == '$' && (isascii(sc.chNext) && isxdigit(sc.chNext))) ) {
				// number starting with $ is a hex number
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && isxdigit(sc.chNext))
					sc.Forward();
			} else if ( (sc.ch == '%' && (isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))) ) {
				// number starting with % is binary
				sc.SetState(SCE_FORTH_NUMBER);
				while(sc.More() && isascii(sc.chNext) && (sc.chNext == '0' || sc.chNext == '1'))
					sc.Forward();
			} else if (	isascii(sc.ch) &&
						(isxdigit(sc.ch) || ((sc.ch == '.' || sc.ch == '-') && isascii(sc.chNext) && isxdigit(sc.chNext)) )
					){
				sc.SetState(SCE_FORTH_NUMBER);
			} else if (IsAWordStart(sc.ch)) {
				sc.SetState(SCE_FORTH_IDENTIFIER);
			} else if (sc.ch == '{') {
				sc.SetState(SCE_FORTH_LOCALE);
			} else if (sc.ch == ':' && isascii(sc.chNext) && isspace(sc.chNext)) {
				// highlight word definitions e.g.  : GCD ( n n -- n ) ..... ;
				//                                  ^ ^^^
				sc.SetState(SCE_FORTH_DEFWORD);
				while(sc.More() && isascii(sc.chNext) && isspace(sc.chNext))
					sc.Forward();
			} else if (sc.ch == ';' &&
					(sc.atLineStart || IsASpaceChar(sc.chPrev)) &&
					(sc.atLineEnd   || IsASpaceChar(sc.chNext))	) {
				// mark the ';' that ends a word
				sc.SetState(SCE_FORTH_DEFWORD);
				sc.ForwardSetState(SCE_FORTH_DEFAULT);
			}
		}

	}
	sc.Complete();
}

static void FoldForthDoc(unsigned int, int, int, WordList *[],
						Accessor &) {
}

static const char * const forthWordLists[] = {
			"control keywords",
			"keywords",
			"definition words",
			"prewords with one argument",
			"prewords with two arguments",
			"string definition keywords",
			0,
		};

LexerModule lmForth(SCLEX_FORTH, ColouriseForthDoc, "forth", FoldForthDoc, forthWordLists);

<|endoftext|>


<commit_before>#include "espresso_core.h"

int main(int argc, char** argv) {

  handle_cmd_args(argc, argv);

  // TODO: open filesystem data for when you need it
  // filepath is argv[FILESYSTEM]

  char storage_file[] = ".data_storage";
  char *file = (char *)malloc(strlen (argv[FILESYSTEM]) +
                              strlen (storage_file) + 1);
  strcpy (file, argv[FILESYSTEM]);
  strcat (file, storage_file);

  printf ("Opening storage file %s\n", file);

  int storage_file_fd;
  if ((storage_file_fd  = open (file, O_RDWR | O_CREAT,
                                S_IRUSR | S_IWUSR)) < 0) {
    perror("Unable to open data storage file.");
    exit (EXIT_FAILURE);
  }

  printf ("storage file open (%d)\n", storage_file_fd);

  espresso_global_data_init (storage_file_fd, NODE_STORAGE_SIZE);

  char* barista_hostname = argv[BARISTA_HOSTNAME];
  int barista_port = atoi(argv[BARISTA_PORT]);
  int node_id = atoi(argv[NODE_ID]);
  EspressoClient espresso(barista_hostname, barista_port, node_id);
  espresso.openConnection();
  espresso.run();

  // the svc_main_loop function lives in network core and
  // calls registered espresso functions as it receives the rpcs
  //svc_main_loop(argc, argv);

  return 0;
}

void handle_cmd_args(int argc, char** argv) {

  if (argc == NUM_EXPECTED_ARGS) {

  }
  else {
     fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
     fprintf(stderr, "\nUsage: %s <node_id> <persistent metadata path> <data path> <barista hostname> <barista port>\n", argv[0]);
     exit(-1);
  }
}
<commit_msg>I think this should make the espresso node work<commit_after>#include "espresso_core.h"

int main(int argc, char** argv) {

  handle_cmd_args(argc, argv);

  // TODO: open filesystem data for when you need it
  // filepath is argv[FILESYSTEM]

  char storage_file[] = ".data_storage";
  char *file = (char *)malloc(strlen (argv[FILESYSTEM]) +
                              strlen (storage_file) + 1);
  strcpy (file, argv[FILESYSTEM]);
  strcat (file, storage_file);

  printf ("Opening storage file %s\n", file);

  int storage_file_fd;
  if ((storage_file_fd  = open (file, O_RDWR | O_CREAT,
                                S_IRUSR | S_IWUSR)) < 0) {
    perror("Unable to open data storage file.");
    exit (EXIT_FAILURE);
  }

  printf ("storage file open (%d)\n", storage_file_fd);

  espresso_global_data_init (argv[FILESYSTEM], NODE_STORAGE_SIZE);

  char* barista_hostname = argv[BARISTA_HOSTNAME];
  int barista_port = atoi(argv[BARISTA_PORT]);
  int node_id = atoi(argv[NODE_ID]);
  EspressoClient espresso(barista_hostname, barista_port, node_id);
  espresso.openConnection();
  espresso.run();

  // the svc_main_loop function lives in network core and
  // calls registered espresso functions as it receives the rpcs
  //svc_main_loop(argc, argv);

  return 0;
}

void handle_cmd_args(int argc, char** argv) {

  if (argc == NUM_EXPECTED_ARGS) {

  }
  else {
     fprintf(stderr, "%s exiting: invalid command line arguments provided", argv[0]);
     fprintf(stderr, "\nUsage: %s <node_id> <persistent metadata path> <data path> <barista hostname> <barista port>\n", argv[0]);
     exit(-1);
  }
}
<|endoftext|>


<commit_before>/*
  For more information, please see: http://software.sci.utah.edu

  The MIT License

  Copyright (c) 2015 Scientific Computing and Imaging Institute,
  University of Utah.

  License for the specific language governing rights and limitations under
  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
*/

#include <es-log/trace-log.h>
#include <QtGui>
#include <functional>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Core/Utils/Legacy/MemoryUtil.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Interface/Application/GuiLogger.h>
#include <Interface/Application/SCIRunMainWindow.h>
#include <Interface/Application/NetworkEditor.h>
#include <Interface/Application/ProvenanceWindow.h>
#include <Interface/Application/DeveloperConsole.h>
#include <Interface/Application/Connection.h>
#include <Interface/Application/PreferencesWindow.h>
#include <Interface/Application/TagManagerWindow.h>
#include <Interface/Application/ShortcutsInterface.h>
#include <Interface/Application/TreeViewCollaborators.h>
#include <Interface/Application/MainWindowCollaborators.h>
#include <Interface/Application/GuiCommands.h>
#include <Interface/Application/NetworkEditorControllerGuiProxy.h>
#include <Interface/Application/NetworkExecutionProgressBar.h>
#include <Interface/Application/DialogErrorControl.h>
#include <Interface/Modules/Base/RemembersFileDialogDirectory.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h> //TODO
#include <Interface/Application/ModuleWizard/ModuleWizard.h>
#include <Dataflow/Network/NetworkFwd.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h> //DOH! see TODO in setController
#include <Dataflow/Engine/Controller/ProvenanceManager.h>
#include <Dataflow/Network/SimpleSourceSink.h>  //TODO: encapsulate!!!
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Core/Application/Application.h>
#include <Core/Application/Preferences/Preferences.h>
#include <Core/Logging/Log.h>
#include <Core/Thread/Parallel.h>
#include <Core/Application/Version.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Core/Utils/CurrentFileName.h>

#ifdef BUILD_WITH_PYTHON
#include <Interface/Application/PythonConsoleWidget.h>
#include <Core/Python/PythonInterpreter.h>
#endif
#include "TriggeredEventsWindow.h"
#include <Dataflow/Serialization/Network/XMLSerializer.h>

using namespace SCIRun;
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Commands;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Algorithms;

void SCIRunMainWindow::initialize()
{
  postConstructionSignalHookup();

  fillModuleSelector();

  executeCommandLineRequests();
}

void SCIRunMainWindow::setController(NetworkEditorControllerHandle controller)
{
  auto controllerProxy(boost::make_shared<NetworkEditorControllerGuiProxy>(controller, networkEditor_));
  networkEditor_->setNetworkEditorController(controllerProxy);
  //TODO: need better way to wire this up
  controller->setSerializationManager(networkEditor_);
}

void SCIRunMainWindow::preexecute()
{
	if (Preferences::Instance().saveBeforeExecute && !Application::Instance().parameters()->isRegressionMode())
	{
		saveNetwork();
	}
}

void SCIRunMainWindow::setupQuitAfterExecute()
{
  connect(networkEditor_->getNetworkEditorController().get(), SIGNAL(executionFinished(int)), this, SLOT(exitApplication(int)));
  quitAfterExecute_ = true;
}

void SCIRunMainWindow::saveNetworkFile(const QString& fileName)
{
  writeSettings();
  NetworkSaveCommand save;
  save.set(Variables::Filename, fileName.toStdString());
  save.execute();
}

bool SCIRunMainWindow::loadNetworkFile(const QString& filename, bool isTemporary)
{
  if (!filename.isEmpty())
  {
    RENDERER_LOG("Opening network file: {}", filename.toStdString());
    FileOpenCommand command;
    command.set(Variables::Filename, filename.toStdString());
    command.set(Name("temporaryFile"), isTemporary);
    if (command.execute())
    {
      networkProgressBar_->updateTotalModules(networkEditor_->numModules());
      if (!isTemporary)
      {
        setCurrentFile(filename);
        statusBar()->showMessage(tr("File loaded: ") + filename, 2000);
        provenanceWindow_->clear();
        provenanceWindow_->showFile(command.file_);
      }
      else
      {
        setCurrentFile("");
        setWindowModified(true);
        showStatusMessage("Toolkit network loaded. ", 2000);
      }
			networkEditor_->viewport()->update();
      return true;
    }
    else
    {
      if (Application::Instance().parameters()->isRegressionMode())
        exit(7);
      //TODO: set error code to non-0 so regression tests fail!
      // probably want to control this with a --regression flag.
    }
  }
  return false;
}

bool SCIRunMainWindow::importLegacyNetworkFile(const QString& filename)
{
	bool success = false;
  if (!filename.isEmpty())
  {
    FileImportCommand command;
    command.set(Variables::Filename, filename.toStdString());
    if (command.execute())
    {
      statusBar()->showMessage(tr("File imported: ") + filename, 2000);
      networkProgressBar_->updateTotalModules(networkEditor_->numModules());
      networkEditor_->viewport()->update();
      success = true;
    }
    else
    {
      statusBar()->showMessage(tr("File import failed: ") + filename, 2000);
    }
		auto log = QString::fromStdString(command.logContents());
    auto isoString = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::universal_time());
    auto logFileName = QString::fromStdString(Core::Logging::LogSettings::Instance().logDirectory().string())
      + "/" + ("importLog_" + strippedName(filename) + "_" + QString::fromStdString(isoString) + ".log");
		QFile logFile(logFileName);
    if (logFile.open(QFile::WriteOnly | QFile::Text))
		{
			QTextStream stream(&logFile);
			stream << log;
			QMessageBox::information(this, "SRN File Import", "SRN File Import log file can be found here: " + logFileName
				+ "\n\nAdditionally, check the log directory for a list of missing modules (look for file missingModules.log)");
    }
		else
		{
			QMessageBox::information(this, "SRN File Import", "Failed to write SRN File Import log file: " + logFileName);
		}
  }
  return success;
}

void SCIRunMainWindow::setCurrentFile(const QString& fileName)
{
  currentFile_ = fileName;
  setCurrentFileName(currentFile_.toStdString());
  setWindowModified(false);
  auto shownName = tr("Untitled");
  if (!currentFile_.isEmpty())
  {
    shownName = strippedName(currentFile_);
    latestNetworkDirectory_ = QFileInfo(currentFile_).dir();
    recentFiles_.removeAll(currentFile_);
    recentFiles_.prepend(currentFile_);
    updateRecentFileActions();
  }
  setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun")));
}

void SCIRunMainWindow::runPythonScript(const QString& scriptFileName)
{
#ifdef BUILD_WITH_PYTHON
  NetworkEditor::InEditingContext iec(networkEditor_);
  GuiLogger::logInfoQ("RUNNING PYTHON SCRIPT: " + scriptFileName);
  PythonInterpreter::Instance().importSCIRunLibrary();
  PythonInterpreter::Instance().run_file(scriptFileName.toStdString());
  statusBar()->showMessage(tr("Script is running."), 2000);
#else
  GuiLogger::logInfo("Python not included in this build, cannot run " + scriptFileName);
#endif
}

bool SCIRunMainWindow::isInFavorites(const QString& module) const
{
	return favoriteModuleNames_.contains(module);
}

void SCIRunMainWindow::setDataDirectory(const QString& dir)
{
  if (!dir.isEmpty())
  {
    prefsWindow_->scirunDataLineEdit_->setText(dir);
    prefsWindow_->scirunDataLineEdit_->setToolTip(dir);

    RemembersFileDialogDirectory::setStartingDir(dir);
    Preferences::Instance().setDataDirectory(dir.toStdString());
    Q_EMIT dataDirectorySet(dir);
  }
}

void SCIRunMainWindow::setDataPath(const QString& dirs)
{
	if (!dirs.isEmpty())
	{
    //prefsWindow_->scirunDataPathTextEdit_->setPlainText(dirs);
    //prefsWindow_->scirunDataPathTextEdit_->setToolTip(dirs);

		Preferences::Instance().setDataPath(dirs.toStdString());
	}
}

void SCIRunMainWindow::addToDataDirectory(const QString& dir)
{
	if (!dir.isEmpty())
	{
    // auto text = prefsWindow_->scirunDataPathTextEdit_->toPlainText();
		// if (!text.isEmpty())
		// 	text += ";\n";
		// text += dir;
    // prefsWindow_->scirunDataPathTextEdit_->setPlainText(text);
    // prefsWindow_->scirunDataPathTextEdit_->setToolTip(prefsWindow_->scirunDataPathTextEdit_->toPlainText());

		RemembersFileDialogDirectory::setStartingDir(dir);
		Preferences::Instance().addToDataPath(dir.toStdString());
	}
}

void SCIRunMainWindow::addToolkit(const QString& filename, const QString& directory, const ToolkitFile& toolkit)
{
  auto menu = menuToolkits_->addMenu(filename);
  auto networks = menu->addMenu("Networks");
  toolkitDirectories_[filename] = directory;
  toolkitNetworks_[filename] = toolkit;
  auto fullpath = directory + QDir::separator() + filename + ".toolkit";
  toolkitMenus_[fullpath] = menu;
  std::map<std::string, std::map<std::string, NetworkFile>> toolkitMenuData;
  for (const auto& toolkitPair : toolkit.networks)
  {
    std::vector<std::string> elements;
    for (const auto& p : boost::filesystem::path(toolkitPair.first))
      elements.emplace_back(p.filename().string());

    if (elements.size() == 2)
    {
      toolkitMenuData[elements[0]][elements[1]] = toolkitPair.second;
    }
    else
    {
      qDebug() << "Cannot handle toolkit folders of depth > 1";
    }
  }

  for (const auto& t1 : toolkitMenuData)
  {
    auto t1menu = networks->addMenu(QString::fromStdString(t1.first));
    for (const auto& t2 : t1.second)
    {
      auto networkAction = t1menu->addAction(QString::fromStdString(t2.first));
      std::ostringstream net;
      XMLSerializer::save_xml(t2.second, net, "networkFile");
      networkAction->setProperty("network", QString::fromStdString(net.str()));
      connect(networkAction, SIGNAL(triggered()), this, SLOT(openToolkitNetwork()));
    }
  }

  auto folder = menu->addAction("Open Toolkit Directory");
  folder->setProperty("path", directory);
  connect(folder, SIGNAL(triggered()), this, SLOT(openToolkitFolder()));

  auto remove = menu->addAction("Remove Toolkit...");
  remove->setProperty("filename", filename);
  remove->setProperty("fullpath", fullpath);
  connect(remove, SIGNAL(triggered()), this, SLOT(removeToolkit()));

  if (!startup_)
  {
    QMessageBox::information(this, "Toolkit loaded", "Toolkit " + filename +
      " successfully imported. A new submenu is available under Toolkits for loading networks.\n\n"
      + "Remember to update your data folder under Preferences->Paths.");
    actionPreferences_->trigger();
  }
}
<commit_msg>Improve import log file name<commit_after>/*
  For more information, please see: http://software.sci.utah.edu

  The MIT License

  Copyright (c) 2015 Scientific Computing and Imaging Institute,
  University of Utah.

  License for the specific language governing rights and limitations under
  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
*/

#include <es-log/trace-log.h>
#include <QtGui>
#include <functional>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Core/Utils/Legacy/MemoryUtil.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Interface/Application/GuiLogger.h>
#include <Interface/Application/SCIRunMainWindow.h>
#include <Interface/Application/NetworkEditor.h>
#include <Interface/Application/ProvenanceWindow.h>
#include <Interface/Application/DeveloperConsole.h>
#include <Interface/Application/Connection.h>
#include <Interface/Application/PreferencesWindow.h>
#include <Interface/Application/TagManagerWindow.h>
#include <Interface/Application/ShortcutsInterface.h>
#include <Interface/Application/TreeViewCollaborators.h>
#include <Interface/Application/MainWindowCollaborators.h>
#include <Interface/Application/GuiCommands.h>
#include <Interface/Application/NetworkEditorControllerGuiProxy.h>
#include <Interface/Application/NetworkExecutionProgressBar.h>
#include <Interface/Application/DialogErrorControl.h>
#include <Interface/Modules/Base/RemembersFileDialogDirectory.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h> //TODO
#include <Interface/Application/ModuleWizard/ModuleWizard.h>
#include <Dataflow/Network/NetworkFwd.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h> //DOH! see TODO in setController
#include <Dataflow/Engine/Controller/ProvenanceManager.h>
#include <Dataflow/Network/SimpleSourceSink.h>  //TODO: encapsulate!!!
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Core/Application/Application.h>
#include <Core/Application/Preferences/Preferences.h>
#include <Core/Logging/Log.h>
#include <Core/Thread/Parallel.h>
#include <Core/Application/Version.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Core/Utils/CurrentFileName.h>

#ifdef BUILD_WITH_PYTHON
#include <Interface/Application/PythonConsoleWidget.h>
#include <Core/Python/PythonInterpreter.h>
#endif
#include "TriggeredEventsWindow.h"
#include <Dataflow/Serialization/Network/XMLSerializer.h>

using namespace SCIRun;
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Commands;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Algorithms;

void SCIRunMainWindow::initialize()
{
  postConstructionSignalHookup();

  fillModuleSelector();

  executeCommandLineRequests();
}

void SCIRunMainWindow::setController(NetworkEditorControllerHandle controller)
{
  auto controllerProxy(boost::make_shared<NetworkEditorControllerGuiProxy>(controller, networkEditor_));
  networkEditor_->setNetworkEditorController(controllerProxy);
  //TODO: need better way to wire this up
  controller->setSerializationManager(networkEditor_);
}

void SCIRunMainWindow::preexecute()
{
	if (Preferences::Instance().saveBeforeExecute && !Application::Instance().parameters()->isRegressionMode())
	{
		saveNetwork();
	}
}

void SCIRunMainWindow::setupQuitAfterExecute()
{
  connect(networkEditor_->getNetworkEditorController().get(), SIGNAL(executionFinished(int)), this, SLOT(exitApplication(int)));
  quitAfterExecute_ = true;
}

void SCIRunMainWindow::saveNetworkFile(const QString& fileName)
{
  writeSettings();
  NetworkSaveCommand save;
  save.set(Variables::Filename, fileName.toStdString());
  save.execute();
}

bool SCIRunMainWindow::loadNetworkFile(const QString& filename, bool isTemporary)
{
  if (!filename.isEmpty())
  {
    RENDERER_LOG("Opening network file: {}", filename.toStdString());
    FileOpenCommand command;
    command.set(Variables::Filename, filename.toStdString());
    command.set(Name("temporaryFile"), isTemporary);
    if (command.execute())
    {
      networkProgressBar_->updateTotalModules(networkEditor_->numModules());
      if (!isTemporary)
      {
        setCurrentFile(filename);
        statusBar()->showMessage(tr("File loaded: ") + filename, 2000);
        provenanceWindow_->clear();
        provenanceWindow_->showFile(command.file_);
      }
      else
      {
        setCurrentFile("");
        setWindowModified(true);
        showStatusMessage("Toolkit network loaded. ", 2000);
      }
			networkEditor_->viewport()->update();
      return true;
    }
    else
    {
      if (Application::Instance().parameters()->isRegressionMode())
        exit(7);
      //TODO: set error code to non-0 so regression tests fail!
      // probably want to control this with a --regression flag.
    }
  }
  return false;
}

bool SCIRunMainWindow::importLegacyNetworkFile(const QString& filename)
{
	bool success = false;
  if (!filename.isEmpty())
  {
    FileImportCommand command;
    command.set(Variables::Filename, filename.toStdString());
    if (command.execute())
    {
      statusBar()->showMessage(tr("File imported: ") + filename, 2000);
      networkProgressBar_->updateTotalModules(networkEditor_->numModules());
      networkEditor_->viewport()->update();
      success = true;
    }
    else
    {
      statusBar()->showMessage(tr("File import failed: ") + filename, 2000);
    }
		auto log = QString::fromStdString(command.logContents());
    auto isoString = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::universal_time());
    auto logFileName = QString::fromStdString(Core::Logging::LogSettings::Instance().logDirectory().string())
      + "/" + (strippedName(filename) + "_importLog_" + QString::fromStdString(isoString) + ".log");
		QFile logFile(logFileName);
    if (logFile.open(QFile::WriteOnly | QFile::Text))
		{
			QTextStream stream(&logFile);
			stream << log;
			QMessageBox::information(this, "SRN File Import", "SRN File Import log file can be found here: " + logFileName
				+ "\n\nAdditionally, check the log directory for a list of missing modules (look for file missingModules.log)");
    }
		else
		{
			QMessageBox::information(this, "SRN File Import", "Failed to write SRN File Import log file: " + logFileName);
		}
  }
  return success;
}

void SCIRunMainWindow::setCurrentFile(const QString& fileName)
{
  currentFile_ = fileName;
  setCurrentFileName(currentFile_.toStdString());
  setWindowModified(false);
  auto shownName = tr("Untitled");
  if (!currentFile_.isEmpty())
  {
    shownName = strippedName(currentFile_);
    latestNetworkDirectory_ = QFileInfo(currentFile_).dir();
    recentFiles_.removeAll(currentFile_);
    recentFiles_.prepend(currentFile_);
    updateRecentFileActions();
  }
  setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("SCIRun")));
}

void SCIRunMainWindow::runPythonScript(const QString& scriptFileName)
{
#ifdef BUILD_WITH_PYTHON
  NetworkEditor::InEditingContext iec(networkEditor_);
  GuiLogger::logInfoQ("RUNNING PYTHON SCRIPT: " + scriptFileName);
  PythonInterpreter::Instance().importSCIRunLibrary();
  PythonInterpreter::Instance().run_file(scriptFileName.toStdString());
  statusBar()->showMessage(tr("Script is running."), 2000);
#else
  GuiLogger::logInfo("Python not included in this build, cannot run " + scriptFileName);
#endif
}

bool SCIRunMainWindow::isInFavorites(const QString& module) const
{
	return favoriteModuleNames_.contains(module);
}

void SCIRunMainWindow::setDataDirectory(const QString& dir)
{
  if (!dir.isEmpty())
  {
    prefsWindow_->scirunDataLineEdit_->setText(dir);
    prefsWindow_->scirunDataLineEdit_->setToolTip(dir);

    RemembersFileDialogDirectory::setStartingDir(dir);
    Preferences::Instance().setDataDirectory(dir.toStdString());
    Q_EMIT dataDirectorySet(dir);
  }
}

void SCIRunMainWindow::setDataPath(const QString& dirs)
{
	if (!dirs.isEmpty())
	{
    //prefsWindow_->scirunDataPathTextEdit_->setPlainText(dirs);
    //prefsWindow_->scirunDataPathTextEdit_->setToolTip(dirs);

		Preferences::Instance().setDataPath(dirs.toStdString());
	}
}

void SCIRunMainWindow::addToDataDirectory(const QString& dir)
{
	if (!dir.isEmpty())
	{
    // auto text = prefsWindow_->scirunDataPathTextEdit_->toPlainText();
		// if (!text.isEmpty())
		// 	text += ";\n";
		// text += dir;
    // prefsWindow_->scirunDataPathTextEdit_->setPlainText(text);
    // prefsWindow_->scirunDataPathTextEdit_->setToolTip(prefsWindow_->scirunDataPathTextEdit_->toPlainText());

		RemembersFileDialogDirectory::setStartingDir(dir);
		Preferences::Instance().addToDataPath(dir.toStdString());
	}
}

void SCIRunMainWindow::addToolkit(const QString& filename, const QString& directory, const ToolkitFile& toolkit)
{
  auto menu = menuToolkits_->addMenu(filename);
  auto networks = menu->addMenu("Networks");
  toolkitDirectories_[filename] = directory;
  toolkitNetworks_[filename] = toolkit;
  auto fullpath = directory + QDir::separator() + filename + ".toolkit";
  toolkitMenus_[fullpath] = menu;
  std::map<std::string, std::map<std::string, NetworkFile>> toolkitMenuData;
  for (const auto& toolkitPair : toolkit.networks)
  {
    std::vector<std::string> elements;
    for (const auto& p : boost::filesystem::path(toolkitPair.first))
      elements.emplace_back(p.filename().string());

    if (elements.size() == 2)
    {
      toolkitMenuData[elements[0]][elements[1]] = toolkitPair.second;
    }
    else
    {
      qDebug() << "Cannot handle toolkit folders of depth > 1";
    }
  }

  for (const auto& t1 : toolkitMenuData)
  {
    auto t1menu = networks->addMenu(QString::fromStdString(t1.first));
    for (const auto& t2 : t1.second)
    {
      auto networkAction = t1menu->addAction(QString::fromStdString(t2.first));
      std::ostringstream net;
      XMLSerializer::save_xml(t2.second, net, "networkFile");
      networkAction->setProperty("network", QString::fromStdString(net.str()));
      connect(networkAction, SIGNAL(triggered()), this, SLOT(openToolkitNetwork()));
    }
  }

  auto folder = menu->addAction("Open Toolkit Directory");
  folder->setProperty("path", directory);
  connect(folder, SIGNAL(triggered()), this, SLOT(openToolkitFolder()));

  auto remove = menu->addAction("Remove Toolkit...");
  remove->setProperty("filename", filename);
  remove->setProperty("fullpath", fullpath);
  connect(remove, SIGNAL(triggered()), this, SLOT(removeToolkit()));

  if (!startup_)
  {
    QMessageBox::information(this, "Toolkit loaded", "Toolkit " + filename +
      " successfully imported. A new submenu is available under Toolkits for loading networks.\n\n"
      + "Remember to update your data folder under Preferences->Paths.");
    actionPreferences_->trigger();
  }
}
<|endoftext|>