void GoogleDocumentService::handleNetworkData(QNetworkReply *networkReply)
{
    if (!networkReply->error()) {
        if (!loggedin) {
            QString text(networkReply->readAll());
            text = text.right(text.length() - text.indexOf("Auth=") - 5);
            authToken = QString("GoogleLogin auth=") + text.left(text.indexOf("\n"));
            if(authToken.length() > 20) {
                if(!haveDocAuthToken) {
                    docAuthToken = authToken;
                    haveDocAuthToken = true;
                    qDebug() << "Received Doc token = " << docAuthToken;
                    clientLogin(this->username, this->password);
                    return;
                }
                spreadAuthToken = authToken;
                authToken = "";
                loggedin = true;
                qDebug() << "Received Spreadsheet token = " << spreadAuthToken;
                listDocuments();
                emit userAuthenticated(loggedin, "");
            }
        }
        else if (waitingForDoc) {
            QByteArray data = networkReply->readAll();
            QFile file(QDir::tempPath() + QLatin1Char('/') + documentList->currentDocument());
            file.open(QIODevice::ReadWrite);
            file.write(data);
            file.close();
            qDebug() << "Received Document!!!!! " << file.fileName();
            emit receivedDocument(file.fileName());
            waitingForDoc = false;
            showDocumentListWindow(false);
        }
        else {
            QByteArray bytAry = networkReply->readAll();
//            qDebug() << bytAry;

//            xmlInput.setData(networkReply->readAll());
            xmlInput.setData(bytAry);
            qDebug() << "Part received.........";
            if (newInformation) {
                emit progressUpdate("Parsing document list...");
                newInformation = xmlReader.parse(&xmlInput, true);
                qDebug() << "New Information = " << newInformation;
//                newInformation = false;
                getDocument();
            }
        }
    } else {
        QString errorString(networkReply->readAll());
        qDebug() << "Error occurred !!!!  " << errorString;
        errorString = errorString.right(errorString.length() - errorString.indexOf("Error=") - 6);
        if (!loggedin) {
            emit userAuthenticated(loggedin, errorString);
        } else {
            QMessageBox msgBox(QMessageBox::Information, i18n("Online Document Services"),
                               "Error occurred !!!!  " + errorString);
            msgBox.exec();
        }
    }
}
Ejemplo n.º 2
0
bool CmdPartDesignBody::isActive(void)
{
    return hasActiveDocument() && !PartDesignGui::isLegacyWorkflow ( getDocument () );
}
Ejemplo n.º 3
0
void CmdPartDesignMoveFeature::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    std::vector<App::DocumentObject*> features = getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
    if (features.empty()) return;

    // Check if all features are valid to move
    if (std::any_of(std::begin(features), std::end(features), [](App::DocumentObject* obj){return !PartDesignGui::isFeatureMovable(obj); }))
    {
        //show messagebox and cancel
        QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Features cannot be moved"),
            QObject::tr("Some of the selected features have dependencies in the source body"));
        return;
    }

    // Collect dependenies of the selected features
    std::vector<App::DocumentObject*> dependencies = PartDesignGui::collectMovableDependencies(features);
    if (!dependencies.empty())
        features.insert(std::end(features), std::begin(dependencies), std::end(dependencies));

    // Create a list of all bodies in this part
    std::vector<App::DocumentObject*> bodies = getDocument()->getObjectsOfType(Part::BodyBase::getClassTypeId());

    std::set<App::DocumentObject*> source_bodies;
    for (auto feat : features) {
        PartDesign::Body* source = PartDesign::Body::findBodyOf(feat);
        source_bodies.insert(static_cast<App::DocumentObject*>(source));
    }

    std::vector<App::DocumentObject*> target_bodies;
    for (auto body : bodies) {
        if (!source_bodies.count(body))
            target_bodies.push_back(body);
    }

    if (target_bodies.empty())
    {
        QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Features cannot be moved"),
            QObject::tr("There are no other bodies to move to"));
        return;
    }

    // Ask user to select the target body (remove source bodies from list)
    bool ok;
    QStringList items;
    for (auto body : target_bodies) {
        items.push_back(QString::fromUtf8(body->Label.getValue()));
    }
    QString text = QInputDialog::getItem(Gui::getMainWindow(),
        qApp->translate("PartDesign_MoveFeature", "Select body"),
        qApp->translate("PartDesign_MoveFeature", "Select a body from the list"),
        items, 0, false, &ok);
    if (!ok) return;
    int index = items.indexOf(text);
    if (index < 0) return;

    PartDesign::Body* target = static_cast<PartDesign::Body*>(target_bodies[index]);

    openCommand("Move an object");

    for (auto feat: features) {
        // Find body of this feature
        Part::BodyBase* source = PartDesign::Body::findBodyOf(feat);
        bool featureWasTip = false;

        if (source == target) continue;

        // Remove from the source body if the feature belonged to a body
        if (source) {
            featureWasTip = (source->Tip.getValue() == feat);
            doCommand(Doc,"App.activeDocument().%s.removeObject(App.activeDocument().%s)",
                      source->getNameInDocument(), (feat)->getNameInDocument());
        }

        App::DocumentObject* targetOldTip = target->Tip.getValue();

        // Add to target body (always at the Tip)
        doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",
                      target->getNameInDocument(), (feat)->getNameInDocument());
        // Recompute to update the shape
        doCommand(Gui,"App.activeDocument().recompute()");

        // Adjust visibility of features
        // TODO: May be something can be done in view provider (2015-08-05, Fat-Zer)
        // If we removed the tip of the source body, make the new tip visible
        if ( featureWasTip ) {
            App::DocumentObject * sourceNewTip = source->Tip.getValue();
            if (sourceNewTip)
                doCommand(Gui,"Gui.activeDocument().show(\"%s\")", sourceNewTip->getNameInDocument());
        }

        // Hide old tip and show new tip (the moved feature) of the target body
        App::DocumentObject* targetNewTip = target->Tip.getValue();
        if ( targetOldTip != targetNewTip ) {
            if ( targetOldTip ) {
                doCommand(Gui,"Gui.activeDocument().hide(\"%s\")", targetOldTip->getNameInDocument());
            }
            if (targetNewTip) {
                doCommand(Gui,"Gui.activeDocument().show(\"%s\")", targetNewTip->getNameInDocument());
            }
        }

        // Fix sketch support
        if (feat->getTypeId().isDerivedFrom(Sketcher::SketchObject::getClassTypeId())) {
            Sketcher::SketchObject *sketch = static_cast<Sketcher::SketchObject*>(feat);
            try {
                PartDesignGui::fixSketchSupport(sketch);
            } catch (Base::Exception &) {
                QMessageBox::warning( Gui::getMainWindow(), QObject::tr("Sketch plane cannot be migrated"),
                        QObject::tr("Please edit '%1' and redefine it to use a Base or Datum plane as the sketch plane.").
                        arg( QString::fromLatin1( sketch->Label.getValue () ) ) );
            }
        }

        //relink origin for sketches and datums (coordinates)
        PartDesignGui::relinkToOrigin(feat, target);
    }

    updateActive();
}
Ejemplo n.º 4
0
//==============================================================================
Rectangle<int> PaintElement::getCurrentBounds (const Rectangle<int>& parentArea) const
{
    return position.getRectangle (parentArea, getDocument()->getComponentLayout());
}
Ejemplo n.º 5
0
daeInt daeSTLDatabase::getElement(daeElement** pElement,daeInt index,daeString name,daeString type,daeString file)
{	
	// this sorts the vector if necessary
	validate(); 
	
	// If the index is out of range, there can be no match
	if ( index < 0 ) 
	{
		return DAE_ERR_QUERY_NO_MATCH;
	}

	// If no name, type or file was specified we return the element at "index" - SLOW
	if ( !name && !type && !file ) 
	{
		daeUInt count = 0;
		std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.begin();
		std::map< std::string, std::vector< daeElement*> >::iterator end = elements.end();
		while( iter != end )
		{
			count += (daeUInt)(*iter).second.size();
			if ( (daeInt)count > index )
			{
				*pElement = (*iter).second[index - (count - (*iter).second.size())] ;
				return DAE_OK;
			}
			++iter;
		}
		return DAE_ERR_QUERY_NO_MATCH;
	}
	
	if ( name ) 
	{ 
		//name specified
		int count = 0;
		if ( file ) 
		{ 
			// If a document URI was a search key (in file) resolve it to a text URI with no fragment
			daeURI tempURI(file,true);
			daeDocument *col = getDocument( tempURI.getURI() );
			if ( col == NULL ) {
				*pElement = NULL;
				return DAE_ERR_QUERY_NO_MATCH;
			}
			//a document was specified
			std::pair< std::multimap< std::string, daeElement* >::iterator, std::multimap< std::string, daeElement* >::iterator> range;
			range = elementsIDMap.equal_range( std::string( name ) );
			std::multimap< std::string, daeElement* >::iterator i = range.first;
			while ( i != range.second )
			{
				if ( col == (*i).second->getDocument() )
				{
					if ( count == index )
					{
						*pElement = (*i).second;
						return DAE_OK;
					}
					count++;
				}
				++i;
			}
			*pElement = NULL;
			return DAE_ERR_QUERY_NO_MATCH;
		}
		else 
		{ 
			//no document specified
			std::multimap< std::string, daeElement* >::iterator i = elementsIDMap.find( std::string( name ) );
			if ( index > (daeInt)elementsIDMap.count( std::string( name ) ) || i == elementsIDMap.end() )
			{
				*pElement = NULL;
				return DAE_ERR_QUERY_NO_MATCH;
			}
			for ( int x = 0; x < index; x++ )
			{
				++i;
			}
			*pElement = i->second;
			return DAE_OK;
		}
	}
	
	if ( type ) 
	{ 
		std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.find( std::string( type ) );
		if ( iter == elements.end() )
		{
			*pElement = NULL;
			return DAE_ERR_QUERY_NO_MATCH;
		}
		//type specified
		int count = 0;
		if ( file ) 
		{ 
			// If a document URI was a search key (in file) resolve it to a text URI with no fragment
			daeURI tempURI(file,true);
			daeDocument *col = getDocument( tempURI.getURI() );
			if ( col == NULL ) {
				return DAE_ERR_QUERY_NO_MATCH;
			}
			//a document was specified
			// a document was specified
			std::vector< daeElement* > &vec = (*iter).second;
			std::vector< daeElement* >::iterator i = vec.begin();
			std::vector< daeElement* >::iterator end = vec.end();
			while( i != end )
			{
				if ( col == (*i)->getDocument() )
				{
					if ( count == index )
					{
						*pElement = (*i);
						return DAE_OK;
					}
					++count;
				}
				++i;
			}
			return DAE_ERR_QUERY_NO_MATCH;
		}
		else 
		{ 
			//no document specified
			if ( index >= (daeInt)(*iter).second.size() )
			{
				*pElement = NULL;
				return DAE_ERR_QUERY_NO_MATCH;
			}
			*pElement = (*iter).second[index];
			return DAE_OK;
		}
	}

	//if you get here only the file was specified - SLOW
	daeURI tempURI(file,true);
	daeDocument *col = getDocument( tempURI.getURI() );
	if ( col == NULL ) {
		return DAE_ERR_QUERY_NO_MATCH;
	}
	//a document was specified
	int count = 0;
	std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.begin();
	std::map< std::string, std::vector< daeElement*> >::iterator end = elements.end();
	while( iter != end )
	{
		std::vector< daeElement* > &vec = (*iter).second;
		std::vector< daeElement* >::iterator i = vec.begin();
		std::vector< daeElement* >::iterator end2 = vec.end();
		while( i != end2 )
		{
			if( col == (*i)->getDocument() ) 
			{
				if( count == index ) 
				{
					*pElement = (*i);
					return DAE_OK;
				}
				++count;
			}
			++i;
		}
		++iter;
	}
	return DAE_ERR_QUERY_NO_MATCH;

}
Ejemplo n.º 6
0
QPair<QVariant, RPropertyAttributes> RBlockReferenceEntity::getProperty(
        RPropertyTypeId& propertyTypeId,
        bool humanReadable, bool noAttributes) {

    if (propertyTypeId == PropertyPositionX) {
        return qMakePair(QVariant(data.position.x), RPropertyAttributes());
    } else if (propertyTypeId == PropertyPositionY) {
        return qMakePair(QVariant(data.position.y), RPropertyAttributes());
    } else if (propertyTypeId == PropertyPositionZ) {
        return qMakePair(QVariant(data.position.z), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleX) {
        return qMakePair(QVariant(data.scaleFactors.x), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleY) {
        return qMakePair(QVariant(data.scaleFactors.y), RPropertyAttributes());
    } else if (propertyTypeId == PropertyScaleZ) {
        return qMakePair(QVariant(data.scaleFactors.z), RPropertyAttributes());
    } else if (propertyTypeId == PropertyRotation) {
        return qMakePair(QVariant(data.rotation), 
            RPropertyAttributes(RPropertyAttributes::Angle));
    } else if (propertyTypeId == PropertyReferencedBlock) {
        if (humanReadable) {
            RDocument* document = getData().getDocument();
            if (document != NULL) {
                RPropertyAttributes attr;
                // TODO
                if (!noAttributes) {
                    QSet<QString> blockNames = document->getBlockNames();
                    QSet<QString> filtered;
                    QSet<QString>::iterator it;
                    for (it=blockNames.begin(); it!=blockNames.end(); it++) {
                        if (!(*it).startsWith("*")) {
                            filtered.insert(*it);
                        }
                    }
                    attr.setChoices(filtered);
                }
                return qMakePair(QVariant(document->getBlockName(
                        getData().getReferencedBlockId())), attr);
            }
        } else {
            return qMakePair(QVariant(getData().getReferencedBlockId()),
                    RPropertyAttributes());
        }
    }
    else if (propertyTypeId.isCustom()) {
        if (propertyTypeId.getCustomPropertyTitle()=="Attributes") {
            QString tag = propertyTypeId.getCustomPropertyName();

            const RDocument* doc = getDocument();
            if (doc!=NULL) {
                QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
                QSet<REntity::Id>::iterator it;
                for (it=childIds.begin(); it!=childIds.end(); it++) {
                    REntity::Id childId = *it;
                    QSharedPointer<REntity> child = doc->queryEntityDirect(childId);
                    if (child.isNull()) {
                        continue;
                    }

                    QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
                    QSet<RPropertyTypeId>::iterator it2;
                    for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
                        RPropertyTypeId pid = *it2;
                        QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
                        if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
                            //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
                            return qMakePair(QVariant(p.first), RPropertyAttributes());
                        }
                    }
                }
            }

            //document->queryChildEntities(getId());

            //return qMakePair(QVariant("Dummy"), RPropertyAttributes());
        }
    }

    return REntity::getProperty(propertyTypeId, humanReadable, noAttributes);
}
Ejemplo n.º 7
0
void RExporter::exportBlock(RBlock::Id blockId) {
    QSharedPointer<RBlock> block = getDocument().queryBlock(blockId);
    if (block.isNull() || !block->isFrozen()) {
        exportBlock(*block);
    }
}
Ejemplo n.º 8
0
    void SerializedCAS::print(ostream & os) const {

      os << "===============================" << endl;
      os << "Document:" << endl;
      os << getDocument() << endl;

      os << endl << "===============================" << endl;
      os << "Type Inheritance: " << endl;
      vector<TyNum> const & typeInh = getTypeInheritanceTable();
      printVector(os, typeInh);

      os << "Type Symbol Table: " << endl;
      printVector(os, getTypeSymbolTable());

      os << "Feature Definition: " << endl;
      printVector(os, getFeatureDefinitionTable());

      os << "Feature Symbol Table: " << endl;
      printVector(os, getFeatureSymbolTable());

      os << "Feature offsets:" << endl;
      printVector(os, getFeatureOffsetTable());

      os << "Index IDs:" << endl;
      printVector(os, getIndexIDTable() );

      os << "Comparator start:" << endl;
      printVector(os, getComparatorStartTable() );

      os << "Comparatordefinition:" << endl;
      printVector(os, getComparatorDefinitionTable());

      os << "IndexKind:" << endl;
      printVector(os, getIndexKindTable());


      os << endl << "===============================" << endl;
      os << "Serialized Heap:" << endl;
      vector<TyNum> const & heap = getFSHeapArray();
      size_t i;
      for (i=0; i<heap.size(); ++i) {
        os << i  << ": " << heap[i] << endl;
      }

      os << endl << "===============================" << endl;
      os << "Serialized ByteHeap:" << endl;
      vector<char> const & bheap = getByteHeapArray();

      for (i=0; i<bheap.size(); ++i) {
        os << i  << ": " << bheap[i] << endl;
      }

      os << endl << "===============================" << endl;
      os << "Serialized ShortHeap:" << endl;
      vector<short> const & sheap = getShortHeapArray();

      for (i=0; i<sheap.size(); ++i) {
        os << i  << ": " << sheap[i] << endl;
      }
      os << endl << "===============================" << endl;
      os << "Serialized LongHeap:" << endl;
      vector<INT64> const & lheap = getLongHeapArray();

      for (i=0; i<lheap.size(); ++i) {
        os << i  << ": " << lheap[i] << endl;
      }

      os << endl << "===============================" << endl;
      os << "Serialized String table:" << endl;
      vector<UnicodeStringRef> const & strings =  getStringSymbolTable();
      for (i=0; i<strings.size(); ++i) {
        os << i << ": " << strings[i] << endl;
      }

      os << endl << "===============================" << endl;
      os << "Indexed FSs:" << endl;
      vector<TyNum> const & indexedFSs = getIndexedFSs();
      for (i=0; i<indexedFSs.size(); ++i) {
        os << i << ": " << indexedFSs[i] << endl;
      }
    }
Ejemplo n.º 9
0
/**
 * Determines the number of lines contained in the area.
 *
 * @return the number of lines > 0
 */
/*public*/ int getLineCount() {
    Element map = getDocument().getDefaultRootElement();
    return map.getElementCount();
}
Ejemplo n.º 10
0
void QEditor::removeSelection(TypeSel sel_type) {
	getDocument()->removeSelection((int) sel_type);
   repaintChanged();
}
Ejemplo n.º 11
0
bool pt_PieceTable::_realInsertStrux(PT_DocPosition dpos,
									 PTStruxType pts,
									 const gchar ** attributes,
									 const gchar ** properties,
									 pf_Frag_Strux ** ppfs_ret)
{
	// insert a new structure fragment at the given document position.
	// this function can only be called while editing the document.
	// Also can specify an indexAP to be used for the frag rather
	// than that obtained by default. Very useful for insertting
	// Cells where you can immediately specify the cell position in
	// a table.  this function can only be called while editing the
	// document.

	UT_return_val_if_fail (m_pts==PTS_Editing, false);

	// get the fragment at the doc postion containing the given
	// document position.

	pf_Frag * pf = NULL;
	PT_BlockOffset fragOffset = 0;
	bool bFoundFrag = getFragFromPosition(dpos,&pf,&fragOffset);
	UT_return_val_if_fail (bFoundFrag, false);

	// get the strux containing the given position.

	pf_Frag_Strux * pfsContainer = NULL;
	bool bFoundContainer = _getStruxFromPosition(dpos,&pfsContainer);
	UT_return_val_if_fail (bFoundContainer,false);
	//
	// Can only insert an endTOC into a TOC
	//
	if((pfsContainer->getStruxType() == PTX_SectionTOC) && (pts != PTX_EndTOC))
	{
		bFoundContainer = _getStruxFromPosition(pfsContainer->getPos(),&pfsContainer);
		dpos--;
	}
	if(isEndFootnote(pfsContainer))
	{
		bFoundContainer = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
	}
	// if we are inserting something similar to the previous strux,
	// we will clone the attributes/properties; we assume that the
	// new strux should have the same AP as the one which preceeds us.
	// This is generally true for inserting a paragraph -- it should
	// inherit the style of the one we just broke.

	PT_AttrPropIndex indexAP = 0;
	if (pfsContainer->getStruxType() == pts)
	{
		// TODO paul, add code here to see if this strux has a "followed-by"
		// TODO paul, property (or property in the style) and get the a/p
		// TODO paul, from there rather than just taking the attr/prop
		// TODO paul, of the previous strux.
		indexAP = pfsContainer->getIndexAP();
	}

//
// Look to see if we're in the middle of a hyperlink span now.
//
	pf_Frag * pHype = _findPrevHyperlink(pf);
	if(pHype != NULL && (pts != PTX_SectionFrame) // allow annotations in
	                                              // hyperlinks
	   && (pts != PTX_SectionAnnotation)
	   && (pts != PTX_EndAnnotation)) // frames are always placed
		                                           // at the end of blocks
                                                   // so we don't need this 
	{
//
// We have an open hyperlink! FIXME later we should allow this by terminating
// the hyperlink span just before this strux, then doing the insert strux.
// Instead for now we'll just disallow this insertStrux.
//
// This assert is to remind use to write the code to terminate
// the hyperlink.
//
		pf_Frag * pEndHype = _findNextHyperlink(pf);
		PT_DocPosition posEnd = 0;
		if(pEndHype)
		{
			posEnd = pEndHype->getPos();
		}
		//
		// OK now insert a new end of hyperlink at pf
		//
		insertObject(dpos, PTO_Hyperlink,NULL,NULL);
		m_fragments.cleanFrags();
		dpos++;
		if(posEnd > 0)
		{
			//
			// Now delete the old endhyperlink.
			//
			pf_Frag * pfEnd = NULL;
			UT_uint32 newOff = 0;
			posEnd++; // from the insert
			UT_uint32 offset = 0;
			_deleteObjectWithNotify(posEnd,
									static_cast<pf_Frag_Object*>(pEndHype),
									offset,1,pfsContainer,&pfEnd,&newOff,true);
		}
		m_fragments.cleanFrags();
		bFoundFrag = getFragFromPosition(dpos,&pf,&fragOffset);
		UT_return_val_if_fail (bFoundFrag, false);
	}	

//
// If desired, merge in the specified attributes/properties. This
// enables cells to inherit the properties of the block from which
// they were inserted.
//
	if (attributes || properties)
	{
		PT_AttrPropIndex pAPIold = indexAP;
		bool bMerged = m_varset.mergeAP(PTC_AddFmt,pAPIold,attributes,properties,&indexAP,getDocument());
        UT_UNUSED(bMerged);
		UT_ASSERT_HARMLESS(bMerged);
	}

	pf_Frag_Strux * pfsNew = NULL;
	if (!_createStrux(pts,indexAP,&pfsNew))
		return false;

	pfsNew->setXID(getXID());
	
	// when inserting paragraphs, we try to remember the current
	// span formatting active at the insertion point and add a
	// FmtMark immediately after the block.  this way, if the
	// user keeps typing text, the FmtMark will control it's
	// attr/prop -- if the user warps away and/or edits elsewhere
	// and then comes back to this point (the FmtMark may or may
	// not still be here) new text will either use the FmtMark or
	// look to the right.

	bool bNeedGlob = false;
	PT_AttrPropIndex apFmtMark = 0;
	if (pfsNew->getStruxType() == PTX_Block)
	{
		bNeedGlob = _computeFmtMarkForNewBlock(pfsNew,pf,fragOffset,&apFmtMark);
		if (bNeedGlob)
			beginMultiStepGlob();

		// if we are leaving an empty block (are stealing all it's content) we should
		// put a FmtMark in it to remember the active span fmt at the time.
		// this lets things like hitting two consecutive CR's and then comming
		// back to the first empty paragraph behave as expected.

		// fixme sevior here

		if ((pf->getType()==pf_Frag::PFT_Text) && (fragOffset == 0) &&
			(pf->getPrev()!=NULL) && (pf->getPrev()->getType()==pf_Frag::PFT_Strux))
		{
			pf_Frag_Strux *pfsStrux = static_cast<pf_Frag_Strux *>(pf->getPrev());
			if(pfsStrux->getStruxType() == PTX_Block)
			{
				_insertFmtMarkAfterBlockWithNotify(pfsContainer,dpos,apFmtMark);
			}
		}
	}
	//
	// Look if we're placing an endcell in an empty block. If so, 
	// insert a format mark
	//
	if (pfsNew->getStruxType() == PTX_EndCell)
	{
		if((pf->getPrev()!=NULL) && (pf->getPrev()->getType()==pf_Frag::PFT_Strux))
		{
			pf_Frag_Strux *pfsStrux = static_cast<pf_Frag_Strux *>(pf->getPrev());
			if(pfsStrux->getStruxType() == PTX_Block)
			{
				_insertFmtMarkAfterBlockWithNotify(pfsContainer,dpos,apFmtMark);
			}
		}
	}

	// insert this frag into the fragment list. Update the container strux as needed
	_insertStrux(pf,fragOffset,pfsNew);
	if (ppfs_ret)
		*ppfs_ret = pfsNew;

	// create a change record to describe the change, add
	// it to the history, and let our listeners know about it.
	if(pfsNew->getStruxType() == PTX_SectionFrame)
	{
		// Inserting a sectionFrame screws up dos. It goes just before the next
		// block strux found.
		dpos = pfsNew->getPrev()->getPos() + pfsNew->getPrev()->getLength();
	}
	PX_ChangeRecord_Strux * pcrs
		= new PX_ChangeRecord_Strux(PX_ChangeRecord::PXT_InsertStrux,
									dpos,indexAP,pfsNew->getXID(), pts);
	UT_return_val_if_fail (pcrs,false);

	// add record to history.  we do not attempt to coalesce these.
	m_history.addChangeRecord(pcrs);
	m_pDocument->notifyListeners(pfsContainer,pfsNew,pcrs);

	if (bNeedGlob)
	{
		UT_return_val_if_fail (!pfsNew->getNext() || pfsNew->getNext()->getType()!=pf_Frag::PFT_FmtMark, false);
		_insertFmtMarkAfterBlockWithNotify(pfsNew,dpos+pfsNew->getLength(),apFmtMark);
		endMultiStepGlob();
	}

	return true;
}
Ejemplo n.º 12
0
QEditorIndenter* QEditor::indenter() const
{
  return dynamic_cast<QEditorIndenter*>( getDocument()->indent() );
}
Ejemplo n.º 13
0
QSourceColorizer* QEditor::colorizer() const
{
    return dynamic_cast<QSourceColorizer*>( getDocument()->preProcessor() );
}
Ejemplo n.º 14
0
    /**
     * Modifiers
     */
    __INLINE void
    ElementRef::addAttr (AttributeRef& attr)
    {
#if PARANOID
        AssertBug ( &document == &(attr.document), "AttributeRef and ElementRef do not have the same document !\n" );
        AssertBug ( attr.getParentElementPtr() == NullPtr || attr.getParentElementPtr() == getElementPtr(),
                "AttributeRef already added to another ElementRef \n" );
        AssertBug ( attr.getAttributePtr() != NullPtr, "AttributeRef not defined !\n" );
#endif
        for (AttributeRef myAttr = getFirstAttr(); myAttr; myAttr = myAttr.getNext())
        {
            if (myAttr.getKeyId() == attr.getKeyId() && myAttr.getAttributeType() == attr.getAttributeType())
            {
                NotImplemented("Duplicate attributes : key=%x:%s, type=%x, attribute=%s\n", myAttr.getKeyId(),
                               myAttr.getKey().c_str(), myAttr.getAttributeType(),
                               myAttr.generateVersatileXPath().c_str());
            }
        }
        ElementSegment* me = getMe<Write>();
        __checkElementFlag_HasAttributesAndChildren(me->flags);

        if (attr.getAttributeType() == AttributeType_NamespaceAlias && !(me->flags & ElementFlag_HasNamespaceAlias))
        {
            getDocumentAllocator().alter(me);
            me->flags |= ElementFlag_HasNamespaceAlias;
            getDocumentAllocator().protect(me);
        }

        SegmentPtr nextAttrPtr = NullPtr;
        if (me->attributesAndChildren.attrPtr == NullPtr)
        {
            getDocumentAllocator().alter(me);
            me->attributesAndChildren.attrPtr = attr.getAttributePtr();
            getDocumentAllocator().protect(me);
        }
        else
        {
            SegmentPtr lastAttrPtr = me->attributesAndChildren.attrPtr;
            AttributeSegment* lastAttrSeg = getDocumentAllocator().getSegment<AttributeSegment, Read>(lastAttrPtr);
            while (lastAttrSeg->nextPtr != NullPtr)
            {
                lastAttrPtr = lastAttrSeg->nextPtr;
                lastAttrSeg = getDocumentAllocator().getSegment<AttributeSegment, Read>(lastAttrPtr);
            }
            getDocumentAllocator().authorizeWrite(lastAttrPtr, lastAttrSeg);
            getDocumentAllocator().alter(lastAttrSeg);
            lastAttrSeg->nextPtr = attr.getAttributePtr();
            getDocumentAllocator().protect(lastAttrSeg);
        }
        AttributeSegment * attrSeg = getDocumentAllocator().getSegment<AttributeSegment, Read>(attr.getAttributePtr());
        getDocumentAllocator().alter(attrSeg);
        attrSeg->nextPtr = nextAttrPtr;
        getDocumentAllocator().protect(attrSeg);
        attr.setParentElementPtr(getElementPtr());

        Log_Element ( "Added attr on elementRef=%llx:%x (%llx, ref at %p), attr=%x (elt=%llx,attr=%llx, ref at %p)\n",
                getElementId(), getKeyId(), getElementPtr(), this,
                attr.getKeyId(), attr.getParentElementPtr(), attr.getAttributePtr(), &attr );
        if (attr.isBaseType())
        {
            getDocument().appendJournal(*this, JournalOperation_UpdateAttribute, *this, attr.getKeyId());
        }
    }
Ejemplo n.º 15
0
bool pt_PieceTable::_realChangeSpanFmt(PTChangeFmt ptc,
									   PT_DocPosition dpos1,
									   PT_DocPosition dpos2,
									   const gchar ** attributes,
									   const gchar ** properties,
									   bool bRevisionDelete)
{
	// apply a span-level formatting change to the given region.

	UT_return_val_if_fail (m_pts==PTS_Editing,false);
    _tweakFieldSpan(dpos1,dpos2);
//
// Deal with case of exactly selecting the endOfFootnote
//
	pf_Frag * pfEndDum = m_fragments.findFirstFragBeforePos(dpos2);
	if(isEndFootnote(pfEndDum))
	{
		if(dpos2 > dpos1)
		{
			dpos2--;
		}
	}
//
// Deal with addStyle
//
	bool bApplyStyle = (PTC_AddStyle == ptc);
	const gchar ** sProps = NULL;
	const gchar ** lProps = properties;
	if(bApplyStyle)
	{
//
// OK for styles we expand out all defined properties including BasedOn styles
// Then we use these to eliminate any specfic properties in the current strux
// Then properties in the current strux will resolve to those defined in the
// style (they exist there) to specifc values in strux (if not overridden by
// the style) then finally to default value.
//
		const gchar * szStyle = UT_getAttribute(PT_STYLE_ATTRIBUTE_NAME,attributes);
		PD_Style * pStyle = NULL;
		UT_return_val_if_fail (szStyle,false);
		getDocument()->getStyle(szStyle,&pStyle);
		UT_return_val_if_fail (pStyle,false);
		UT_Vector vProps;
//
// Get the vector of properties
//
		pStyle->getAllProperties(&vProps,0);
//
// Finally make the const gchar * array of properties
//
		UT_uint32 countp = vProps.getItemCount() + 1;
		sProps = (const gchar **) UT_calloc(countp, sizeof(gchar *));
		countp--;
		UT_uint32 i;
		for(i=0; i<countp; i++)
		{
			sProps[i] = (const gchar *) vProps.getNthItem(i);
		}
		sProps[i] = NULL;
		lProps = sProps;
	}
	if (dpos1 == dpos2) 		// if length of change is zero, then we have a toggle format.
	{
		UT_uint32 startUndoPos = m_history.getUndoPos();
		bool bRes = _insertFmtMarkFragWithNotify(ptc,dpos1,attributes,lProps);
		UT_uint32 endUndoPos = m_history.getUndoPos();
		// Won't be a persistant change if it's just a toggle
		PX_ChangeRecord *pcr=0;
		m_history.getUndo(&pcr,true);
		if (pcr && (startUndoPos != endUndoPos) )
		{
			UT_DEBUGMSG(("Setting persistance of change to false\n"));
			pcr->setPersistance(false);
			m_history.setSavePosition(m_history.getSavePosition()+1);
		}
		if(bApplyStyle)
		{
			FREEP(sProps);
		}
		return bRes;
	}

	UT_return_val_if_fail (dpos1 < dpos2,false);
	bool bHaveAttributes, bHaveProperties;
	bHaveAttributes = (attributes && *attributes);
	bHaveProperties = (lProps && *lProps);

	pf_Frag * pf_First;
	pf_Frag * pf_End;
	PT_BlockOffset fragOffset_First;
	PT_BlockOffset fragOffset_End;

	bool bFound;
	bFound = getFragsFromPositions(dpos1,dpos2,&pf_First,&fragOffset_First,&pf_End,&fragOffset_End);
	UT_return_val_if_fail (bFound, false);

#if 0
	{
		pf_Frag * pf1, * pf2;
		PT_BlockOffset fo1, fo2;

		bool bFound1 = getFragFromPosition(dpos1,&pf1,&fo1);
		bool bFound2 = getFragFromPosition(dpos2,&pf2,&fo2);
		UT_return_val_if_fail (bFound1 && bFound2, false);
		UT_return_val_if_fail ((pf1==pf_First) && (fragOffset_First==fo1), false);
		UT_return_val_if_fail ((pf2==pf_End) && (fragOffset_End==fo2), false);
	}
#endif

	// see if the amount of text to be changed is completely
	// contained within a single fragment.  if so, we have a
	// simple change.  otherwise, we need to set up a multi-step
	// change -- it may not actually take more than one step,
	// but it is too complicated to tell at this point, so we
	// assume it will and don't worry about it.
	//
	// we are in a simple change if the beginning and end are
	// within the same fragment.

	// NOTE: if we call beginMultiStepGlob() we ***MUST*** call
	// NOTE: endMultiStepGlob() before we return -- otherwise,
	// NOTE: the undo/redo won't be properly bracketed.

	bool bSimple = (pf_First == pf_End);
	if (!bSimple)
		beginMultiStepGlob();

	pf_Frag_Strux * pfsContainer = NULL;
	pf_Frag * pfNewEnd;
	UT_uint32 fragOffsetNewEnd;

	UT_uint32 length = dpos2 - dpos1;
	while (length != 0)
	{
		// FIXME: Special check to support a FmtMark at the end of the
		// document. This is necessary because FmtMarks don't have a
		// length...  See bug 452.
		if (0 == length
			&& (!pf_First || pf_Frag::PFT_FmtMark != pf_First->getType()))
			break;

		UT_return_val_if_fail (dpos1+length==dpos2, false);

		UT_uint32 lengthInFrag = pf_First->getLength() - fragOffset_First;
		UT_uint32 lengthThisStep = UT_MIN(lengthInFrag, length);

		switch (pf_First->getType())
		{
		case pf_Frag::PFT_EndOfDoc:
		default:
			UT_DEBUGMSG(("fragment type: %d\n",pf_First->getType()));
			UT_ASSERT_HARMLESS(0);
			if(bApplyStyle)
			{
				FREEP(sProps);
			}
			return false;

		case pf_Frag::PFT_Strux:
			{
				// we are only applying span-level changes, so we ignore strux.
				// but we still need to update our loop indices.

				pfNewEnd = pf_First->getNext();
				fragOffsetNewEnd = 0;
				pfsContainer = static_cast<pf_Frag_Strux *> (pf_First);
				bool bFoundStrux = false;
				if(isEndFootnote(pfsContainer))
				{
					bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux, false);
				}
			}
			break;

		case pf_Frag::PFT_Text:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}
				}

				bool bResult;
				bResult	= _fmtChangeSpanWithNotify(ptc,static_cast<pf_Frag_Text *>(pf_First),
											   fragOffset_First,dpos1,lengthThisStep,
											   attributes,lProps,
											   pfsContainer,&pfNewEnd,&fragOffsetNewEnd,bRevisionDelete);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		case pf_Frag::PFT_Object:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}
				}

				bool bResult;
				bResult	= _fmtChangeObjectWithNotify(ptc,static_cast<pf_Frag_Object *>(pf_First),
												 fragOffset_First,dpos1,lengthThisStep,
												 attributes,lProps,
												 pfsContainer,&pfNewEnd,&fragOffsetNewEnd,false);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		case pf_Frag::PFT_FmtMark:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}

				}

				bool bResult;
				bResult = _fmtChangeFmtMarkWithNotify(ptc,static_cast<pf_Frag_FmtMark *>(pf_First),
												  dpos1, attributes,lProps,
												  pfsContainer,&pfNewEnd,&fragOffsetNewEnd);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		}

		dpos1 += lengthThisStep;
		length -= lengthThisStep;

		// since _fmtChange{Span,FmtMark,...}WithNotify(), can delete pf_First, mess with the
		// fragment list, and does some aggressive coalescing of
		// fragments, we cannot just do a pf_First->getNext() here.
		// to advance to the next fragment, we use the *NewEnd variables
		// that each of the cases routines gave us.

		pf_First = pfNewEnd;
		if (!pf_First)
			length = 0;
		fragOffset_First = fragOffsetNewEnd;
	}
	if(bApplyStyle)
	{
		FREEP(sProps);
	}

	if (!bSimple)
		endMultiStepGlob();

	return true;
}
Ejemplo n.º 16
0
/**
 * Testing function.
 */
void LC_SimpleTests::slotTestInsertBlock() {
	RS_DEBUG->print("%s\n: begin\n", __func__);
	auto appWin=QC_ApplicationWindow::getAppWindow();

	RS_Document* d = appWin->getDocument();
	if (d && d->rtti()==RS2::EntityGraphic) {
		RS_Graphic* graphic = (RS_Graphic*)d;
		if (graphic==NULL) {
			return;
		}

		graphic->addLayer(new RS_Layer("default"));
		RS_Block* block = new RS_Block(graphic, RS_BlockData("debugblock",
															 RS_Vector(0.0,0.0), true));

		RS_Line* line;
		RS_Arc* arc;
		RS_Circle* circle;

		// Add one red line:
		line = new RS_Line{block, {0.,0.}, {50.,0.}};
		line->setLayerToActive();
		line->setPen(RS_Pen(RS_Color(255, 0, 0),
							RS2::Width01,
							RS2::SolidLine));
		block->addEntity(line);

		// Add one line with attributes from block:
		line = new RS_Line{block, {50.,0.}, {50.,50.}};
		line->setPen(RS_Pen(RS_Color(RS2::FlagByBlock),
							RS2::WidthByBlock,
							RS2::LineByBlock));
		block->addEntity(line);

		// Add one arc with attributes from block:
		RS_ArcData d({50.,0.},
					 50.0, M_PI_2, M_PI,
					 false);
		arc = new RS_Arc(block, d);
		arc->setPen(RS_Pen(RS_Color(RS2::FlagByBlock),
						   RS2::WidthByBlock,
						   RS2::LineByBlock));
		block->addEntity(arc);

		// Add one blue circle:
		RS_CircleData circleData(RS_Vector(20.0,15.0),
								 12.5);
		circle = new RS_Circle(block, circleData);
		circle->setLayerToActive();
		circle->setPen(RS_Pen(RS_Color(0, 0, 255),
							  RS2::Width01,
							  RS2::SolidLine));
		block->addEntity(circle);


		graphic->addBlock(block);



		RS_Insert* ins;
		RS_InsertData insData("debugblock",
							  RS_Vector(0.0,0.0),
							  RS_Vector(1.0,1.0), 0.0,
							  1, 1, RS_Vector(0.0, 0.0),
							  NULL, RS2::NoUpdate);

		// insert one magenta instance of the block (original):
		ins = new RS_Insert(graphic, insData);
		ins->setLayerToActive();
		ins->setPen(RS_Pen(RS_Color(255, 0, 255),
						   RS2::Width02,
						   RS2::SolidLine));
		ins->update();
		graphic->addEntity(ins);

		// insert one green instance of the block (rotate):
		insData = RS_InsertData("debugblock",
								RS_Vector(-50.0,20.0),
								RS_Vector(1.0,1.0), M_PI/6.,
								1, 1, RS_Vector(0.0, 0.0),
								NULL, RS2::NoUpdate);
		ins = new RS_Insert(graphic, insData);
		ins->setLayerToActive();
		ins->setPen(RS_Pen(RS_Color(0, 255, 0),
						   RS2::Width02,
						   RS2::SolidLine));
		ins->update();
		graphic->addEntity(ins);

		// insert one cyan instance of the block (move):
		insData = RS_InsertData("debugblock",
								RS_Vector(10.0,20.0),
								RS_Vector(1.0,1.0), 0.0,
								1, 1, RS_Vector(0.0, 0.0),
								NULL, RS2::NoUpdate);
		ins = new RS_Insert(graphic, insData);
		ins->setLayerToActive();
		ins->setPen(RS_Pen(RS_Color(0, 255, 255),
						   RS2::Width02,
						   RS2::SolidLine));
		ins->update();
		graphic->addEntity(ins);

		// insert one blue instance of the block:
		for (double a=0.0; a<360.0; a+=45.0) {
			insData = RS_InsertData("debugblock",
									RS_Vector(60.0,0.0),
									RS_Vector(2.0/5,2.0/5), RS_Math::deg2rad(a),
									1, 1, RS_Vector(0.0, 0.0),
									NULL, RS2::NoUpdate);
			ins = new RS_Insert(graphic, insData);
			ins->setLayerToActive();
			ins->setPen(RS_Pen(RS_Color(0, 0, 255),
							   RS2::Width05,
							   RS2::SolidLine));
			ins->update();
			graphic->addEntity(ins);
		}

		// insert an array of yellow instances of the block:
		insData = RS_InsertData("debugblock",
								RS_Vector(-100.0,-100.0),
								RS_Vector(0.2,0.2), M_PI/6.0,
								6, 4, RS_Vector(100.0, 100.0),
								NULL, RS2::NoUpdate);
		ins = new RS_Insert(graphic, insData);
		ins->setLayerToActive();
		ins->setPen(RS_Pen(RS_Color(255, 255, 0),
						   RS2::Width01,
						   RS2::SolidLine));
		ins->update();
		graphic->addEntity(ins);


		RS_GraphicView* v = appWin->getGraphicView();
		if (v) {
			v->redraw();
		}
	}
	RS_DEBUG->print("%s\n: end\n", __func__);
}
Ejemplo n.º 17
0
bool RBlockReferenceEntity::setProperty(RPropertyTypeId propertyTypeId,
        const QVariant& value, RTransaction* transaction) {
    bool ret = REntity::setProperty(propertyTypeId, value, transaction);

//    if (propertyTypeId==PropertyPositionX) {
//        double d = value - data.position.x;
//        RObject::setMember(data.position.x, value);

//        const RDocument* doc = getDocument();
//        if (doc!=NULL) {
//            QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
//            QSet<REntity::Id>::iterator it;
//            for (it=childIds.begin(); it!=childIds.end(); it++) {
//                REntity::Id childId = *it;
//                QSharedPointer<REntity> child = doc->queryEntity(childId);
//                if (child.isNull()) {
//                    continue;
//                }

//                QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
//                QSet<RPropertyTypeId>::iterator it2;
//                for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
//                    RPropertyTypeId pid = *it2;
//                    QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
//                    if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
//                        //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
//                        //return qMakePair(QVariant(p.first), RPropertyAttributes());
//                        child->setProperty(pid, value.toString(), transaction);
//                        transaction->addObject(child);
//                    }
//                }
//            }
//        }
//    }

    ret = ret || RObject::setMember(data.position.x, value, PropertyPositionX == propertyTypeId);
    ret = ret || RObject::setMember(data.position.y, value, PropertyPositionY == propertyTypeId);
    ret = ret || RObject::setMember(data.position.z, value, PropertyPositionZ == propertyTypeId);

    ret = ret || RObject::setMember(data.scaleFactors.x, value, PropertyScaleX == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);
    ret = ret || RObject::setMember(data.scaleFactors.y, value, PropertyScaleY == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);
    ret = ret || RObject::setMember(data.scaleFactors.z, value, PropertyScaleZ == propertyTypeId && fabs(value.toDouble())>RS::PointTolerance);

    ret = ret || RObject::setMember(data.rotation, value, PropertyRotation == propertyTypeId);

    if (propertyTypeId == PropertyReferencedBlock) {
        if (value.type() == QVariant::Int ||
            value.type() == QVariant::LongLong) {

            ret = ret || RObject::setMember(
                getData().referencedBlockId, value.toInt(), true);
        } else if (value.type() == QVariant::String) {
            RDocument* document = getData().getDocument();
            if (document != NULL) {
                ret = ret || RObject::setMember(getData().referencedBlockId,
                        document->getBlockId(value.toString()), true);
            }
        }
    }

    // allow editing of attributes in the context of a block reference:
    if (transaction && propertyTypeId.isCustom()) {
        if (propertyTypeId.getCustomPropertyTitle()=="Attributes") {
            QString tag = propertyTypeId.getCustomPropertyName();

            const RDocument* doc = getDocument();
            if (doc!=NULL) {
                QSet<REntity::Id> childIds = doc->queryChildEntities(getId(), RS::EntityAttribute);
                QSet<REntity::Id>::iterator it;
                for (it=childIds.begin(); it!=childIds.end(); it++) {
                    REntity::Id childId = *it;
                    QSharedPointer<REntity> child = doc->queryEntity(childId);
                    if (child.isNull()) {
                        continue;
                    }

                    QSet<RPropertyTypeId> childProperties = child->getPropertyTypeIds();
                    QSet<RPropertyTypeId>::iterator it2;
                    for (it2=childProperties.begin(); it2!=childProperties.end(); it2++) {
                        RPropertyTypeId pid = *it2;
                        QPair<QVariant, RPropertyAttributes> p = child->getProperty(pid);
                        if (p.second.isVisibleToParent() && pid.getCustomPropertyName()==tag) {
                            //ret.insert(RPropertyTypeId(QT_TRANSLATE_NOOP("REntity", "Attributes"), p.first.toString()));
                            //return qMakePair(QVariant(p.first), RPropertyAttributes());
                            child->setProperty(pid, value.toString(), transaction);
                            transaction->addObject(child);
                        }
                    }
                }
            }
        }
    }

    if (ret) {
        data.update();
    }

    return ret;
}
Ejemplo n.º 18
0
/**
 * Testing function.
 */
void LC_SimpleTests::slotTestInsertEllipse() {
	RS_DEBUG->print("%s\n: begin\n", __func__);
	auto appWin=QC_ApplicationWindow::getAppWindow();

	RS_Document* d = appWin->getDocument();
	if (d) {
		RS_Graphic* graphic = (RS_Graphic*)d;
		if (!graphic) {
			return;
		}

		RS_Ellipse* ellipse;
		RS_Line* line;

		for (double a=0.; a<2.*M_PI; a+=0.1) {
			RS_Vector v = RS_Vector::polar(50., a);
			double xp = 1000.*a;

			ellipse = new RS_Ellipse(graphic,
			{xp,0.}, v,
									 0.5,
									 0., 2.*M_PI,
									 false);

			ellipse->setPen(RS_Pen(RS_Color(255, 0, 255),
								   RS2::Width01,
								   RS2::SolidLine));

			graphic->addEntity(ellipse);
			//graphic->addEntity(new RS_Point(graphic, ellipse->getMax()));
			//graphic->addEntity(new RS_Point(graphic, ellipse->getMin()));

			line = new RS_Line{graphic, {xp, 0.}, RS_Vector{xp, 0.}+v};
			line->setPen(RS_Pen(RS_Color(128, 128, 128),
								RS2::Width01,
								RS2::SolidLine));
			graphic->addEntity(line);


			/*
					 for (double mx=-60.0; mx<60.0; mx+=1.0) {
						 //for (double mx=0.0; mx<1.0; mx+=2.5) {
						 RS_VectorSolutions sol = ellipse->mapX(xp + mx);
						 //graphic->addEntity(new RS_Point(graphic,
						 //                   sol.vector2 + RS_Vector(a*500.0, 0.0)));
						 //graphic->addEntity(new RS_Point(graphic,
						 //                   sol.vector3 + RS_Vector(a*500.0, 0.0)));
						 //graphic->addEntity(new RS_Point(graphic,
						 //                   sol.vector4 + RS_Vector(a*500.0, 0.0)));

						 line = new RS_Line(graphic,
											RS_LineData(RS_Vector(xp+mx,-50.0),
														RS_Vector(xp+mx,50.0)));
						 line->setPen(RS_Pen(RS_Color(60, 60, 60),
											 RS2::Width01,
											 RS2::SolidLine));
						 graphic->addEntity(line);

						 graphic->addEntity(new RS_Point(graphic,
														 sol.get(0)));
					 }
			*/
		}


		// different minor/minor relations
		/*
			  double x, y;
			  for (y=-250.0; y<=250.0; y+=50.0) {
				  for (x=-250.0; x<=250.0; x+=50.0) {
					  RS_Vector v(x, y);

					  ellipse = new RS_Ellipse(graphic,
											   v,
											   RS_Vector((x/5+50.0)/2.0, 0.0),
										 fabs(x/y),
											   0.0, 2*M_PI,
											   false);

				ellipse->setPen(RS_Pen(RS_Color(255, 255, 0),
									   RS2::Width01,
									   RS2::DashDotLine));

					  graphic->addEntity(ellipse);
					  graphic->addEntity(new RS_Point(graphic, ellipse->getMax()));
					  graphic->addEntity(new RS_Point(graphic, ellipse->getMin()));

				ellipse = new RS_Ellipse(graphic,
											   v + RS_Vector(750.0, 0.0),
											   RS_Vector((x/5+50.0)/2.0, 0.0),
											   fabs(x/y),
											   2*M_PI, 0.0,
											   true);

					  graphic->addEntity(ellipse);
					  graphic->addEntity(new RS_Point(graphic, ellipse->getMax()));
					  graphic->addEntity(new RS_Point(graphic, ellipse->getMin()));
				  }
			  }
		*/

		/*
			  // different rotation angles:
			  double rot;
			  for (rot=0.0; rot<=2*M_PI+0.1; rot+=(M_PI/8)) {
				  ellipse = new RS_Ellipse(graphic,
										   RS_Vector(rot*200, 500.0),
										   RS_Vector(50.0, 0.0).rotate(rot),
										   0.3,
										   0.0, 2*M_PI,
										   false);
				  graphic->addEntity(ellipse);
				  graphic->addEntity(new RS_Point(graphic, ellipse->getMax()));
				  graphic->addEntity(new RS_Point(graphic, ellipse->getMin()));
			  }


			  // different arc angles:
			  double a1, a2;
			  for (rot=0.0; rot<=2*M_PI+0.1; rot+=(M_PI/8)) {
				  for (a1=0.0; a1<=2*M_PI+0.1; a1+=(M_PI/8)) {
					  for (a2=a1+M_PI/8; a2<=2*M_PI+a1+0.1; a2+=(M_PI/8)) {
						  ellipse = new RS_Ellipse(graphic,
												   RS_Vector(-500.0-a1*200.0-5000.0*rot,
															 500.0-a2*200.0),
												   RS_Vector(50.0, 0.0).rotate(rot),
												   0.3,
												   a1, a2,
												   false);
						  graphic->addEntity(ellipse);
						  graphic->addEntity(new RS_Point(graphic, ellipse->getMax()));
						  graphic->addEntity(new RS_Point(graphic, ellipse->getMin()));
					  }
				  }
			  }
		*/

		RS_GraphicView* v = appWin->getGraphicView();
		if (v) {
			v->redraw();
		}
	}
	RS_DEBUG->print("%s\n: end\n", __func__);
}
Ejemplo n.º 19
0
void RExporter::exportLayer(RLayer::Id layerId) {
    QSharedPointer<RLayer> layer = getDocument().queryLayer(layerId);
    if (layer.isNull() || !layer->isFrozen()) {
        exportLayer(*layer);
    }
}
Ejemplo n.º 20
0
int copyDocument(const TixiDocumentHandle oldTixiDocumentHandle, TixiDocumentHandle* newTixiDocumentHandle)
{
  TixiDocument* srcDocument = getDocument(oldTixiDocumentHandle);
  TixiDocument* dstDocument = NULL;
  xmlDocPtr xmlDocument = NULL;
  xmlNodePtr rootNode = NULL;

  if (!srcDocument) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Invalid document handle.\n");
    return FAILED;
  }

  /* make a deep copy of the document */
  xmlDocument = xmlCopyDoc(srcDocument->docPtr, 1);

  if (!xmlDocument) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Could not copy document.\n");
    return FAILED;
  }

  rootNode = xmlDocGetRootElement(xmlDocument);
  if (!rootNode) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Could not get root node in source document.\n");
    return EROROR_CREATE_ROOT_NODE;
  }

  dstDocument = (TixiDocument*) malloc(sizeof(TixiDocument));

  /* copy attributes from source document */
  if (srcDocument->xmlFilename != NULL) {
    dstDocument->xmlFilename = (char*) malloc(sizeof(char) * strlen(srcDocument->xmlFilename) + 1);
    strcpy(dstDocument->xmlFilename, srcDocument->xmlFilename);
  }
  else {
    dstDocument->xmlFilename = NULL;
  }

  if (srcDocument->dirname != NULL) {
    dstDocument->dirname = (char*) malloc(sizeof(char) * strlen(srcDocument->dirname) + 1);
    strcpy(dstDocument->dirname, srcDocument->dirname);
  }
  else {
    dstDocument->dirname = NULL;
  }

  if (srcDocument->filename != NULL) {
    dstDocument->filename = (char*) malloc(sizeof(char) * strlen(srcDocument->filename) + 1);
    strcpy(dstDocument->filename, srcDocument->filename);
  }
  else {
    dstDocument->filename = NULL;
  }

  if (srcDocument->validationFilename != NULL) {
    dstDocument->validationFilename = (char*) malloc(sizeof(char) * strlen(srcDocument->validationFilename) + 1);
    strcpy(dstDocument->validationFilename, srcDocument->validationFilename);
  }
  else {
    dstDocument->validationFilename = NULL;
  }

  dstDocument->docPtr = xmlDocument;
  dstDocument->currentNode = rootNode;
  dstDocument->isValid = srcDocument->isValid;
  dstDocument->status = srcDocument->status;
  dstDocument->memoryListHead = NULL;
  dstDocument->memoryListTail = NULL;
  dstDocument->uidListHead = NULL;
  dstDocument->hasIncludedExternalFiles = srcDocument->hasIncludedExternalFiles;
  dstDocument->usePrettyPrint = srcDocument->usePrettyPrint;

  if (addDocumentToList(dstDocument, &(dstDocument->handle)) != SUCESS) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Failed  adding document to document list.");
    return FAILED;
  }

  *newTixiDocumentHandle = dstDocument->handle;
  return SUCCESS;
}
Ejemplo n.º 21
0
void RExporter::exportView(RView::Id viewId) {
    QSharedPointer<RView> view = getDocument().queryView(viewId);
    if (view.isNull()) {
        exportView(*view);
    }
}
Ejemplo n.º 22
0
ReturnCode saveDocument (TixiDocumentHandle handle, const char* xmlFilename, InternalSaveMode saveMode)
{
  TixiDocument* document = getDocument(handle);
  TixiDocument* cpyDoc = NULL;
  xmlNodePtr rootNode = NULL;
  TixiDocumentHandle newHandle;

  if (!xmlFilename) {
    printMsg(MESSAGETYPE_ERROR, "Error: No filename given.\n");
    return FAILED;
  }

  if (!document) {
    printMsg(MESSAGETYPE_ERROR, "Error: Invalid document handle.\n");
    return INVALID_HANDLE;
  }

  if (saveMode == COMPLETE) {
    if (xmlSaveFormatFileEnc(xmlFilename, document->docPtr, "utf-8", document->usePrettyPrint) == -1) {
      printMsg(MESSAGETYPE_ERROR, "Error: Failed in writing document to file.\n");
      return FAILED;
    };

  }
  else if (saveMode == SPLITTED) {
    /* save included nodes back to external files */
    /* first create a copy and don't chance the original document */
    copyDocument(handle, &newHandle);
    cpyDoc = getDocument(newHandle);

    // update directory and file name
    if (cpyDoc->dirname) {
      free(cpyDoc->dirname);
    }
    if (cpyDoc->filename) {
      free(cpyDoc->filename);
    }
    strip_dirname(xmlFilename, &cpyDoc->dirname, &cpyDoc->filename);

    rootNode = xmlDocGetRootElement(cpyDoc->docPtr);
    saveExternalFiles(rootNode, cpyDoc);

    if (xmlSaveFormatFileEnc(xmlFilename, cpyDoc->docPtr, "utf-8", document->usePrettyPrint) == -1) {
      printMsg(MESSAGETYPE_ERROR, "Error: Failed in writing document to file.\n");
      return FAILED;
    };
    removeDocumentFromList(newHandle);
    freeTixiDocument(cpyDoc);

  }
  else if (saveMode == REMOVED) {
    copyDocument(handle, &newHandle);
    cpyDoc = getDocument(newHandle);

    rootNode = xmlDocGetRootElement(cpyDoc->docPtr);
    removeExternalNodes(rootNode, cpyDoc);

    if (xmlSaveFormatFileEnc(xmlFilename, cpyDoc->docPtr, "utf-8", cpyDoc->usePrettyPrint) == -1) {
      printMsg(MESSAGETYPE_ERROR, "Error: Failed in writing document to file.\n");
      return FAILED;
    };

  }
  else {
    return FAILED;
  }

  free(document->xmlFilename);
  document->xmlFilename = (char*) malloc(sizeof(char) * (strlen(xmlFilename) + 1));
  strcpy(document->xmlFilename, xmlFilename);

  document->status = SAVED;
  return SUCCESS;
}
Ejemplo n.º 23
0
daeUInt daeSTLDatabase::getElementCount(daeString name,daeString type,daeString file)
{	
	validate(); 
	
	// If none of the search keys was specified, return the total element count in the database
	if ( !name && !type && !file ) 
	{
		daeUInt count = 0;
		std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.begin();
		std::map< std::string, std::vector< daeElement*> >::iterator end = elements.end();
		while( iter != end )
		{
			count += (daeUInt)(*iter).second.size();
			++iter;
		}
		return count;
	}

	if ( name ) 
	{ 
		// name specified
		int count = 0;
		if ( file ) 
		{ 
			// If a document URI was a search key (in file) resolve it to a text URI with no fragment
			daeURI tempURI(file,true);
			daeDocument *col = getDocument( tempURI.getURI() );
			if ( col == NULL ) {
				return 0;
			}
			// a document was specified
			std::pair< std::multimap< std::string, daeElement* >::iterator, std::multimap< std::string, daeElement* >::iterator > range;
			range = elementsIDMap.equal_range( std::string( name ) );
			std::multimap< std::string, daeElement* >::iterator i = range.first;
			while ( i != range.second )
			{
				if ( col == (*i).second->getDocument() )
				{
					count++;
				}
				++i;
			}
			return count;
		}
		else 
		{ 
			//no file specified - just name
			return (daeUInt)elementsIDMap.count( std::string( name ) );
		}
	}

	if ( type ) 
	{ 
		// type specified
		std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.find( std::string( type ) );
		if ( iter == elements.end() )
		{
			return 0;
		}

		int count = 0;
		if ( file ) 
		{ 
			// If a document URI was a search key (in file) resolve it to a text URI with no fragment
			daeURI tempURI(file,true);
			daeDocument *col = getDocument( tempURI.getURI() );
			if ( col == NULL ) {
				return 0;
			}
			// a document was specified
			std::vector< daeElement* > &vec = (*iter).second;
			std::vector< daeElement* >::iterator i = vec.begin();
			std::vector< daeElement* >::iterator end = vec.end();
			while( i != end )
			{
				if ( col == (*i)->getDocument() )
				{
					++count;
				}
				++i;
			}
			return count;
		}
		else 
		{ 
			//no file specified - just type
			return (daeUInt)(*iter).second.size();
		}
	}

	//if you get here only a file was specified
	daeURI tempURI(file,true);
	daeDocument *col = getDocument( tempURI.getURI() );
	if ( col == NULL ) {
		return 0;
	}
	//a document was specified
	int count = 0;
	std::map< std::string, std::vector< daeElement*> >::iterator iter = elements.begin();
	std::map< std::string, std::vector< daeElement*> >::iterator end = elements.end();
	while( iter != end )
	{
		std::vector< daeElement* > &vec = (*iter).second;
		std::vector< daeElement* >::iterator i = vec.begin();
		std::vector< daeElement* >::iterator end2 = vec.end();
		while( i != end2 )
		{
			if( col == (*i)->getDocument() )
			{
				++count;
			}
			++i;
		}
		++iter;
	}
	return count;

}
Ejemplo n.º 24
0
ReturnCode getPoint(const TixiDocumentHandle handle, const char* parentPath, const int pointIndex,
                    int ignoreMissingElements, double* x, double* y, double* z)
{
  ReturnCode error = -1;
  ReturnCode errorX = -1;
  ReturnCode errorY = -1;
  ReturnCode errorZ = -1;

  TixiDocument* document = getDocument(handle);
  xmlDocPtr xmlDocument = NULL;
  xmlXPathObjectPtr xpathParentObject = NULL;
  xmlNodePtr parent = NULL;
  char* pointPath = NULL;
  char* coordinatePathBuffer = NULL;
  int nPointElements = 0;

  if (!document) {
    printMsg(MESSAGETYPE_ERROR, "Error: Invalid document handle.\n");
    return INVALID_HANDLE;
  }

  if (pointIndex < 1) {
    printMsg(MESSAGETYPE_ERROR, "Error: Invalid point index %d\n", pointIndex);
    return INDEX_OUT_OF_RANGE;
  }

  xmlDocument = document->docPtr;

  error = checkElement(xmlDocument, parentPath, &parent, &xpathParentObject);
  xmlXPathFreeObject(xpathParentObject);

  if (!error) {

    xmlXPathObjectPtr xpathPointObject = NULL;

    size_t lengthPointPath = (strlen(parentPath) +      /* length of path to parent   */
                              1);      				    /* trailing \0                */

    pointPath = (char*) malloc(sizeof(char) * lengthPointPath);

    strcpy(pointPath, parentPath);

    /* pad with trailing blanks, so we can check for the size in getCoordinateValue */

    error = checkExistence(xmlDocument, pointPath, &xpathPointObject);

    if (xpathPointObject) {
      nPointElements = xpathPointObject->nodesetval->nodeNr;
      xmlXPathFreeObject(xpathPointObject);
    }

    if (error == ELEMENT_NOT_FOUND) {
      printMsg(MESSAGETYPE_ERROR, "Error: No point element found in element \"%s\".\n", parentPath);
      error = NO_POINT_FOUND;
    }
    else if (!error) {
      if (pointIndex > nPointElements) {
        printMsg(MESSAGETYPE_ERROR, "Error: Index (%d) larger than number of point elements.\n", pointIndex);
        error = INDEX_OUT_OF_RANGE;
      }
      else {
        errorX = getCoordinateValue(xmlDocument, pointPath, pointIndex, "x", ignoreMissingElements, x);
        errorY = getCoordinateValue(xmlDocument, pointPath, pointIndex, "y", ignoreMissingElements, y);
        errorZ = getCoordinateValue(xmlDocument, pointPath, pointIndex, "z", ignoreMissingElements, z);

        if( errorX && errorY && errorZ) {
          error = NO_POINT_FOUND;
        }
        else {
          error = SUCCESS;
        }
      }

    }
  }

  free(coordinatePathBuffer);
  free(pointPath);
  return error;
}
Ejemplo n.º 25
0
void CmdPartDesignBody::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    if ( !PartDesignGui::assureModernWorkflow( getDocument() ) )
        return;
    App::Part *actPart = PartDesignGui::getActivePart ();
    App::Part* partOfBaseFeature = nullptr;

    std::vector<App::DocumentObject*> features =
        getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
    App::DocumentObject* baseFeature = nullptr;
    bool viewAll = features.empty();


    if (!features.empty()) {
        if (features.size() == 1) {
            baseFeature = features[0];
            if ( baseFeature->isDerivedFrom ( PartDesign::Feature::getClassTypeId() ) &&
                    PartDesign::Body::findBodyOf ( baseFeature ) ) {
                // Prevent creating bodies based on features already belonging to other bodies
                QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"),
                        QObject::tr("Body can't be based on a PartDesign feature."));
                baseFeature = nullptr;
            }
            else if (PartDesign::Body::findBodyOf ( baseFeature )){
                QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"),
                        QObject::tr("%1 already belongs to a body, can't use it as base feature for another body.")
                                     .arg(QString::fromUtf8(baseFeature->Label.getValue())));
                baseFeature = nullptr;
            }
            else if ( baseFeature->isDerivedFrom ( Part::BodyBase::getClassTypeId() ) )  {
                // Prevent creating bodies based on bodies
                QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"),
                        QObject::tr("Body can't be based on another body."));
                baseFeature = nullptr;
            }
            else {
                partOfBaseFeature = App::Part::getPartOfObject(baseFeature);
                if (partOfBaseFeature != 0  &&  partOfBaseFeature != actPart){
                    //prevent cross-part mess
                    QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"),
                            QObject::tr("Base feature (%1) belongs to other part.")
                                         .arg(QString::fromUtf8(baseFeature->Label.getValue())));
                    baseFeature = nullptr;
                };
            }

        } else {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"),
                QObject::tr("Body may be based no more than on one feature."));
            return;
        }
    }


    openCommand("Add a Body");

    std::string bodyName = getUniqueObjectName("Body");

    // add the Body feature itself, and make it active
    doCommand(Doc,"App.activeDocument().addObject('PartDesign::Body','%s')", bodyName.c_str());
    if (baseFeature) {
        if (partOfBaseFeature){
            //withdraw base feature from Part, otherwise visibility mandess results
            doCommand(Doc,"App.activeDocument().%s.removeObject(App.activeDocument().%s)",
                    partOfBaseFeature->getNameInDocument(), baseFeature->getNameInDocument());
        }
        doCommand(Doc,"App.activeDocument().%s.BaseFeature = App.activeDocument().%s",
                bodyName.c_str(), baseFeature->getNameInDocument());
    }
    addModule(Gui,"PartDesignGui"); // import the Gui module only once a session
    doCommand(Gui::Command::Gui, "Gui.activeView().setActiveObject('%s', App.activeDocument().%s)", 
            PDBODYKEY, bodyName.c_str());

    // Make the "Create sketch" prompt appear in the task panel
    doCommand(Gui,"Gui.Selection.clearSelection()");
    doCommand(Gui,"Gui.Selection.addSelection(App.ActiveDocument.%s)", bodyName.c_str());
    if (actPart) {
        doCommand(Doc,"App.activeDocument().%s.addObject(App.ActiveDocument.%s)",
                 actPart->getNameInDocument(), bodyName.c_str());
    }

    // The method 'SoCamera::viewBoundingBox' is still declared as protected in Coin3d versions
    // older than 4.0.
#if COIN_MAJOR_VERSION >= 4
    // if no part feature was there then auto-adjust the camera
    if (viewAll) {
        Gui::Document* doc = Gui::Application::Instance->getDocument(getDocument());
        Gui::View3DInventor* view = doc ? qobject_cast<Gui::View3DInventor*>(doc->getActiveView()) : nullptr;
        if (view) {
            SoCamera* camera = view->getViewer()->getCamera();
            SbViewportRegion vpregion = view->getViewer()->getViewportRegion();
            float aspectratio = vpregion.getViewportAspectRatio();

            float size = Gui::ViewProviderOrigin::defaultSize();
            SbBox3f bbox;
            bbox.setBounds(-size,-size,-size,size,size,size);
            camera->viewBoundingBox(bbox, aspectratio, 1.0f);
        }
    }
#endif

    updateActive();
}
Ejemplo n.º 26
0
void NodeImpl::changed() {
    // we do not actually store this information on every node, we only
    // have a global indicator on the Document. Doing otherwise cost us too
    // much for little gain.
    getDocument()->changed();
}
Ejemplo n.º 27
0
void CmdPartDesignMigrate::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    App::Document *doc = getDocument();

    std::set<PartDesign::Feature*> migrateFeatures;


    // Retrive all PartDesign Features objects and filter out features already belongs to some body
    for ( const auto & feat: doc->getObjects(  ) ) {
         if( feat->isDerivedFrom( PartDesign::Feature::getClassTypeId() ) &&
                 !PartDesign::Body::findBodyOf( feat ) && PartDesign::Body::isSolidFeature ( feat ) ) {
             migrateFeatures.insert ( static_cast <PartDesign::Feature *>( feat ) );
         }
    }

    if ( migrateFeatures.empty() ) {
        if ( !PartDesignGui::isModernWorkflow ( doc ) ) {
            // If there is nothing to migrate and workflow is still old just set it to modern
            PartDesignGui::WorkflowManager::instance()->forceWorkflow (
                    doc, PartDesignGui::Workflow::Modern );
        } else {
            // Huh? nothing to migrate?
            QMessageBox::warning ( 0, QObject::tr ( "Nothing to migrate" ),
                    QObject::tr ( "No PartDesign features which doesn't belong to a body found."
                        " Nothing to migrate." ) );
        }
        return;
    }

    // Note: this action is undoable, should it be?
    PartDesignGui::WorkflowManager::instance()->forceWorkflow ( doc, PartDesignGui::Workflow::Modern );

    // Put features into chains. Each chain should become a separate body.
    std::list< std::list<PartDesign::Feature *> > featureChains;
    std::list<PartDesign::Feature *> chain; //< the current chain we are working on

    for (auto featIt = migrateFeatures.begin(); !migrateFeatures.empty(); ) {
        Part::Feature *base = (*featIt)->getBaseObject( /*silent =*/ true );

        chain.push_front ( *featIt );

        if ( !base || !base->isDerivedFrom (PartDesign::Feature::getClassTypeId () ) ||
                PartDesignGui::isAnyNonPartDesignLinksTo ( static_cast <PartDesign::Feature *>(base),
                                                           /*respectGroups=*/ true ) ) {
            // a feature based on nothing as well as on non-partdesign solid starts a new chain
            auto newChainIt = featureChains.emplace (featureChains.end());
            newChainIt->splice (newChainIt->end(), chain);
        } else {
            // we are basing on some partdesign feature which supposed to belong to some body
            PartDesign::Feature *baseFeat = static_cast <PartDesign::Feature *>( base );

            auto baseFeatSetIt = find ( migrateFeatures.begin (), migrateFeatures.end (), baseFeat );

            if ( baseFeatSetIt != migrateFeatures.end() ) {
                // base feature is pending for migration, switch to it and continue over
                migrateFeatures.erase(featIt);
                featIt = baseFeatSetIt;
                continue;
            } else {
                // The base feature seems already assigned to some chain
                // Find which
                std::list<PartDesign::Feature *>::iterator baseFeatIt;
                auto chainIt = std::find_if( featureChains.begin(), featureChains.end(),
                        [baseFeat, &baseFeatIt] ( std::list<PartDesign::Feature *>&chain ) mutable -> bool {
                            baseFeatIt = std::find( chain.begin(), chain.end(), baseFeat );
                            return baseFeatIt !=  chain.end();
                        } );

                if ( chainIt != featureChains.end() ) {
                    assert (baseFeatIt != chainIt->end());
                    if ( std::next ( baseFeatIt ) == chainIt->end() ) {
                        // just append our chain to already found
                        chainIt->splice ( chainIt->end(), chain );
                        // TODO If we will hit a third part everything will be messed up again.
                        //      Probably it will require a yet another smart-ass find_if. (2015-08-10, Fat-Zer)
                    } else {
                        // We have a fork of a partDesign feature here
                        // add a chain for current body
                        auto newChainIt = featureChains.emplace (featureChains.end());
                        newChainIt->splice (newChainIt->end(), chain);
                        // add a chain for forked one
                        newChainIt = featureChains.emplace (featureChains.end());
                        newChainIt->splice (newChainIt->end(), *chainIt,
                                std::next ( baseFeatIt ), chainIt->end());
                    }
                } else {
                    // The feature is not present in list pending for migration,
                    // This generally shouldn't happen but may be if we run into some broken file
                    // Try to find out the body we should insert into
                    // TODO Some error/warning is needed here (2015-08-10, Fat-Zer)
                    auto newChainIt = featureChains.emplace (featureChains.end());
                    newChainIt->splice (newChainIt->end(), chain);
                }
            }
        }
        migrateFeatures.erase ( featIt );
        featIt = migrateFeatures.begin ();
        // TODO Align visibility (2015-08-17, Fat-Zer)
    } /* for */

    // TODO make it work without parts (2015-09-04, Fat-Zer)
    // add a part if there is no active yet
    App::Part *actPart = PartDesignGui::assertActivePart ();

    if (!actPart) {
        return;
    }

    // do the actual migration
    Gui::Command::openCommand("Migrate legacy part design features to Bodies");

    for ( auto chainIt = featureChains.begin(); !featureChains.empty();
            featureChains.erase (chainIt), chainIt = featureChains.begin () ) {
#ifndef FC_DEBUG
        if ( chainIt->empty () ) { // prevent crash in release in case of errors
            continue;
        }
#else
        assert ( !chainIt->empty () );
#endif
        Part::Feature *base = chainIt->front()->getBaseObject ( /*silent =*/ true );

        // Find a suitable chain to work with
        for( ; chainIt != featureChains.end(); chainIt ++) {
            base = chainIt->front()->getBaseObject ( /*silent =*/ true );
            if (!base || !base->isDerivedFrom ( PartDesign::Feature::getClassTypeId () ) ) {
                break;   // no base is ok
            } else {
                // The base feature is a PartDesign, it's a fork, try to reassign it to a body...
                base = PartDesign::Body::findBodyOf ( base );
                if ( base ) {
                    break;
                }
            }
        }

        if ( chainIt == featureChains.end() ) {
            // Shouldn't happen, may be only in case of some circular dependency?
            // TODO Some error message (2015-08-11, Fat-Zer)
            chainIt = featureChains.begin();
            base = chainIt->front()->getBaseObject ( /*silent =*/ true );
        }

        // Construct a Pretty Body name based on the Tip
        std::string bodyName = getUniqueObjectName (
                std::string ( chainIt->back()->getNameInDocument() ).append ( "Body" ).c_str () ) ;

        // Create a body for the chain
        doCommand ( Doc,"App.activeDocument().addObject('PartDesign::Body','%s')", bodyName.c_str () );
        doCommand ( Doc,"App.activeDocument().%s.addObject(App.ActiveDocument.%s)",
                actPart->getNameInDocument (), bodyName.c_str () );
        if (base) {
            doCommand ( Doc,"App.activeDocument().%s.BaseFeature = App.activeDocument().%s",
                bodyName.c_str (), base->getNameInDocument () );
        }

        // Fill the body with features
        for ( auto feature: *chainIt ) {
            if ( feature->isDerivedFrom ( PartDesign::ProfileBased::getClassTypeId() ) ) {
                // add the sketch and also reroute it if needed
                PartDesign::ProfileBased *sketchBased = static_cast<PartDesign::ProfileBased *> ( feature );
                Part::Part2DObject *sketch = sketchBased->getVerifiedSketch( /*silent =*/ true);
                if ( sketch ) {
                    doCommand ( Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",
                            bodyName.c_str (), sketch->getNameInDocument() );

                    if ( sketch->isDerivedFrom ( Sketcher::SketchObject::getClassTypeId() ) ) {
                        try {
                            PartDesignGui::fixSketchSupport ( static_cast<Sketcher::SketchObject *> ( sketch ) );
                        } catch (Base::Exception &) {
                            QMessageBox::critical(Gui::getMainWindow(),
                                    QObject::tr("Sketch plane cannot be migrated"),
                                    QObject::tr("Please edit '%1' and redefine it to use a Base or "
                                        "Datum plane as the sketch plane.").
                                    arg(QString::fromUtf8(sketch->Label.getValue()) ) );
                        }
                    } else {
                        // TODO Message that sketchbased is based not on a sketch (2015-08-11, Fat-Zer)
                    }
                }
            }
            doCommand ( Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",
                    bodyName.c_str (), feature->getNameInDocument() );

            PartDesignGui::relinkToBody ( feature );
        }

    }

    updateActive();
}
Ejemplo n.º 28
0
bool pt_PieceTable::_fmtChangeSpanWithNotify(PTChangeFmt ptc,
											 pf_Frag_Text * pft, UT_uint32 fragOffset,
											 PT_DocPosition dpos,
											 UT_uint32 length,
											 const gchar ** attributes,
											 const gchar ** properties,
											 pf_Frag_Strux * pfs,
											 pf_Frag ** ppfNewEnd,
											 UT_uint32 * pfragOffsetNewEnd,
											 bool bRevisionDelete)
{
	// create a change record for this change and put it in the history.

	if (length == 0)					// TODO decide if this is an error.
	{
		UT_DEBUGMSG(("_fmtChangeSpanWithNotify: length==0\n"));
		SETP(ppfNewEnd, pft->getNext());
		SETP(pfragOffsetNewEnd, 0);
		return true;
	}

	UT_return_val_if_fail (fragOffset+length <= pft->getLength(), false);

	PT_AttrPropIndex indexNewAP;
	PT_AttrPropIndex indexOldAP = pft->getIndexAP();
	bool bMerged;
	if(attributes && properties && (attributes[0] == NULL) && (properties[0] == NULL))
	{
	    //
	    // Clear out all attributes/properties and set to the first index
	    //
	    bMerged = true;
	    indexNewAP = 0;
	}
	else
	  bMerged = m_varset.mergeAP(ptc,indexOldAP,attributes,properties,&indexNewAP,getDocument());

	UT_ASSERT_HARMLESS(bMerged);

	if (indexOldAP == indexNewAP)		// the requested change will have no effect on this fragment.
	{
		if (fragOffset+length == pft->getLength())
		{
			SETP(ppfNewEnd, pft->getNext());
			SETP(pfragOffsetNewEnd, 0);
		}
		else
		{
			SETP(ppfNewEnd, pft);
			SETP(pfragOffsetNewEnd, fragOffset+length);
		}

		return true;
	}

	// we do this before the actual change because various fields that
	// we need may be blown away during the change.  we then notify all
	// listeners of the change.

	PT_BlockOffset blockOffset = _computeBlockOffset(pfs,pft) + fragOffset;

	PX_ChangeRecord_SpanChange * pcr
		= new PX_ChangeRecord_SpanChange(PX_ChangeRecord::PXT_ChangeSpan,
										 dpos, indexOldAP,indexNewAP,
										 m_varset.getBufIndex(pft->getBufIndex(),fragOffset),
										 length,blockOffset,bRevisionDelete);
	UT_return_val_if_fail (pcr,false);
	bool bResult = _fmtChangeSpan(pft,fragOffset,length,indexNewAP,ppfNewEnd,pfragOffsetNewEnd);

	// add record to history.  we do not attempt to coalesce these.
	m_history.addChangeRecord(pcr);
	m_pDocument->notifyListeners(pfs,pcr);

	return bResult;
}
Ejemplo n.º 29
0
bool CmdPartDesignMoveFeatureInTree::isActive(void)
{
    return hasActiveDocument () && !PartDesignGui::isLegacyWorkflow ( getDocument () );
}
Ejemplo n.º 30
0
 Status Element::appendNull(const StringData& fieldName) {
     return pushBack(getDocument().makeElementNull(fieldName));
 }