<commit_before>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *   Copyright (c) 2012 Luke Parry    <l.parry@warwick.ac.uk>              *
 *                                                                         *
 *   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 <QAction>
# include <QMenu>
# include <QTimer>
#include <QPointer>
#include <boost/signal.hpp>
#include <boost/bind.hpp>

#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>

#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Control.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/Selection.h>
#include <Gui/ViewProvider.h>
#include <Gui/ViewProviderDocumentObject.h>
#include <Gui/ViewProviderDocumentObjectGroup.h>

#include "MDIViewPage.h"
#include "ViewProviderPage.h"
#include <Mod/TechDraw/App/DrawPage.h>
#include <Mod/TechDraw/App/DrawView.h>
#include <Mod/TechDraw/App/DrawProjGroupItem.h>
#include <Mod/TechDraw/App/DrawViewDimension.h>
#include <Mod/TechDraw/App/DrawHatch.h>
#include <Mod/TechDraw/App/DrawUtil.h>

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderPage::ViewProviderPage()
  : m_mdiView(0),
    m_docReady(true)
{
    sPixmap = "TechDraw_Tree_Page";

    Visibility.setStatus(App::Property::Hidden,true);
    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderPage::~ViewProviderPage()
{
}

void ViewProviderPage::attach(App::DocumentObject *pcFeat)
{
    ViewProviderDocumentObject::attach(pcFeat);

    auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1);
    auto feature = getDrawPage();
    if (feature != nullptr) {
        connectGuiRepaint = feature->signalGuiPaint.connect(bnd);
    } else {
        Base::Console().Log("VPP::attach has no Feature!\n");
    }

}

void ViewProviderPage::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderPage::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();
    StrList.push_back("Drawing");
    return StrList;
}

void ViewProviderPage::show(void)
{
    showMDIViewPage();
}

void ViewProviderPage::hide(void)
{
    if (!m_mdiView.isNull()) {                                //m_mdiView is a QPointer
        // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614
        //Gui::getMainWindow()->activatePreviousWindow();
        Gui::getMainWindow()->removeWindow(m_mdiView);
    }
    ViewProviderDocumentObject::hide();
}

void ViewProviderPage::updateData(const App::Property* prop)
{
    if (prop == &(getDrawPage()->KeepUpdated)) {
       if (getDrawPage()->KeepUpdated.getValue()) {
           sPixmap = "TechDraw_Tree_Page";
           if (!m_mdiView.isNull() &&
               !getDrawPage()->isUnsetting()) {
               m_mdiView->updateDrawing();
           }
       } else {
           sPixmap = "TechDraw_Tree_Page_Unsync";
       }
    }

    //if a view is added/deleted, rebuild the visual
    if (prop == &(getDrawPage()->Views)) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    //if the template is changed, rebuild the visual
    } else if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView &&
          !getDrawPage()->isUnsetting()) {
            m_mdiView->matchSceneRectToTemplate();
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::updateData(prop);
}

bool ViewProviderPage::onDelete(const std::vector<std::string> &items)
{
    if (!m_mdiView.isNull()) {
        Gui::getMainWindow()->removeWindow(m_mdiView);
        Gui::getMainWindow()->activatePreviousWindow();
        m_mdiView->deleteLater(); // Delete the drawing m_mdiView;
    } else {
        // MDIViewPage is not displayed yet so don't try to delete it!
        Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n");
    }
    Gui::Selection().clearSelection();
    return ViewProviderDocumentObject::onDelete(items);
}

void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member);
    QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member);
//    act->setData(QVariant(1));  // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073   //this is edit ModNum
    act->setData(QVariant((int) ViewProvider::Default));
}

bool ViewProviderPage::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default) {
        showMDIViewPage();   // show the drawing
        Gui::getMainWindow()->setActiveWindow(m_mdiView);
        return false;
    } else {
        Gui::ViewProviderDocumentObject::setEdit(ModNum);
    }
    return true;
}

bool ViewProviderPage::doubleClicked(void)
{
    showMDIViewPage();
    Gui::getMainWindow()->setActiveWindow(m_mdiView);
    return true;
}

bool ViewProviderPage::showMDIViewPage()
{
    if (isRestoring()) {
        return true;
    }

    if (m_mdiView.isNull()){
        Gui::Document* doc = Gui::Application::Instance->getDocument
            (pcObject->getDocument());
        m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow());
        m_mdiView->setWindowTitle(QObject::tr("Drawing viewer") + QString::fromLatin1("[*]"));
        m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page"));
        m_mdiView->updateDrawing(true);
        Gui::getMainWindow()->addWindow(m_mdiView);
        m_mdiView->viewAll();
    } else {
        m_mdiView->updateDrawing(true);
        m_mdiView->updateTemplate(true);
    }
    return true;
}

std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const
{
    std::vector<App::DocumentObject*> temp;

    App::DocumentObject *templateFeat = 0;
    templateFeat = getDrawPage()->Template.getValue();

    if(templateFeat) {
        temp.push_back(templateFeat);
    }

    // Collect any child views
    // for Page, valid children are any View except: DrawProjGroupItem
    //                                               DrawViewDimension
    //                                               any FeatuerView in a DrawViewClip
    //                                               DrawHatch

    const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues();

    try {
      for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
          TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it);
          App::DocumentObject *docObj = *it;
          // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere
          if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId())            ||
             (featView && featView->isInClip()) )
              continue;
          else
              temp.push_back(*it);
      }
      return temp;
    } catch (...) {
        std::vector<App::DocumentObject*> tmp;
        return tmp;
    }
}

void ViewProviderPage::unsetEdit(int ModNum)
{
    Q_UNUSED(ModNum);
    static_cast<void>(showMDIViewPage());
    return;
}

MDIViewPage* ViewProviderPage::getMDIViewPage()
{
    if (m_mdiView.isNull()) {
        Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n");
        return 0;
    } else {
        return m_mdiView;
    }
}

void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg)
{
    if(!m_mdiView.isNull()) {
        if(msg.Type == Gui::SelectionChanges::SetSelection) {
            m_mdiView->clearSelection();
            std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName);

            for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) {
                Gui::SelectionSingleton::SelObj selObj = *it;
                if(selObj.pObject == getDrawPage())
                    continue;

                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me   wf: don't think this is ever executed
                    }
                } else {
                        m_mdiView->selectFeature(selObj.pObject, true);
                }
            }
        } else {
            bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false;
            Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument());
            App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName);
            if(obj) {
                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me
                    } else {
                        m_mdiView->selectFeature(obj, selectState);
                    }
                }
            }
        }  //else (Gui::SelectionChanges::SetPreselect)
    }
}

void ViewProviderPage::onChanged(const App::Property *prop)
{
    if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView) {
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderPage::startRestoring()
{
    m_docReady = false;
    Gui::ViewProviderDocumentObject::startRestoring();
}

void ViewProviderPage::finishRestoring()
{
    m_docReady = true;
    static_cast<void>(showMDIViewPage());
    Gui::ViewProviderDocumentObject::finishRestoring();
}

bool ViewProviderPage::isShow(void) const
{
    return Visibility.getValue();
}

//! Redo the whole visual page
void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp)
{
    if (dp == getDrawPage()) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    }
}

TechDraw::DrawPage* ViewProviderPage::getDrawPage() const
{
    //during redo, pcObject can become invalid, but non-zero??
    if (!pcObject) {
        Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n");
        return nullptr;
    }
    return dynamic_cast<TechDraw::DrawPage*>(pcObject);
}
<commit_msg>Fix #2967 Ph2 Do not show page on restore.<commit_after>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *   Copyright (c) 2012 Luke Parry    <l.parry@warwick.ac.uk>              *
 *                                                                         *
 *   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 <QAction>
# include <QMenu>
# include <QTimer>
#include <QPointer>
#include <boost/signal.hpp>
#include <boost/bind.hpp>

#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>

#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Control.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/Selection.h>
#include <Gui/ViewProvider.h>
#include <Gui/ViewProviderDocumentObject.h>
#include <Gui/ViewProviderDocumentObjectGroup.h>

#include "MDIViewPage.h"
#include "ViewProviderPage.h"
#include <Mod/TechDraw/App/DrawPage.h>
#include <Mod/TechDraw/App/DrawView.h>
#include <Mod/TechDraw/App/DrawProjGroupItem.h>
#include <Mod/TechDraw/App/DrawViewDimension.h>
#include <Mod/TechDraw/App/DrawHatch.h>
#include <Mod/TechDraw/App/DrawUtil.h>

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderPage::ViewProviderPage()
  : m_mdiView(0),
    m_docReady(true)
{
    sPixmap = "TechDraw_Tree_Page";

    Visibility.setStatus(App::Property::Hidden,true);
    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderPage::~ViewProviderPage()
{
}

void ViewProviderPage::attach(App::DocumentObject *pcFeat)
{
    ViewProviderDocumentObject::attach(pcFeat);

    auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1);
    auto feature = getDrawPage();
    if (feature != nullptr) {
        connectGuiRepaint = feature->signalGuiPaint.connect(bnd);
    } else {
        Base::Console().Log("VPP::attach has no Feature!\n");
    }

}

void ViewProviderPage::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderPage::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();
    StrList.push_back("Drawing");
    return StrList;
}

void ViewProviderPage::show(void)
{
    showMDIViewPage();
}

void ViewProviderPage::hide(void)
{
    if (!m_mdiView.isNull()) {                                //m_mdiView is a QPointer
        // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614
        //Gui::getMainWindow()->activatePreviousWindow();
        Gui::getMainWindow()->removeWindow(m_mdiView);
    }
    ViewProviderDocumentObject::hide();
}

void ViewProviderPage::updateData(const App::Property* prop)
{
    if (prop == &(getDrawPage()->KeepUpdated)) {
       if (getDrawPage()->KeepUpdated.getValue()) {
           sPixmap = "TechDraw_Tree_Page";
           if (!m_mdiView.isNull() &&
               !getDrawPage()->isUnsetting()) {
               m_mdiView->updateDrawing();
           }
       } else {
           sPixmap = "TechDraw_Tree_Page_Unsync";
       }
    }

    //if a view is added/deleted, rebuild the visual
    if (prop == &(getDrawPage()->Views)) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    //if the template is changed, rebuild the visual
    } else if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView &&
          !getDrawPage()->isUnsetting()) {
            m_mdiView->matchSceneRectToTemplate();
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::updateData(prop);
}

bool ViewProviderPage::onDelete(const std::vector<std::string> &items)
{
    if (!m_mdiView.isNull()) {
        Gui::getMainWindow()->removeWindow(m_mdiView);
        Gui::getMainWindow()->activatePreviousWindow();
        m_mdiView->deleteLater(); // Delete the drawing m_mdiView;
    } else {
        // MDIViewPage is not displayed yet so don't try to delete it!
        Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n");
    }
    Gui::Selection().clearSelection();
    return ViewProviderDocumentObject::onDelete(items);
}

void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member);
    QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member);
//    act->setData(QVariant(1));  // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073   //this is edit ModNum
    act->setData(QVariant((int) ViewProvider::Default));
}

bool ViewProviderPage::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default) {
        showMDIViewPage();   // show the drawing
        Gui::getMainWindow()->setActiveWindow(m_mdiView);
        return false;
    } else {
        Gui::ViewProviderDocumentObject::setEdit(ModNum);
    }
    return true;
}

bool ViewProviderPage::doubleClicked(void)
{
    showMDIViewPage();
    Gui::getMainWindow()->setActiveWindow(m_mdiView);
    return true;
}

bool ViewProviderPage::showMDIViewPage()
{
    if (isRestoring()) {
        return true;
    }

    if (m_mdiView.isNull()){
        Gui::Document* doc = Gui::Application::Instance->getDocument
            (pcObject->getDocument());
        m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow());
        m_mdiView->setWindowTitle(QObject::tr("Drawing viewer") + QString::fromLatin1("[*]"));
        m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page"));
        m_mdiView->updateDrawing(true);
        Gui::getMainWindow()->addWindow(m_mdiView);
        m_mdiView->viewAll();
    } else {
        m_mdiView->updateDrawing(true);
        m_mdiView->updateTemplate(true);
    }
    return true;
}

std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const
{
    std::vector<App::DocumentObject*> temp;

    App::DocumentObject *templateFeat = 0;
    templateFeat = getDrawPage()->Template.getValue();

    if(templateFeat) {
        temp.push_back(templateFeat);
    }

    // Collect any child views
    // for Page, valid children are any View except: DrawProjGroupItem
    //                                               DrawViewDimension
    //                                               any FeatuerView in a DrawViewClip
    //                                               DrawHatch

    const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues();

    try {
      for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
          TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it);
          App::DocumentObject *docObj = *it;
          // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere
          if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId())            ||
             (featView && featView->isInClip()) )
              continue;
          else
              temp.push_back(*it);
      }
      return temp;
    } catch (...) {
        std::vector<App::DocumentObject*> tmp;
        return tmp;
    }
}

void ViewProviderPage::unsetEdit(int ModNum)
{
    Q_UNUSED(ModNum);
    static_cast<void>(showMDIViewPage());
    return;
}

MDIViewPage* ViewProviderPage::getMDIViewPage()
{
    if (m_mdiView.isNull()) {
        Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n");
        return 0;
    } else {
        return m_mdiView;
    }
}

void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg)
{
    if(!m_mdiView.isNull()) {
        if(msg.Type == Gui::SelectionChanges::SetSelection) {
            m_mdiView->clearSelection();
            std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName);

            for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) {
                Gui::SelectionSingleton::SelObj selObj = *it;
                if(selObj.pObject == getDrawPage())
                    continue;

                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me   wf: don't think this is ever executed
                    }
                } else {
                        m_mdiView->selectFeature(selObj.pObject, true);
                }
            }
        } else {
            bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false;
            Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument());
            App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName);
            if(obj) {
                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me
                    } else {
                        m_mdiView->selectFeature(obj, selectState);
                    }
                }
            }
        }  //else (Gui::SelectionChanges::SetPreselect)
    }
}

void ViewProviderPage::onChanged(const App::Property *prop)
{
    if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView) {
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderPage::startRestoring()
{
    m_docReady = false;
    Gui::ViewProviderDocumentObject::startRestoring();
}

void ViewProviderPage::finishRestoring()
{
    m_docReady = true;
    //control drawing opening on restore based on Preference
    //mantis #2967 ph2 - don't even show blank page
    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General");
    bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l);
    if (autoUpdate) {
        static_cast<void>(showMDIViewPage());
    }
    Gui::ViewProviderDocumentObject::finishRestoring();
}

bool ViewProviderPage::isShow(void) const
{
    return Visibility.getValue();
}

//! Redo the whole visual page
void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp)
{
    if (dp == getDrawPage()) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    }
}

TechDraw::DrawPage* ViewProviderPage::getDrawPage() const
{
    //during redo, pcObject can become invalid, but non-zero??
    if (!pcObject) {
        Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n");
        return nullptr;
    }
    return dynamic_cast<TechDraw::DrawPage*>(pcObject);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2009
 *
 * School of Computing, University of Utah,
 * Salt Lake City, UT 84112, USA
 *
 * and the Gauss Group
 * http://www.cs.utah.edu/formal_verification
 *
 * See LICENSE for licensing information
 */

#ifndef _TRACE_HPP
#define _TRACE_HPP

#include <vector>
#include <list>
#include <algorithm>
#include <sstream>
#include <memory>
#include <boost/range/adaptor/reversed.hpp>

#include "Envelope.hpp"
#include "Transition.hpp"

using std::unique_ptr;
using std::shared_ptr;
using std::vector;
using std::list; // XXX: remove

/*
 * Each process collects a list of transitions.
 */
class Trace {

public:
    const int pid;

    Trace(int p) : pid(p) {}

    inline unsigned int size() const { return tlist.size(); }

    inline Transition & get(int index) const { return *tlist[index]; }

    inline Transition & getLast() const { return *tlist.back(); }

    bool add(unique_ptr<Envelope> t);

    inline auto begin() { return tlist.begin(); }

    inline auto end() { return tlist.end(); }

    inline auto begin() const { return tlist.begin(); }

    inline auto end() const { return tlist.end(); }

    auto reverse() {
        return boost::adaptors::reverse(tlist);
    }

    vector<shared_ptr<Transition> > getRequestedProcs(const Transition &child) const {
        assert(child.pid == pid);
        vector<shared_ptr<Transition> > result;
        for (auto req_proc : child.getEnvelope().req_procs) {
            result.push_back(tlist[req_proc]);
        }
        return result;
    }

private:
    vector<shared_ptr<Transition> > tlist;

    list<int> ulist;

    bool intraCB (const Transition &f, const Transition &s) const;
};

#endif
<commit_msg>In getLast() return a shared_ptr instead of a const &.<commit_after>/*
 * Copyright (c) 2008-2009
 *
 * School of Computing, University of Utah,
 * Salt Lake City, UT 84112, USA
 *
 * and the Gauss Group
 * http://www.cs.utah.edu/formal_verification
 *
 * See LICENSE for licensing information
 */

#ifndef _TRACE_HPP
#define _TRACE_HPP

#include <vector>
#include <list>
#include <algorithm>
#include <sstream>
#include <memory>
#include <boost/range/adaptor/reversed.hpp>

#include "Envelope.hpp"
#include "Transition.hpp"

using std::unique_ptr;
using std::shared_ptr;
using std::vector;
using std::list; // XXX: remove

/*
 * Each process collects a list of transitions.
 */
class Trace {

public:
    const int pid;

    Trace(int p) : pid(p) {}

    inline unsigned int size() const { return tlist.size(); }

    inline Transition & get(int index) const { return *tlist[index]; }

    inline shared_ptr<Transition> getLast() const { return tlist.back(); }

    bool add(unique_ptr<Envelope> t);

    inline auto begin() { return tlist.begin(); }

    inline auto end() { return tlist.end(); }

    inline auto begin() const { return tlist.begin(); }

    inline auto end() const { return tlist.end(); }

    auto reverse() {
        return boost::adaptors::reverse(tlist);
    }

    vector<shared_ptr<Transition> > getRequestedProcs(const Transition &child) const {
        assert(child.pid == pid);
        vector<shared_ptr<Transition> > result;
        for (auto req_proc : child.getEnvelope().req_procs) {
            result.push_back(tlist[req_proc]);
        }
        return result;
    }

private:
    vector<shared_ptr<Transition> > tlist;

    list<int> ulist;

    bool intraCB (const Transition &f, const Transition &s) const;
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: modulepcr.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 13:19:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"

#ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX
#include "modulepcr.hxx"
#endif

#ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H
#include <rtl/instance.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/getglobalmutex.hxx>
#endif

//........................................................................
namespace pcr
{
//........................................................................

    IMPLEMENT_MODULE( PcrModule, "pcr" )

//........................................................................
} // namespace pcr
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.8.276); FILE MERGED 2008/04/01 12:29:50 thb 1.8.276.2: #i85898# Stripping all external header guards 2008/03/31 12:31:50 rt 1.8.276.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: modulepcr.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "modulepcr.hxx"

#ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H
#include <rtl/instance.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/getglobalmutex.hxx>
#endif

//........................................................................
namespace pcr
{
//........................................................................

    IMPLEMENT_MODULE( PcrModule, "pcr" )

//........................................................................
} // namespace pcr
//........................................................................
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *   Copyright (c) 2012 Luke Parry    <l.parry@warwick.ac.uk>              *
 *                                                                         *
 *   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 <QAction>
# include <QMenu>
# include <QTimer>
#include <QPointer>
#include <boost/signal.hpp>
#include <boost/bind.hpp>

#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>

#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Control.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/Selection.h>
#include <Gui/ViewProvider.h>
#include <Gui/ViewProviderDocumentObject.h>
#include <Gui/ViewProviderDocumentObjectGroup.h>

#include "MDIViewPage.h"
#include "ViewProviderPage.h"
#include <Mod/TechDraw/App/DrawPage.h>
#include <Mod/TechDraw/App/DrawView.h>
#include <Mod/TechDraw/App/DrawProjGroupItem.h>
#include <Mod/TechDraw/App/DrawViewDimension.h>
#include <Mod/TechDraw/App/DrawHatch.h>
#include <Mod/TechDraw/App/DrawUtil.h>

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderPage::ViewProviderPage()
  : m_mdiView(0),
    m_docReady(true)
{
    sPixmap = "TechDraw_Tree_Page";

    Visibility.setStatus(App::Property::Hidden,true);
    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderPage::~ViewProviderPage()
{
}

void ViewProviderPage::attach(App::DocumentObject *pcFeat)
{
    ViewProviderDocumentObject::attach(pcFeat);

    auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1);
    auto feature = getDrawPage();
    if (feature != nullptr) {
        connectGuiRepaint = feature->signalGuiPaint.connect(bnd);
    } else {
        Base::Console().Log("VPP::attach has no Feature!\n");
    }

}

void ViewProviderPage::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderPage::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();
    StrList.push_back("Drawing");
    return StrList;
}

void ViewProviderPage::show(void)
{
    showMDIViewPage();
}

void ViewProviderPage::hide(void)
{
    if (!m_mdiView.isNull()) {                                //m_mdiView is a QPointer
        // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614
        //Gui::getMainWindow()->activatePreviousWindow();
        Gui::getMainWindow()->removeWindow(m_mdiView);
    }
    ViewProviderDocumentObject::hide();
}

void ViewProviderPage::updateData(const App::Property* prop)
{
    if (prop == &(getDrawPage()->KeepUpdated)) {
       if (getDrawPage()->KeepUpdated.getValue()) {
           sPixmap = "TechDraw_Tree_Page";
           if (!m_mdiView.isNull() &&
               !getDrawPage()->isUnsetting()) {
               m_mdiView->updateDrawing();
           }
       } else {
           sPixmap = "TechDraw_Tree_Page_Unsync";
       }
    }

    //if a view is added/deleted, rebuild the visual
    if (prop == &(getDrawPage()->Views)) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    //if the template is changed, rebuild the visual
    } else if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView &&
          !getDrawPage()->isUnsetting()) {
            m_mdiView->matchSceneRectToTemplate();
            m_mdiView->updateTemplate();
        }
    //if the Label changes, rename the tab
    } else if (prop == &(getDrawPage()->Label)) {
        if(m_mdiView) {
            QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue());
            m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]"));
        }
    }

    Gui::ViewProviderDocumentObject::updateData(prop);
}

bool ViewProviderPage::onDelete(const std::vector<std::string> &items)
{
    if (!m_mdiView.isNull()) {
        Gui::getMainWindow()->removeWindow(m_mdiView);
        Gui::getMainWindow()->activatePreviousWindow();
        m_mdiView->deleteLater(); // Delete the drawing m_mdiView;
    } else {
        // MDIViewPage is not displayed yet so don't try to delete it!
        Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n");
    }
    Gui::Selection().clearSelection();
    return ViewProviderDocumentObject::onDelete(items);
}

void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member);
    QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member);
//    act->setData(QVariant(1));  // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073   //this is edit ModNum
    act->setData(QVariant((int) ViewProvider::Default));
}

bool ViewProviderPage::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default) {
        showMDIViewPage();   // show the drawing
        Gui::getMainWindow()->setActiveWindow(m_mdiView);
        return false;
    } else {
        Gui::ViewProviderDocumentObject::setEdit(ModNum);
    }
    return true;
}

bool ViewProviderPage::doubleClicked(void)
{
    showMDIViewPage();
    Gui::getMainWindow()->setActiveWindow(m_mdiView);
    return true;
}

bool ViewProviderPage::showMDIViewPage()
{
    if (isRestoring()) {
        return true;
    }

    if (m_mdiView.isNull()){
        Gui::Document* doc = Gui::Application::Instance->getDocument
            (pcObject->getDocument());
        m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow());
        QString tabTitle = QString::fromUtf8(getDrawPage()->getNameInDocument());
        m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]"));
        m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page"));
        m_mdiView->updateDrawing(true);
        Gui::getMainWindow()->addWindow(m_mdiView);
        m_mdiView->viewAll();
    } else {
        m_mdiView->updateDrawing(true);
        m_mdiView->updateTemplate(true);
    }
    return true;
}

std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const
{
    std::vector<App::DocumentObject*> temp;

    App::DocumentObject *templateFeat = 0;
    templateFeat = getDrawPage()->Template.getValue();

    if(templateFeat) {
        temp.push_back(templateFeat);
    }

    // Collect any child views
    // for Page, valid children are any View except: DrawProjGroupItem
    //                                               DrawViewDimension
    //                                               any FeatuerView in a DrawViewClip
    //                                               DrawHatch

    const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues();

    try {
      for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
          TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it);
          App::DocumentObject *docObj = *it;
          // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere
          if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId())            ||
             (featView && featView->isInClip()) )
              continue;
          else
              temp.push_back(*it);
      }
      return temp;
    } catch (...) {
        std::vector<App::DocumentObject*> tmp;
        return tmp;
    }
}

void ViewProviderPage::unsetEdit(int ModNum)
{
    Q_UNUSED(ModNum);
    static_cast<void>(showMDIViewPage());
    return;
}

MDIViewPage* ViewProviderPage::getMDIViewPage()
{
    if (m_mdiView.isNull()) {
        Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n");
        return 0;
    } else {
        return m_mdiView;
    }
}

void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg)
{
    if(!m_mdiView.isNull()) {
        if(msg.Type == Gui::SelectionChanges::SetSelection) {
            m_mdiView->clearSelection();
            std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName);

            for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) {
                Gui::SelectionSingleton::SelObj selObj = *it;
                if(selObj.pObject == getDrawPage())
                    continue;

                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me   wf: don't think this is ever executed
                    }
                } else {
                        m_mdiView->selectFeature(selObj.pObject, true);
                }
            }
        } else {
            bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false;
            Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument());
            App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName);
            if(obj) {
                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me
                    } else {
                        m_mdiView->selectFeature(obj, selectState);
                    }
                }
            }
        }  //else (Gui::SelectionChanges::SetPreselect)
    }
}

void ViewProviderPage::onChanged(const App::Property *prop)
{
    if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView) {
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderPage::startRestoring()
{
    m_docReady = false;
    Gui::ViewProviderDocumentObject::startRestoring();
}

void ViewProviderPage::finishRestoring()
{
    m_docReady = true;
    //control drawing opening on restore based on Preference
    //mantis #2967 ph2 - don't even show blank page
    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General");
    bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l);
    if (autoUpdate) {
        static_cast<void>(showMDIViewPage());
    }
    Gui::ViewProviderDocumentObject::finishRestoring();
}

bool ViewProviderPage::isShow(void) const
{
    return Visibility.getValue();
}

//! Redo the whole visual page
void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp)
{
    if (dp == getDrawPage()) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    }
}

TechDraw::DrawPage* ViewProviderPage::getDrawPage() const
{
    //during redo, pcObject can become invalid, but non-zero??
    if (!pcObject) {
        Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n");
        return nullptr;
    }
    return dynamic_cast<TechDraw::DrawPage*>(pcObject);
}
<commit_msg>Change removeWindow logic for consistency<commit_after>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *   Copyright (c) 2012 Luke Parry    <l.parry@warwick.ac.uk>              *
 *                                                                         *
 *   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 <QAction>
# include <QMenu>
# include <QTimer>
#include <QPointer>
#include <boost/signal.hpp>
#include <boost/bind.hpp>

#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>

#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <Gui/Command.h>
#include <Gui/Control.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/Selection.h>
#include <Gui/ViewProvider.h>
#include <Gui/ViewProviderDocumentObject.h>
#include <Gui/ViewProviderDocumentObjectGroup.h>

#include "MDIViewPage.h"
#include "ViewProviderPage.h"
#include <Mod/TechDraw/App/DrawPage.h>
#include <Mod/TechDraw/App/DrawView.h>
#include <Mod/TechDraw/App/DrawProjGroupItem.h>
#include <Mod/TechDraw/App/DrawViewDimension.h>
#include <Mod/TechDraw/App/DrawHatch.h>
#include <Mod/TechDraw/App/DrawUtil.h>

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderPage::ViewProviderPage()
  : m_mdiView(0),
    m_docReady(true)
{
    sPixmap = "TechDraw_Tree_Page";

    Visibility.setStatus(App::Property::Hidden,true);
    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderPage::~ViewProviderPage()
{
}

void ViewProviderPage::attach(App::DocumentObject *pcFeat)
{
    ViewProviderDocumentObject::attach(pcFeat);

    auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1);
    auto feature = getDrawPage();
    if (feature != nullptr) {
        connectGuiRepaint = feature->signalGuiPaint.connect(bnd);
    } else {
        Base::Console().Log("VPP::attach has no Feature!\n");
    }

}

void ViewProviderPage::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderPage::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();
    StrList.push_back("Drawing");
    return StrList;
}

void ViewProviderPage::show(void)
{
    showMDIViewPage();
}

void ViewProviderPage::hide(void)
{
    if (!m_mdiView.isNull()) {                                //m_mdiView is a QPointer
        // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614
        //Gui::getMainWindow()->activatePreviousWindow();
        Gui::getMainWindow()->removeWindow(m_mdiView);
    }
    ViewProviderDocumentObject::hide();
}

void ViewProviderPage::updateData(const App::Property* prop)
{
    if (prop == &(getDrawPage()->KeepUpdated)) {
       if (getDrawPage()->KeepUpdated.getValue()) {
           sPixmap = "TechDraw_Tree_Page";
           if (!m_mdiView.isNull() &&
               !getDrawPage()->isUnsetting()) {
               m_mdiView->updateDrawing();
           }
       } else {
           sPixmap = "TechDraw_Tree_Page_Unsync";
       }
    }

    //if a view is added/deleted, rebuild the visual
    if (prop == &(getDrawPage()->Views)) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    //if the template is changed, rebuild the visual
    } else if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView &&
          !getDrawPage()->isUnsetting()) {
            m_mdiView->matchSceneRectToTemplate();
            m_mdiView->updateTemplate();
        }
    //if the Label changes, rename the tab
    } else if (prop == &(getDrawPage()->Label)) {
        if(m_mdiView) {
            QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue());
            m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]"));
        }
    }

    Gui::ViewProviderDocumentObject::updateData(prop);
}

bool ViewProviderPage::onDelete(const std::vector<std::string> &items)
{
    if (!m_mdiView.isNull()) {
        Gui::getMainWindow()->removeWindow(m_mdiView);
//        Gui::getMainWindow()->activatePreviousWindow();   //changed for consistency. see comment in hide() above.
                                                            //note: doesn't fix problem here.
                                                            //3d view is still not maximized after page is deleted.
        m_mdiView->deleteLater(); // Delete the drawing m_mdiView;
    } else {
        // MDIViewPage is not displayed yet so don't try to delete it!
        Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n");
    }
    Gui::Selection().clearSelection();
    return ViewProviderDocumentObject::onDelete(items);
}

void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
    Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member);
    QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member);
//    act->setData(QVariant(1));  // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073   //this is edit ModNum
    act->setData(QVariant((int) ViewProvider::Default));
}

bool ViewProviderPage::setEdit(int ModNum)
{
    if (ModNum == ViewProvider::Default) {
        showMDIViewPage();   // show the drawing
        Gui::getMainWindow()->setActiveWindow(m_mdiView);
        return false;
    } else {
        Gui::ViewProviderDocumentObject::setEdit(ModNum);
    }
    return true;
}

bool ViewProviderPage::doubleClicked(void)
{
    showMDIViewPage();
    Gui::getMainWindow()->setActiveWindow(m_mdiView);
    return true;
}

bool ViewProviderPage::showMDIViewPage()
{
    if (isRestoring()) {
        return true;
    }

    if (m_mdiView.isNull()){
        Gui::Document* doc = Gui::Application::Instance->getDocument
            (pcObject->getDocument());
        m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow());
        QString tabTitle = QString::fromUtf8(getDrawPage()->getNameInDocument());
        m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]"));
        m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page"));
        m_mdiView->updateDrawing(true);
        Gui::getMainWindow()->addWindow(m_mdiView);
        m_mdiView->viewAll();
    } else {
        m_mdiView->updateDrawing(true);
        m_mdiView->updateTemplate(true);
    }
    return true;
}

std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const
{
    std::vector<App::DocumentObject*> temp;

    App::DocumentObject *templateFeat = 0;
    templateFeat = getDrawPage()->Template.getValue();

    if(templateFeat) {
        temp.push_back(templateFeat);
    }

    // Collect any child views
    // for Page, valid children are any View except: DrawProjGroupItem
    //                                               DrawViewDimension
    //                                               any FeatuerView in a DrawViewClip
    //                                               DrawHatch

    const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues();

    try {
      for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) {
          TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it);
          App::DocumentObject *docObj = *it;
          // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere
          if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())    ||
             docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId())            ||
             (featView && featView->isInClip()) )
              continue;
          else
              temp.push_back(*it);
      }
      return temp;
    } catch (...) {
        std::vector<App::DocumentObject*> tmp;
        return tmp;
    }
}

void ViewProviderPage::unsetEdit(int ModNum)
{
    Q_UNUSED(ModNum);
    static_cast<void>(showMDIViewPage());
    return;
}

MDIViewPage* ViewProviderPage::getMDIViewPage()
{
    if (m_mdiView.isNull()) {
        Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n");
        return 0;
    } else {
        return m_mdiView;
    }
}

void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg)
{
    if(!m_mdiView.isNull()) {
        if(msg.Type == Gui::SelectionChanges::SetSelection) {
            m_mdiView->clearSelection();
            std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName);

            for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) {
                Gui::SelectionSingleton::SelObj selObj = *it;
                if(selObj.pObject == getDrawPage())
                    continue;

                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me   wf: don't think this is ever executed
                    }
                } else {
                        m_mdiView->selectFeature(selObj.pObject, true);
                }
            }
        } else {
            bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false;
            Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument());
            App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName);
            if(obj) {
                std::string str = msg.pSubName;
                // If it's a subfeature, don't select feature
                if (!str.empty()) {
                    if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" ||
                        TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") {
                        // TODO implement me
                    } else {
                        m_mdiView->selectFeature(obj, selectState);
                    }
                }
            }
        }  //else (Gui::SelectionChanges::SetPreselect)
    }
}

void ViewProviderPage::onChanged(const App::Property *prop)
{
    if (prop == &(getDrawPage()->Template)) {
       if(m_mdiView) {
            m_mdiView->updateTemplate();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderPage::startRestoring()
{
    m_docReady = false;
    Gui::ViewProviderDocumentObject::startRestoring();
}

void ViewProviderPage::finishRestoring()
{
    m_docReady = true;
    //control drawing opening on restore based on Preference
    //mantis #2967 ph2 - don't even show blank page
    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General");
    bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l);
    if (autoUpdate) {
        static_cast<void>(showMDIViewPage());
    }
    Gui::ViewProviderDocumentObject::finishRestoring();
}

bool ViewProviderPage::isShow(void) const
{
    return Visibility.getValue();
}

//! Redo the whole visual page
void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp)
{
    if (dp == getDrawPage()) {
        if(!m_mdiView.isNull() &&
           !getDrawPage()->isUnsetting()) {
            m_mdiView->updateDrawing();
        }
    }
}

TechDraw::DrawPage* ViewProviderPage::getDrawPage() const
{
    //during redo, pcObject can become invalid, but non-zero??
    if (!pcObject) {
        Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n");
        return nullptr;
    }
    return dynamic_cast<TechDraw::DrawPage*>(pcObject);
}
<|endoftext|>


<commit_before>
/*
 * Copyright (C) 2013 Michael Imamura
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

#include "StdAfx.h"

#include <iostream>
#include <string>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "App.h"
#include "Exception.h"

using namespace AISDL;

/// Initialize each of the SDL subsystems.
static void InitApp() {
	SDL_LogSetAllPriority(SDL_LOG_PRIORITY_INFO);

	SDL_Log("Starting up all SDL subsystems and libraries.");

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
		throw Exception(std::string("SDL init: ") + SDL_GetError());
	}

	int reqFmts = IMG_INIT_JPG | IMG_INIT_PNG;
	int actualFmts = IMG_Init(reqFmts);
	if ((actualFmts & reqFmts) != reqFmts) {
		throw Exception(std::string("SDL_image init: ") + IMG_GetError());
	}

	if (TTF_Init() == -1) {
		throw Exception(std::string("SDL_ttf init: ") + TTF_GetError());
	}
}

/// Shutdown each of the SDL subsystems.
static void ShutdownApp() {
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();
}

#ifdef _WIN32
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
#else
int main(int argc, char** argv) {
#endif
	srand(static_cast<unsigned int>(time(nullptr)));

	try {
		InitApp();
		App().Run();
	}
	catch (Exception &ex) {
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
			"Adventures in SDL2", ex.what(), NULL);

		std::cerr << ex.what() << std::endl;

		return 1;
	}

	ShutdownApp();

	return 0;
}
<commit_msg>Use simpler Exception constructor.<commit_after>
/*
 * Copyright (C) 2013 Michael Imamura
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

#include "StdAfx.h"

#include <iostream>
#include <string>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "App.h"
#include "Exception.h"

using namespace AISDL;

/// Initialize each of the SDL subsystems.
static void InitApp() {
	SDL_LogSetAllPriority(SDL_LOG_PRIORITY_INFO);

	SDL_Log("Starting up all SDL subsystems and libraries.");

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
		throw Exception("SDL init", SDL_GetError());
	}

	int reqFmts = IMG_INIT_JPG | IMG_INIT_PNG;
	int actualFmts = IMG_Init(reqFmts);
	if ((actualFmts & reqFmts) != reqFmts) {
		throw Exception("SDL_image init", IMG_GetError());
	}

	if (TTF_Init() == -1) {
		throw Exception("SDL_ttf init", TTF_GetError());
	}
}

/// Shutdown each of the SDL subsystems.
static void ShutdownApp() {
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();
}

#ifdef _WIN32
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
#else
int main(int argc, char** argv) {
#endif
	srand(static_cast<unsigned int>(time(nullptr)));

	try {
		InitApp();
		App().Run();
	}
	catch (Exception &ex) {
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
			"Adventures in SDL2", ex.what(), NULL);

		std::cerr << ex.what() << std::endl;

		return 1;
	}

	ShutdownApp();

	return 0;
}
<|endoftext|>


<commit_before>#include <tclap/CmdLine.h>
#include <llvm/IR/Module.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#include <llvm/Support/TargetSelect.h>

#include "utils/util.hpp"
#include "utils/error.hpp"
#include "lexer.hpp"
#include "parser/tokenParser.hpp"
#include "llvm/globalTypes.hpp"
#include "llvm/compiler.hpp"
#include "interpreter/interpreter.hpp"

int main(int argc, const char* argv[]) {
  try {
    TCLAP::CmdLine cmd("test-lang", ' ', "pre-release");

    TCLAP::SwitchArg printTokens("", "tokens", "Print token list", cmd);
    TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd);
    TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd);

    TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd);
    TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd);

    std::vector<std::string> runnerValues {"llvm-lli", "llvm-llc", "tree-walk"};
    TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);
    TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "llvm-lli", &runnerConstraint, cmd);

    TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", true, std::string(), "string", cmd);
    cmd.parse(argc, argv);

    auto lx = Lexer();
    lx.tokenize(code.getValue());
    if (printTokens.getValue()) for (auto tok : lx.getTokens()) println(tok);

    if (doNotParse.getValue()) return 0;
    auto px = TokenParser();
    px.parse(lx.getTokens());
    if (printAST.getValue()) px.getTree().print();

    if (doNotRun.getValue()) return 0;

    if (runner.getValue() == "tree-walk") {
      auto in = TreeWalkInterpreter();
      in.interpret(px.getTree());
      return 0;
    }

    CompileVisitor::Link v = CompileVisitor::create(globalContext, "Command Line Module", px.getTree());
    v->visit();
    if (printIR.getValue()) v->getModule()->dump();

    if (runner.getValue() == "llvm-lli") {
      llvm::InitializeNativeTarget();
      llvm::InitializeNativeTargetAsmPrinter();
      llvm::InitializeNativeTargetAsmParser();

      std::string onError = "";
      auto eb = new llvm::EngineBuilder(v->getModule());
      llvm::ExecutionEngine* ee = eb
        ->setEngineKind(llvm::EngineKind::Interpreter)
        .setErrorStr(&onError)
        .create();
      auto main = v->getEntryPoint();
      if (onError != "") throw InternalError("ExecutionEngine error", {
        METADATA_PAIRS,
        {"supplied error string", onError}
      });
      return ee->runFunctionAsMain(main, {}, {});
    } else if (runner.getValue() == "llvm-llc") {
      println("Not yet implemented!");
      // TODO
    }
  } catch (TCLAP::ArgException& arg) {
    std::cerr << "TCLAP error " << arg.error() << " for " << arg.argId() << std::endl;
  }
  return 0;
}
<commit_msg>Improved error handling in main<commit_after>#include <tclap/CmdLine.h>
#include <llvm/IR/Module.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#include <llvm/Support/TargetSelect.h>

#include "utils/util.hpp"
#include "utils/error.hpp"
#include "lexer.hpp"
#include "parser/tokenParser.hpp"
#include "llvm/globalTypes.hpp"
#include "llvm/compiler.hpp"
#include "interpreter/interpreter.hpp"

enum ExitCodes: int {
  NORMAL_EXIT = 0, // Everything is OK
  TCLAP_ERROR = 11, // TCLAP did something bad, should not happen
  CLI_ERROR = 1, // The user is retar-- uh I mean the user used a wrong option
  USER_PROGRAM_ERROR = 2, // The thing we had to lex/parse/run has an issue
  INTERNAL_ERROR = 3 // Unrecoverable error in this program, almost always a bug
};

int main(int argc, const char* argv[]) {
  try {
    TCLAP::CmdLine cmd("test-lang", ' ', "pre-release");

    TCLAP::SwitchArg printTokens("", "tokens", "Print token list", cmd);
    TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd);
    TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd);

    TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd);
    TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd);

    std::vector<std::string> runnerValues {"llvm-lli", "llvm-llc", "tree-walk"};
    TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);
    TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "llvm-lli", &runnerConstraint, cmd);

    TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false, std::string(), "string", cmd);
    TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file", false, std::string(), "path", cmd);
    cmd.parse(argc, argv);

    if (code.getValue().empty() && filePath.getValue().empty()) {
      TCLAP::ArgException arg("Must specify either option -e or -f");
      cmd.getOutput()->failure(cmd, arg);
    }

    auto lx = Lexer();
    lx.tokenize(code.getValue());
    if (printTokens.getValue()) for (auto tok : lx.getTokens()) println(tok);

    if (doNotParse.getValue()) return NORMAL_EXIT;
    auto px = TokenParser();
    px.parse(lx.getTokens());
    if (printAST.getValue()) px.getTree().print();

    if (doNotRun.getValue()) return NORMAL_EXIT;

    if (runner.getValue() == "tree-walk") {
      auto in = TreeWalkInterpreter();
      in.interpret(px.getTree());
      return NORMAL_EXIT;
    }

    CompileVisitor::Link v = CompileVisitor::create(globalContext, "Command Line Module", px.getTree());
    v->visit();
    if (printIR.getValue()) v->getModule()->dump();

    if (runner.getValue() == "llvm-lli") {
      llvm::InitializeNativeTarget();
      llvm::InitializeNativeTargetAsmPrinter();
      llvm::InitializeNativeTargetAsmParser();

      std::string onError = "";
      auto eb = new llvm::EngineBuilder(v->getModule());
      llvm::ExecutionEngine* ee = eb
        ->setEngineKind(llvm::EngineKind::Interpreter)
        .setErrorStr(&onError)
        .create();
      auto main = v->getEntryPoint();
      if (onError != "") throw InternalError("ExecutionEngine error", {
        METADATA_PAIRS,
        {"supplied error string", onError}
      });
      return ee->runFunctionAsMain(main, {}, {});
    } else if (runner.getValue() == "llvm-llc") {
      println("Not yet implemented!");
      // TODO
    }
  } catch (const TCLAP::ExitException& arg) {
    return CLI_ERROR;
  } catch (const TCLAP::ArgException& arg) {
    println("TCLAP error", arg.error(), "for", arg.argId());
    return TCLAP_ERROR;
  } catch (const Error& err) {
    println(err.what());
    return USER_PROGRAM_ERROR;
  } catch (const InternalError& err) {
    println(err.what());
    return INTERNAL_ERROR;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <memory>

#include <unistd.h>

#include "glload/gl_3_2.h"
#include "glload/gll.hpp"
#include <GL/glfw.h>

#include "config/globals.hpp"

#include "scene/scenemanager.hpp"
#include "scene/perspectivecamera.hpp"
#include "scene/scenegroup.hpp"

#include "sceneitems/genericplanet.hpp"

//HACK for stupid C-functions. Need to edit GLFW-source
scene::PerspectiveCamera* cameraPtr;

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

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, config::globals::multiSamples);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwOpenWindow(config::globals::initialWidth, config::globals::initialHeight, 8, 8, 8, 8, 24, 24, GLFW_WINDOW);
	glfwSetWindowTitle("Awesome planetary simulation demo");

	//Load OpenGL functions
	if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) {
		return 1;
	}

	//Enable depth test
	glEnable(GL_DEPTH_TEST);

	//Backface culling
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_CULL_FACE);

	//Set clear colour to black
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	//Define world
	scene::SceneGroup* world = new scene::SceneGroup;
	cameraPtr = new scene::PerspectiveCamera(world);
	scene::SceneManager sceneManager(cameraPtr, world);

	cameraPtr->changeCameraPosition(glm::vec3(20.0f, 0.0f, 150.0f), glm::vec3(0.0f, 0.0f, -1.0f));
	cameraPtr->rescale(config::globals::initialWidth, config::globals::initialHeight);

	//TODO Hack support for lambda's in GLFW
	glfwSetWindowSizeCallback([](int width, int height) {
		cameraPtr->rescale(width, height);
	});

	cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED);

	glfwSetKeyCallback([](int key, int action) {
		switch(key) {
		case GLFW_KEY_UP:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_DOWN:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::DOWN_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_LEFT:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::LEFT_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_RIGHT:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::RIGHT_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'W':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::W_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'A':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::A_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'S':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::S_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'D':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::D_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_PAGEUP:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEUP_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_PAGEDOWN:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEDOWN_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		}
	});

	scene::SceneItem* planeta = new sceneitems::GenericPlanet(glm::vec3(0.0f, 0.0f, 0.0f), 16.0f);
	scene::SceneItem* planetb = new sceneitems::GenericPlanet(glm::vec3(150.0f, 0.0f, -12.0f), 16.0f);
	scene::SceneItem* planetc = new sceneitems::GenericPlanet(glm::vec3(-35.0f, 45.0f, 0.0f), 20.0f);
	scene::SceneItem* planetd = new sceneitems::GenericPlanet(glm::vec3(0.0f, -45.0f, 30.0f), 5.0f);

	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planeta));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetb));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetc));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetd));

	//Start main render loop
	sceneManager.startSceneLoop();
}
<commit_msg>Remove odd start movement<commit_after>#include <memory>

#include <unistd.h>

#include "glload/gl_3_2.h"
#include "glload/gll.hpp"
#include <GL/glfw.h>

#include "config/globals.hpp"

#include "scene/scenemanager.hpp"
#include "scene/perspectivecamera.hpp"
#include "scene/scenegroup.hpp"

#include "sceneitems/genericplanet.hpp"

//HACK for stupid C-functions. Need to edit GLFW-source
scene::PerspectiveCamera* cameraPtr;

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

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, config::globals::multiSamples);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwOpenWindow(config::globals::initialWidth, config::globals::initialHeight, 8, 8, 8, 8, 24, 24, GLFW_WINDOW);
	glfwSetWindowTitle("Awesome planetary simulation demo");

	//Load OpenGL functions
	if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) {
		return 1;
	}

	//Enable depth test
	glEnable(GL_DEPTH_TEST);

	//Backface culling
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glEnable(GL_CULL_FACE);

	//Set clear colour to black
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	//Define world
	scene::SceneGroup* world = new scene::SceneGroup;
	cameraPtr = new scene::PerspectiveCamera(world);
	scene::SceneManager sceneManager(cameraPtr, world);

	cameraPtr->changeCameraPosition(glm::vec3(20.0f, 0.0f, 150.0f), glm::vec3(0.0f, 0.0f, -1.0f));
	cameraPtr->rescale(config::globals::initialWidth, config::globals::initialHeight);

	//TODO Hack support for lambda's in GLFW
	glfwSetWindowSizeCallback([](int width, int height) {
		cameraPtr->rescale(width, height);
	});

	glfwSetKeyCallback([](int key, int action) {
		switch(key) {
		case GLFW_KEY_UP:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_DOWN:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::DOWN_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_LEFT:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::LEFT_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_RIGHT:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::RIGHT_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'W':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::W_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'A':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::A_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'S':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::S_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case 'D':
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::D_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_PAGEUP:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEUP_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		case GLFW_KEY_PAGEDOWN:
			if(action == GLFW_PRESS) {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEDOWN_KEY_PRESSED);
			} else {
				cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED);
			}
			break;
		}
	});

	scene::SceneItem* planeta = new sceneitems::GenericPlanet(glm::vec3(0.0f, 0.0f, 0.0f), 16.0f);
	scene::SceneItem* planetb = new sceneitems::GenericPlanet(glm::vec3(150.0f, 0.0f, -12.0f), 16.0f);
	scene::SceneItem* planetc = new sceneitems::GenericPlanet(glm::vec3(-35.0f, 45.0f, 0.0f), 20.0f);
	scene::SceneItem* planetd = new sceneitems::GenericPlanet(glm::vec3(0.0f, -45.0f, 30.0f), 5.0f);

	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planeta));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetb));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetc));
	sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetd));

	//Start main render loop
	sceneManager.startSceneLoop();
}
<|endoftext|>


<commit_before>/* main.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 */

#include <algorithm>
#include <cassert>
#include <chrono>
#include <ctime>
#include <future>
#include <iostream>
#include <thread>

#include "algorithm/algorithm.hpp"
#include "individual/individual.hpp"
#include "problem/problem.hpp"
#include "random_generator/random_generator.hpp"

int main() {
  using individual::Individual;
  using namespace problem;
  const Problem problem{get_data(), 64, 128, 3, 3};
  const int trials = 16;
  int trial = 0;
  const unsigned long hardware_threads = std::thread::hardware_concurrency();
  const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2;
  assert(trials % blocks == 0);
  std::vector<Individual> candidates;
  std::chrono::time_point<std::chrono::system_clock> start, end;
  // begin timing trials
  std::time_t time = std::time(nullptr);
  start = std::chrono::system_clock::now();
  // spawn trials number of threads in blocks
  for (unsigned long t = 0; t < trials / blocks; ++t) {
    std::vector<std::future<const Individual>> results;
    for (unsigned long i = 0; i < blocks; ++i)
      results.emplace_back(std::async(std::launch::async, algorithm::genetic, problem, time, ++trial));
    // gather results
    for (std::future<const Individual> & result : results)
      candidates.emplace_back(result.get());
  }
  // end timing trials
  end = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = end - start;
  const Individual best = *std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness);
  std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n"
	    << "Average time: " << elapsed_seconds.count() / trials << "s\n"
	    << best.print();
}
<commit_msg>Outputting which trial was best<commit_after>/* main.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 */

#include <algorithm>
#include <cassert>
#include <chrono>
#include <ctime>
#include <future>
#include <iostream>
#include <thread>

#include "algorithm/algorithm.hpp"
#include "individual/individual.hpp"
#include "problem/problem.hpp"
#include "random_generator/random_generator.hpp"

int main() {
  using individual::Individual;
  using namespace problem;
  const Problem problem{get_data(), 64, 128, 3, 3};
  const int trials = 16;
  int trial = 0;
  const unsigned long hardware_threads = std::thread::hardware_concurrency();
  const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2;
  assert(trials % blocks == 0);
  std::vector<Individual> candidates;
  std::chrono::time_point<std::chrono::system_clock> start, end;
  // begin timing trials
  std::time_t time = std::time(nullptr);
  start = std::chrono::system_clock::now();
  // spawn trials number of threads in blocks
  for (unsigned long t = 0; t < trials / blocks; ++t) {
    std::vector<std::future<const Individual>> results;
    for (unsigned long i = 0; i < blocks; ++i)
      results.emplace_back(std::async(std::launch::async, algorithm::genetic, problem, time, ++trial));
    // gather results
    for (std::future<const Individual> & result : results)
      candidates.emplace_back(result.get());
  }
  // end timing trials
  end = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = end - start;
  std::vector<Individual>::iterator best = std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness);
  std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n"
	    << "Average time: " << elapsed_seconds.count() / trials << "s\n"
	    << "Best trial: " << time << "_"
	    << std::distance(candidates.begin(), best) + 1 << "\n"
	    << best->print();
}
<|endoftext|>