void PropertyLinkSubList::Restore(Base::XMLReader &reader)
{
    // read my element
    reader.readElement("LinkSubList");
    // get the value of my attribute
    int count = reader.getAttributeAsInteger("count");

    std::vector<DocumentObject*> values;
    values.reserve(count);
    std::vector<std::string> SubNames;
    SubNames.reserve(count);
    for (int i = 0; i < count; i++) {
        reader.readElement("Link");
        std::string name = reader.getAttribute("obj");
        // In order to do copy/paste it must be allowed to have defined some
        // referenced objects in XML which do not exist anymore in the new
        // document. Thus, we should silently ignore this.
        // Property not in an object!
        DocumentObject* father = static_cast<DocumentObject*>(getContainer());
        App::Document* document = father->getDocument();
        DocumentObject* child = document ? document->getObject(name.c_str()) : 0;
        if (child)
            values.push_back(child);
        else if (reader.isVerbose())
            Base::Console().Warning("Lost link to '%s' while loading, maybe "
                                    "an object was not loaded correctly\n",name.c_str());
        std::string subName = reader.getAttribute("sub");
        SubNames.push_back(subName);
    }

    reader.readEndElement("LinkSubList");

    // assignment
    setValues(values,SubNames);
}
void PropertyLinkSub::Restore(Base::XMLReader &reader)
{
    // read my element
    reader.readElement("LinkSub");
    // get the values of my attributes
    std::string name = reader.getAttribute("value");
    int count = reader.getAttributeAsInteger("count");

    // Property not in a DocumentObject!
    assert(getContainer()->getTypeId().isDerivedFrom(App::DocumentObject::getClassTypeId()) );

    std::vector<std::string> values(count);
    for (int i = 0; i < count; i++) {
        reader.readElement("Sub");
        values[i] = reader.getAttribute("value");
    }

    reader.readEndElement("LinkSub");

    DocumentObject *pcObject;
    if (!name.empty()) {
        App::Document* document = static_cast<DocumentObject*>(getContainer())->getDocument();
        pcObject = document ? document->getObject(name.c_str()) : 0;
        if (!pcObject) {
            if (reader.isVerbose()) {
                Base::Console().Warning("Lost link to '%s' while loading, maybe "
                                        "an object was not loaded correctly\n",name.c_str());
            }
        }
        setValue(pcObject,values);
    }
    else {
       setValue(0);
    }
}
void PropertyLink::Restore(Base::XMLReader &reader)
{
    // read my element
    reader.readElement("Link");
    // get the value of my attribute
    std::string name = reader.getAttribute("value");

    // Property not in a DocumentObject!
    assert(getContainer()->getTypeId().isDerivedFrom(App::DocumentObject::getClassTypeId()) );

    if (name != "") {
        DocumentObject* parent = static_cast<DocumentObject*>(getContainer());

        App::Document* document = parent->getDocument();
        DocumentObject* object = document ? document->getObject(name.c_str()) : 0;
        if (!object) {
            if (reader.isVerbose()) {
                Base::Console().Warning("Lost link to '%s' while loading, maybe "
                                        "an object was not loaded correctly\n",name.c_str());
            }
        }
        else if (parent == object) {
            if (reader.isVerbose()) {
                Base::Console().Warning("Object '%s' links to itself, nullify it\n",name.c_str());
            }
            object = 0;
        }

        setValue(object);
    }
    else {
        setValue(0);
    }
}
Beispiel #4
0
void DlgFilletEdges::on_shapeObject_activated(int index)
{
    d->object = 0;
    QStandardItemModel *model = qobject_cast<QStandardItemModel*>(ui->treeView->model());
    model->removeRows(0, model->rowCount());

    QByteArray name = ui->shapeObject->itemData(index).toByteArray();
    App::Document* doc = App::GetApplication().getActiveDocument();
    if (!doc)
        return;
    App::DocumentObject* part = doc->getObject((const char*)name);
    if (part && part->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
        d->object = part;
        TopoDS_Shape myShape = static_cast<Part::Feature*>(part)->Shape.getValue();
        // build up map edge->face
        TopTools_IndexedDataMapOfShapeListOfShape edge2Face;
        TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, edge2Face);
        TopTools_IndexedMapOfShape mapOfShape;
        TopExp::MapShapes(myShape, TopAbs_EDGE, mapOfShape);

        // populate the model
        d->edge_ids.clear();
        for (int i=1; i<= edge2Face.Extent(); ++i) {
            // set the index value as user data to use it in accept()
            const TopTools_ListOfShape& los = edge2Face.FindFromIndex(i);
            if (los.Extent() == 2) {
                // set the index value as user data to use it in accept()
                const TopoDS_Shape& edge = edge2Face.FindKey(i);
                // Now check also the continuity to only allow C0-continious
                // faces
                const TopoDS_Shape& face1 = los.First();
                const TopoDS_Shape& face2 = los.Last();
                GeomAbs_Shape cont = BRep_Tool::Continuity(TopoDS::Edge(edge),
                                                           TopoDS::Face(face1),
                                                           TopoDS::Face(face2));
                if (cont == GeomAbs_C0) {
                    int id = mapOfShape.FindIndex(edge);
                    d->edge_ids.push_back(id);
                }
            }
        }

        model->insertRows(0, d->edge_ids.size());
        int index = 0;
        for (std::vector<int>::iterator it = d->edge_ids.begin(); it != d->edge_ids.end(); ++it) {
            model->setData(model->index(index, 0), QVariant(tr("Edge%1").arg(*it)));
            model->setData(model->index(index, 0), QVariant(*it), Qt::UserRole);
            model->setData(model->index(index, 1), QVariant(QLocale::system().toString(1.0,'f',2)));
            model->setData(model->index(index, 2), QVariant(QLocale::system().toString(1.0,'f',2)));
            std::stringstream element;
            element << "Edge" << *it;
            if (Gui::Selection().isSelected(part, element.str().c_str()))
                model->setData(model->index(index, 0), Qt::Checked, Qt::CheckStateRole);
            else
                model->setData(model->index(index, 0), Qt::Unchecked, Qt::CheckStateRole);
            index++;
        }
    }
}
Beispiel #5
0
App::DocumentObject * SelectionObject::getObject(void) 
{
    if (!DocName.empty()) {
        App::Document *doc = App::GetApplication().getDocument(DocName.c_str());
        if (doc && !FeatName.empty())
            return doc->getObject(FeatName.c_str());
    }
    return 0;
}
Beispiel #6
0
void ProfileBased::Restore(Base::XMLReader& reader) {
   
    reader.readElement("Properties");
    int Cnt = reader.getAttributeAsInteger("Count");

    for (int i=0 ;i<Cnt ;i++) {
        reader.readElement("Property");
        const char* PropName = reader.getAttribute("name");
        const char* TypeName = reader.getAttribute("type");
        App::Property* prop = getPropertyByName(PropName);
        // NOTE: We must also check the type of the current property because a
        // subclass of PropertyContainer might change the type of a property but
        // not its name. In this case we would force to read-in a wrong property
        // type and the behaviour would be undefined.
        try {
            //check if we load the old sketch property
            if(!prop && (strcmp("Sketch", PropName) == 0) && (strcmp("App::PropertyLink", TypeName) == 0)) {
                
                std::vector<std::string> vec;
                // read my element
                reader.readElement("Link");
                // get the value of my attribute
                std::string name = reader.getAttribute("value");

                if (name != "") {                    
                    App::Document* document = getDocument();
                    DocumentObject* object = document ? document->getObject(name.c_str()) : 0;
                    Profile.setValue(object, vec);
                }
                else {
                    Profile.setValue(0, vec);
                }
            }
            else if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0)
                prop->Restore(reader);
        }
        catch (const Base::XMLParseException&) {
            throw; // re-throw
        }
        catch (const Base::Exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const std::exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const char* e) {
            Base::Console().Error("%s\n", e);
        }

        reader.readEndElement("Property");
    }
    reader.readEndElement("Properties");
}
bool TaskDlgPathCompound::accept()
{
    std::vector<App::DocumentObject*> paths;
    Path::FeatureCompound* pcCompound = static_cast<Path::FeatureCompound*>(CompoundView->getObject());
    App::Document* pcDoc = static_cast<App::Document*>(pcCompound->getDocument());
    std::vector<std::string> names = parameter->getList();
    for(std::size_t i = 0; i < names.size(); i++)
    {
        App::DocumentObject* pcPath = static_cast<App::DocumentObject*>(pcDoc->getObject(names[i].c_str()));
        paths.push_back(pcPath);
    }
    pcCompound->Group.setValues(paths);
    Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
    return true;
}
Beispiel #8
0
std::vector<App::DocumentObject*> DlgExtrusion::getShapesToExtrude() const
{
    QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems();
    App::Document* doc = App::GetApplication().getDocument(this->document.c_str());
    if (!doc)
        throw Base::RuntimeError("Document lost");

    std::vector<App::DocumentObject*> objects;
    for (int i = 0; i < items.size(); i++) {
        App::DocumentObject* obj = doc->getObject(items[i]->data(0, Qt::UserRole).toString().toLatin1());
        if (!obj)
            throw Base::RuntimeError("Object not found");
        objects.push_back(obj);
    }
    return objects;
}
Beispiel #9
0
void CmdSketcherMergeSketches::activated(int iMsg)
{
    std::vector<Gui::SelectionObject> selection = getSelection().getSelectionEx(0, Sketcher::SketchObject::getClassTypeId());
    if (selection.size() < 2) {
        QMessageBox::warning(Gui::getMainWindow(),
                             qApp->translate("CmdSketcherMergeSketches", "Wrong selection"),
                             qApp->translate("CmdSketcherMergeSketches", "Select at least two sketches, please."));
        return;
    }

    App::Document* doc = App::GetApplication().getActiveDocument();

    // create Sketch 
    std::string FeatName = getUniqueObjectName("Sketch");

    openCommand("Create a merge Sketch");
    doCommand(Doc,"App.activeDocument().addObject('Sketcher::SketchObject','%s')",FeatName.c_str());

    Sketcher::SketchObject* mergesketch = static_cast<Sketcher::SketchObject*>(doc->getObject(FeatName.c_str()));

    int baseGeometry=0;
    int baseConstraints=0;

    for (std::vector<Gui::SelectionObject>::const_iterator it=selection.begin(); it != selection.end(); ++it) {
        const Sketcher::SketchObject* Obj = static_cast<const Sketcher::SketchObject*>((*it).getObject());
        int addedGeometries=mergesketch->addGeometry(Obj->getInternalGeometry());

        int addedConstraints=mergesketch->addConstraints(Obj->Constraints.getValues());

        for(int i=0; i<=(addedConstraints-baseConstraints); i++){
            Sketcher::Constraint * constraint= mergesketch->Constraints.getValues()[i+baseConstraints];

            if(constraint->First!=Sketcher::Constraint::GeoUndef || constraint->First==-1 || constraint->First==-2) // not x, y axes or origin
                constraint->First+=baseGeometry;
            if(constraint->Second!=Sketcher::Constraint::GeoUndef || constraint->Second==-1 || constraint->Second==-2) // not x, y axes or origin
                constraint->Second+=baseGeometry;
            if(constraint->Third!=Sketcher::Constraint::GeoUndef || constraint->Third==-1 || constraint->Third==-2) // not x, y axes or origin
                constraint->Third+=baseGeometry;
        }

        baseGeometry=addedGeometries+1;
        baseConstraints=addedConstraints+1;
    }

    doCommand(Gui,"App.activeDocument().recompute()");
}
Beispiel #10
0
void DrawingView::closeEvent(QCloseEvent* ev)
{
    MDIView::closeEvent(ev);
    if (!ev->isAccepted())
        return;

    // when closing the view from GUI notify the view provider to mark it invisible
    if (_pcDocument && !m_objectName.empty()) {
        App::Document* doc = _pcDocument->getDocument();
        if (doc) {
            App::DocumentObject* obj = doc->getObject(m_objectName.c_str());
            Gui::ViewProvider* vp = _pcDocument->getViewProvider(obj);
            if (vp)
                vp->hide();
        }
    }
}
void MDIViewPage::updateDrawing(bool forceUpdate)
{
    // get all the DrawViews for this page, including the second level ones
    // if we ever have collections of collections, we'll need to revisit this
    std::vector<App::DocumentObject*> pChildren  = m_vpPage->getDrawPage()->Views.getValues();
    std::vector<App::DocumentObject*> appendChildren;
    for (auto& pc: pChildren) {
        if(pc->getTypeId().isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId())) {
            TechDraw::DrawViewCollection *collect = dynamic_cast<TechDraw::DrawViewCollection *>(pc);
            std::vector<App::DocumentObject*> cChildren = collect->Views.getValues();
            appendChildren.insert(std::end(appendChildren), std::begin(cChildren), std::end(cChildren));
        }
    }
    pChildren.insert(std::end(pChildren),std::begin(appendChildren),std::end(appendChildren));

    // if dv doesn't have a graphic, make one
    for (auto& dv: pChildren) {
        if (dv->isRemoving()) {
            continue;
        }
        QGIView* qv = m_view->findQViewForDocObj(dv);
        if (qv == nullptr) {
            attachView(dv);
        }
    }
    
    // if qView doesn't have a Feature, delete it
    std::vector<QGIView*> qvs = m_view->getViews();
    App::Document* doc = getAppDocument();
    for (auto& qv: qvs) {
        App::DocumentObject* obj = doc->getObject(qv->getViewName());
        if (obj == nullptr) {
            m_view->removeQView(qv);
        }
    }
    
    // Update all the QGIVxxxx
    const std::vector<QGIView *> &upviews = m_view->getViews();
    for(std::vector<QGIView *>::const_iterator it = upviews.begin(); it != upviews.end(); ++it) {
        if((*it)->getViewObject()->isTouched() ||
           forceUpdate) {
            (*it)->updateView(forceUpdate);
        }
    }
}
Beispiel #12
0
//this is time consuming. should only be used when there is a problem.
//should have been called MDIViewPage::fixWidowAndOrphans()
//void MDIViewPage::updateDrawing(bool forceUpdate)
void MDIViewPage::updateDrawing(void)
{
    // get all the DrawViews for this page, including the second level ones
    // if we ever have collections of collections, we'll need to revisit this
    DrawPage* thisPage = m_vpPage->getDrawPage();
    std::vector<App::DocumentObject*> pChildren  = thisPage->getAllViews();

    // if dv doesn't have a graphic, make one
    for (auto& dv: pChildren) {
        if (dv->isRemoving()) {
            continue;
        }
        QGIView* qv = m_view->findQViewForDocObj(dv);
        if (qv == nullptr) {
            attachView(dv);
        }
    }

    // if qView doesn't have a Feature on this Page, delete it
    std::vector<QGIView*> qvs = m_view->getViews();
    App::Document* doc = getAppDocument();
    for (auto& qv: qvs) {
        App::DocumentObject* obj = doc->getObject(qv->getViewName());
        if (obj == nullptr) {
            m_view->removeQView(qv);
        } else {
            DrawPage* pp = qv->getViewObject()->findParentPage();
            if (thisPage != pp) {
               m_view->removeQView(qv);
            }
        }
    }

    // Update all the QGIVxxxx
    // WF: why do we do this?  views should be keeping themselves up to date.
//    const std::vector<QGIView *> &upviews = m_view->getViews();
//    for(std::vector<QGIView *>::const_iterator it = upviews.begin(); it != upviews.end(); ++it) {
//        Base::Console().Message("TRACE - MDIVP::updateDrawing - updating a QGIVxxxx\n");
//        if((*it)->getViewObject()->isTouched() ||
//           forceUpdate) {
//            (*it)->updateView(forceUpdate);
//        }
//    }
}
Beispiel #13
0
void PropertyLinkList::Restore(Base::XMLReader &reader)
{
    // read my element
    reader.readElement("LinkList");
    // get the value of my attribute
    int count = reader.getAttributeAsInteger("count");
    App::PropertyContainer* container = getContainer();
    if (!container)
        throw Base::RuntimeError("Property is not part of a container");
    if (!container->getTypeId().isDerivedFrom(App::DocumentObject::getClassTypeId())) {
        std::stringstream str;
        str << "Container is not a document object ("
            << container->getTypeId().getName() << ")";
        throw Base::TypeError(str.str());
    }

    std::vector<DocumentObject*> values;
    values.reserve(count);
    for (int i = 0; i < count; i++) {
        reader.readElement("Link");
        std::string name = reader.getAttribute("value");
        // In order to do copy/paste it must be allowed to have defined some
        // referenced objects in XML which do not exist anymore in the new
        // document. Thus, we should silently ignore this.
        // Property not in an object!
        DocumentObject* father = static_cast<DocumentObject*>(getContainer());
        App::Document* document = father->getDocument();
        DocumentObject* child = document ? document->getObject(name.c_str()) : 0;
        if (child)
            values.push_back(child);
        else if (reader.isVerbose())
            Base::Console().Warning("Lost link to '%s' while loading, maybe "
            "an object was not loaded correctly\n", name.c_str());
    }

    reader.readEndElement("LinkList");

    // assignment
    setValues(values);
}
    Py::Object readResult(const Py::Tuple& args)
    {
        char* fileName = NULL;
        char* objName = NULL;

        if (!PyArg_ParseTuple(args.ptr(), "et|et","utf-8", &fileName, "utf-8", &objName))
            throw Py::Exception();
        std::string EncodedName = std::string(fileName);
        PyMem_Free(fileName);
        std::string resName = std::string(objName);
        PyMem_Free(objName);

        if (resName.length())
        {
            App::Document* pcDoc = App::GetApplication().getActiveDocument();
            App::DocumentObject* obj = pcDoc->getObject(resName.c_str());
            FemVTKTools::readResult(EncodedName.c_str(), obj);
        }
        else
            FemVTKTools::readResult(EncodedName.c_str());  // assuming activeObject can hold Result

        return Py::None();
    }
bool SelectionSingleton::setPreselect(const char* pDocName, const char* pObjectName, const char* pSubName, float x, float y, float z)
{
    static char buf[513];

    if (DocName != "")
        rmvPreselect();

    if (ActiveGate) {
        App::Document* pDoc = getDocument(pDocName);
        if (pDoc) {
            if (pObjectName) {
                App::DocumentObject* pObject = pDoc->getObject(pObjectName);
                if (!ActiveGate->allow(pDoc,pObject,pSubName)) {
                    snprintf(buf,512,"Not allowed: %s.%s.%s ",pDocName
                                                       ,pObjectName
                                                       ,pSubName
                                                       );

                    if (getMainWindow()) {
                        getMainWindow()->showMessage(QString::fromAscii(buf),3000);
                        Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
                        mdi->setOverrideCursor(QCursor(Qt::ForbiddenCursor));
                    }
                    return false;
                }

            }
            else
                return ActiveGate->allow(pDoc,0,0);
        }
        else
            return false;

    }

    DocName = pDocName;
    FeatName= pObjectName;
    SubName = pSubName;
    hx = x;
    hy = y;
    hz = z;

    // set up the change object
    SelectionChanges Chng;
    Chng.pDocName  = DocName.c_str();
    Chng.pObjectName = FeatName.c_str();
    Chng.pSubName  = SubName.c_str();
    Chng.x = x;
    Chng.y = y;
    Chng.z = z;
    Chng.Type = SelectionChanges::SetPreselect;

    // set the current preselection
    CurrentPreselection = Chng;

    snprintf(buf,512,"Preselected: %s.%s.%s (%f,%f,%f)",Chng.pDocName
                                                       ,Chng.pObjectName
                                                       ,Chng.pSubName
                                                       ,x,y,z);

    //FIXME: We shouldn't replace the possibly defined edit cursor
    //with the arrow cursor. But it seems that we don't even have to.
    //if (getMainWindow()){
    //    getMainWindow()->showMessage(QString::fromAscii(buf),3000);
    //    Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
    //    mdi->restoreOverrideCursor();
    //}

    Notify(Chng);
    signalSelectionChanged(Chng);

    //Base::Console().Log("Sel : Add preselect %s \n",pObjectName);

    // allows the preselection
    return true;
}
Beispiel #16
0
bool SelectionSingleton::setPreselect(const char* pDocName, const char* pObjectName, const char* pSubName, float x, float y, float z)
{
    if (DocName != "")
        rmvPreselect();

    if (ActiveGate) {
        // if document of object doesn't exist then return with false
        App::Document* pDoc = getDocument(pDocName);
        if (!pDoc || !pObjectName)
            return false;
        App::DocumentObject* pObject = pDoc->getObject(pObjectName);
        if (!pObject)
            return false;

        if (!ActiveGate->allow(pDoc,pObject,pSubName)) {
            QString msg;
            if (ActiveGate->notAllowedReason.length() > 0){
                msg = QObject::tr(ActiveGate->notAllowedReason.c_str());
            } else {
                msg = QCoreApplication::translate("SelectionFilter","Not allowed:");
            }
            msg.append(
                        QObject::tr(" %1.%2.%3 ")
                       .arg(QString::fromLatin1(pDocName))
                       .arg(QString::fromLatin1(pObjectName))
                       .arg(QString::fromLatin1(pSubName))
                        );

            if (getMainWindow()) {
                getMainWindow()->showMessage(msg);
                Gui::MDIView* mdi = Gui::Application::Instance->activeDocument()->getActiveView();
                mdi->setOverrideCursor(QCursor(Qt::ForbiddenCursor));
            }
            return false;
        }
    }

    DocName = pDocName;
    FeatName= pObjectName;
    SubName = pSubName;
    hx = x;
    hy = y;
    hz = z;

    // set up the change object
    SelectionChanges Chng;
    Chng.pDocName  = DocName.c_str();
    Chng.pObjectName = FeatName.c_str();
    Chng.pSubName  = SubName.c_str();
    Chng.pTypeName = "";
    Chng.x = x;
    Chng.y = y;
    Chng.z = z;
    Chng.Type = SelectionChanges::SetPreselect;

    // set the current preselection
    CurrentPreselection = Chng;

    Notify(Chng);
    signalSelectionChanged(Chng);

    // allows the preselection
    return true;
}
void SoFCUnifiedSelection::doAction(SoAction *action)
{
    if (action->getTypeId() == SoFCEnableHighlightAction::getClassTypeId()) {
        SoFCEnableHighlightAction *preaction = (SoFCEnableHighlightAction*)action;
        if (preaction->highlight) {
            this->highlightMode = SoFCUnifiedSelection::AUTO;
        }
        else {
            this->highlightMode = SoFCUnifiedSelection::OFF;
        }
    }

    if (action->getTypeId() == SoFCEnableSelectionAction::getClassTypeId()) {
        SoFCEnableSelectionAction *selaction = (SoFCEnableSelectionAction*)action;
        if (selaction->selection) {
            this->selectionMode = SoFCUnifiedSelection::ON;
        }
        else {
            this->selectionMode = SoFCUnifiedSelection::OFF;
        }
    }

    if (action->getTypeId() == SoFCSelectionColorAction::getClassTypeId()) {
        SoFCSelectionColorAction *colaction = (SoFCSelectionColorAction*)action;
        this->colorSelection = colaction->selectionColor;
    }

    if (action->getTypeId() == SoFCHighlightColorAction::getClassTypeId()) {
        SoFCHighlightColorAction *colaction = (SoFCHighlightColorAction*)action;
        this->colorHighlight = colaction->highlightColor;
    }

    if (selectionMode.getValue() == ON && action->getTypeId() == SoFCSelectionAction::getClassTypeId()) {
        SoFCSelectionAction *selaction = static_cast<SoFCSelectionAction*>(action);
        if (selaction->SelChange.Type == SelectionChanges::AddSelection || 
            selaction->SelChange.Type == SelectionChanges::RmvSelection) {
            // selection changes inside the 3d view are handled in handleEvent()
            if (!currenthighlight) {
                App::Document* doc = App::GetApplication().getDocument(selaction->SelChange.pDocName);
                App::DocumentObject* obj = doc->getObject(selaction->SelChange.pObjectName);
                ViewProvider*vp = Application::Instance->getViewProvider(obj);
                if (vp && vp->useNewSelectionModel() && vp->isSelectable()) {
                    SoDetail* detail = vp->getDetail(selaction->SelChange.pSubName);
                    SoSelectionElementAction::Type type = SoSelectionElementAction::None;
                    if (selaction->SelChange.Type == SelectionChanges::AddSelection) {
                        if (detail)
                            type = SoSelectionElementAction::Append;
                        else
                            type = SoSelectionElementAction::All;
                    }
                    else {
                        if (detail)
                            type = SoSelectionElementAction::Remove;
                        else
                            type = SoSelectionElementAction::None;
                    }

                    SoSelectionElementAction action(type);
                    action.setColor(this->colorSelection.getValue());
                    action.setElement(detail);
                    action.apply(vp->getRoot());
                    delete detail;
                }
            }
        }
        else if (selaction->SelChange.Type == SelectionChanges::ClrSelection ||
                 selaction->SelChange.Type == SelectionChanges::SetSelection) {
            std::vector<ViewProvider*> vps = this->viewer->getViewProvidersOfType
                (ViewProviderDocumentObject::getClassTypeId());
            for (std::vector<ViewProvider*>::iterator it = vps.begin(); it != vps.end(); ++it) {
                ViewProviderDocumentObject* vpd = static_cast<ViewProviderDocumentObject*>(*it);
                if (vpd->useNewSelectionModel()) {
                    if (Selection().isSelected(vpd->getObject()) && vpd->isSelectable()) {
                        SoSelectionElementAction action(SoSelectionElementAction::All);
                        action.setColor(this->colorSelection.getValue());
                        action.apply(vpd->getRoot());
                    }
                    else {
                        SoSelectionElementAction action(SoSelectionElementAction::None);
                        action.setColor(this->colorSelection.getValue());
                        action.apply(vpd->getRoot());
                    }
                }
            }
        }
    }

    inherited::doAction( action );
}
Beispiel #18
0
void DlgExtrusion::apply()
{
    if (ui->treeWidget->selectedItems().isEmpty()) {
        QMessageBox::critical(this, windowTitle(), 
            tr("Select a shape for extrusion, first."));
        return;
    }

    Gui::WaitCursor wc;
    App::Document* activeDoc = App::GetApplication().getDocument(this->document.c_str());
    if (!activeDoc) {
        QMessageBox::critical(this, windowTitle(), 
            tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(this->label.c_str())));
        return;
    }
    activeDoc->openTransaction("Extrude");

    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part");
    bool addBaseName = hGrp->GetBool("AddBaseObjectName", false);

    QString shape, type, name, label;
    QList<QTreeWidgetItem *> items = ui->treeWidget->selectedItems();
    for (QList<QTreeWidgetItem *>::iterator it = items.begin(); it != items.end(); ++it) {
        shape = (*it)->data(0, Qt::UserRole).toString();
        type = QString::fromLatin1("Part::Extrusion");
        if (addBaseName) {
            QString baseName = QString::fromLatin1("Extrude_%1").arg(shape);
            label = QString::fromLatin1("%1_Extrude").arg((*it)->text(0));
            name = QString::fromLatin1(activeDoc->getUniqueObjectName((const char*)baseName.toLatin1()).c_str());
        }
        else {
            name = QString::fromLatin1(activeDoc->getUniqueObjectName("Extrude").c_str());
            label = name;
        }

        double len = ui->dirLen->value();
        double dirX = ui->dirX->value();
        double dirY = ui->dirY->value();
        double dirZ = ui->dirZ->value();
        double angle = ui->taperAngle->value().getValue();
        bool makeSolid = ui->makeSolid->isChecked();

        // inspect geometry
        App::DocumentObject* obj = activeDoc->getObject((const char*)shape.toLatin1());
        if (!obj || !obj->isDerivedFrom(Part::Feature::getClassTypeId())) continue;
        Part::Feature* fea = static_cast<Part::Feature*>(obj);
        const TopoDS_Shape& data = fea->Shape.getValue();
        if (data.IsNull()) continue;

        // check for planes
        if (ui->checkNormal->isChecked() && data.ShapeType() == TopAbs_FACE) {
            BRepAdaptor_Surface adapt(TopoDS::Face(data));
            if (adapt.GetType() == GeomAbs_Plane) {
                double u = 0.5*(adapt.FirstUParameter() + adapt.LastUParameter());
                double v = 0.5*(adapt.FirstVParameter() + adapt.LastVParameter());
                BRepLProp_SLProps prop(adapt,u,v,1,Precision::Confusion());
                if (prop.IsNormalDefined()) {
                    gp_Pnt pnt; gp_Vec vec;
                    // handles the orientation state of the shape
                    BRepGProp_Face(TopoDS::Face(data)).Normal(u,v,pnt,vec);
                    dirX = vec.X();
                    dirY = vec.Y();
                    dirZ = vec.Z();
                }
            }
        }

        QString code = QString::fromLatin1(
            "FreeCAD.getDocument(\"%1\").addObject(\"%2\",\"%3\")\n"
            "FreeCAD.getDocument(\"%1\").%3.Base = FreeCAD.getDocument(\"%1\").%4\n"
            "FreeCAD.getDocument(\"%1\").%3.Dir = (%5,%6,%7)\n"
            "FreeCAD.getDocument(\"%1\").%3.Solid = (%8)\n"
            "FreeCAD.getDocument(\"%1\").%3.TaperAngle = (%9)\n"
            "FreeCADGui.getDocument(\"%1\").%4.Visibility = False\n"
            "FreeCAD.getDocument(\"%1\").%3.Label = '%10'\n")
            .arg(QString::fromLatin1(this->document.c_str()))
            .arg(type).arg(name).arg(shape)
            .arg(dirX*len)
            .arg(dirY*len)
            .arg(dirZ*len)
            .arg(makeSolid ? QLatin1String("True") : QLatin1String("False"))
            .arg(angle)
            .arg(label);
        Gui::Application::Instance->runPythonCode((const char*)code.toLatin1());
        QByteArray to = name.toLatin1();
        QByteArray from = shape.toLatin1();
        Gui::Command::copyVisual(to, "ShapeColor", from);
        Gui::Command::copyVisual(to, "LineColor", from);
        Gui::Command::copyVisual(to, "PointColor", from);
    }

    activeDoc->commitTransaction();
    try {
        ui->statusLabel->clear();
        activeDoc->recompute();
        ui->statusLabel->setText(QString::fromLatin1
            ("<span style=\" color:#55aa00;\">%1</span>").arg(tr("Succeeded")));
    }
    catch (const std::exception& e) {
        ui->statusLabel->setText(QString::fromLatin1
            ("<span style=\" color:#ff0000;\">%1</span>").arg(tr("Failed")));
        Base::Console().Error("%s\n", e.what());
    }
    catch (const Base::Exception& e) {
        ui->statusLabel->setText(QString::fromLatin1
            ("<span style=\" color:#ff0000;\">%1</span>").arg(tr("Failed")));
        Base::Console().Error("%s\n", e.what());
    }
    catch (...) {
        ui->statusLabel->setText(QString::fromLatin1
            ("<span style=\" color:#ff0000;\">%1</span>").arg(tr("Failed")));
        Base::Console().Error("General error in extrusion\n");
    }
}
/// @cond DOXERR
void SelectionView::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
                             Gui::SelectionSingleton::MessageType Reason)
{
    std::string temp;

    if (Reason.Type == SelectionChanges::AddSelection) {
        // insert the selection as item
        temp = Reason.pDocName;
        temp += ".";
        temp += Reason.pObjectName;
        if (Reason.pSubName[0] != 0 ) {
            temp += ".";
            temp += Reason.pSubName;
        }
        App::Document* doc = App::GetApplication().getDocument(Reason.pDocName);
        App::DocumentObject* obj = doc->getObject(Reason.pObjectName);
        temp += " (";
        temp += obj->Label.getValue();
        temp += ")";
        
        new QListWidgetItem(QString::fromAscii(temp.c_str()), selectionView);
    }
    else if (Reason.Type == SelectionChanges::ClrSelection) {
        // remove all items
        selectionView->clear();
    }
    else if (Reason.Type == SelectionChanges::RmvSelection) {
        // build name
        temp = Reason.pDocName;
        temp += ".";
        temp += Reason.pObjectName;
        if (Reason.pSubName[0] != 0) {
            temp += ".";
            temp += Reason.pSubName;
        }
        App::Document* doc = App::GetApplication().getDocument(Reason.pDocName);
        App::DocumentObject* obj = doc->getObject(Reason.pObjectName);
        temp += " (";
        temp += obj->Label.getValue();
        temp += ")";

        // remove all items
        QList<QListWidgetItem *> l = selectionView->findItems(QLatin1String(temp.c_str()),Qt::MatchExactly);
        if (l.size() == 1)
            delete l[0];

    }
    else if (Reason.Type == SelectionChanges::SetSelection) {
        // remove all items
        selectionView->clear();
        std::vector<SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(Reason.pDocName);
        for (std::vector<SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) {
            // build name
            temp = it->DocName;
            temp += ".";
            temp += it->FeatName;
            if (it->SubName && it->SubName[0] != '\0') {
                temp += ".";
                temp += it->SubName;
            }
            App::Document* doc = App::GetApplication().getDocument(it->DocName);
            App::DocumentObject* obj = doc->getObject(it->FeatName);
            temp += " (";
            temp += obj->Label.getValue();
            temp += ")";
            
            new QListWidgetItem(QString::fromAscii(temp.c_str()), selectionView);
        }
    }
}
Beispiel #20
0
void CmdSketcherMirrorSketch::activated(int iMsg)
{
    std::vector<Gui::SelectionObject> selection = getSelection().getSelectionEx(0, Sketcher::SketchObject::getClassTypeId());
    if (selection.size() < 1) {
        QMessageBox::warning(Gui::getMainWindow(),
            qApp->translate("CmdSketcherMirrorSketch", "Wrong selection"),
            qApp->translate("CmdSketcherMirrorSketch", "Select one or more sketches, please."));
        return;
    }
    
    // Ask the user which kind of mirroring he wants
    SketchMirrorDialog * smd = new SketchMirrorDialog();
    
    int refgeoid=-1;
    Sketcher::PointPos refposid=Sketcher::none;
    
    if( smd->exec() == QDialog::Accepted ){
        refgeoid=smd->RefGeoid;
        refposid=smd->RefPosid;
        
        delete smd;
    }
    else {
        delete smd;
        return;
    }
    
    App::Document* doc = App::GetApplication().getActiveDocument();
    
    openCommand("Create a mirror Sketch for each sketch");
    
    for (std::vector<Gui::SelectionObject>::const_iterator it=selection.begin(); it != selection.end(); ++it) {
        // create Sketch 
        std::string FeatName = getUniqueObjectName("MirroredSketch");
        
        doCommand(Doc,"App.activeDocument().addObject('Sketcher::SketchObject','%s')",FeatName.c_str());
        
        Sketcher::SketchObject* mirrorsketch = static_cast<Sketcher::SketchObject*>(doc->getObject(FeatName.c_str()));       
        
        const Sketcher::SketchObject* Obj = static_cast<const Sketcher::SketchObject*>((*it).getObject());
        
        Base::Placement pl = Obj->Placement.getValue();
        
        Base::Vector3d p = pl.getPosition();
        Base::Rotation r = pl.getRotation();
        
        doCommand(Doc,"App.activeDocument().%s.Placement = App.Placement(App.Vector(%f,%f,%f),App.Rotation(%f,%f,%f,%f))",
                  FeatName.c_str(),
                  p.x,p.y,p.z,r[0],r[1],r[2],r[3]);
        
        Sketcher::SketchObject* tempsketch = new Sketcher::SketchObject();
        
        int addedGeometries=tempsketch->addGeometry(Obj->getInternalGeometry());
        
        int addedConstraints=tempsketch->addConstraints(Obj->Constraints.getValues());

        std::vector<int> geoIdList;
        
        for(int i=0;i<=addedGeometries;i++)
            geoIdList.push_back(i);
        
        tempsketch->addSymmetric(geoIdList, refgeoid, refposid);
                
        std::vector<Part::Geometry *> tempgeo = tempsketch->getInternalGeometry();
        std::vector<Sketcher::Constraint *> tempconstr = tempsketch->Constraints.getValues();

        std::vector<Part::Geometry *> mirrorgeo (tempgeo.begin()+addedGeometries+1,tempgeo.end());
        std::vector<Sketcher::Constraint *> mirrorconstr (tempconstr.begin()+addedConstraints+1,tempconstr.end());
        
        for(std::vector<Sketcher::Constraint *>::const_iterator itc=mirrorconstr.begin(); itc != mirrorconstr.end(); ++itc) {
 
            if((*itc)->First!=Sketcher::Constraint::GeoUndef || (*itc)->First==-1 || (*itc)->First==-2) // not x, y axes or origin
                (*itc)->First-=(addedGeometries+1);
            if((*itc)->Second!=Sketcher::Constraint::GeoUndef || (*itc)->Second==-1 || (*itc)->Second==-2) // not x, y axes or origin
                (*itc)->Second-=(addedGeometries+1);
            if((*itc)->Third!=Sketcher::Constraint::GeoUndef || (*itc)->Third==-1 || (*itc)->Third==-2) // not x, y axes or origin
                (*itc)->Third-=(addedGeometries+1);
        }
        
        mirrorsketch->addGeometry(mirrorgeo);
        mirrorsketch->addConstraints(mirrorconstr);
        
        delete tempsketch;
    }
    
    doCommand(Gui,"App.activeDocument().recompute()");
    
}