void SharesNavigatorTreeModel::setupModelData(const QStringList& lines, SharesNavigatorTreeItem* parent)
{
		QList<SharesNavigatorTreeItem*> parents;
		QList<int> indentations;
		parents << parent;
		indentations << 0;

		int number = 0;

		while(number < lines.count())
		{
				int position = 0;
				while(position < lines[number].length())
				{
						if(lines[number].mid(position, 1) != " ")
						{
								break;
						}
						position++;
				}

				QString lineData = lines[number].mid(position).trimmed();

				if(!lineData.isEmpty())
				{
						// Read the column data from the rest of the line.
						QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
						QList<QVariant> columnData;
						for(int column = 0; column < columnStrings.count(); ++column)
						{
								columnData << columnStrings[column];
						}

						if(position > indentations.last())
						{
								// The last child of the current parent is now the new parent
								// unless the current parent has no children.

								if(parents.last()->childCount() > 0)
								{
										parents << parents.last()->child(parents.last()->childCount() - 1);
										indentations << position;
								}
						}
						else
						{
								while(position < indentations.last() && parents.count() > 0)
								{
										parents.pop_back();
										indentations.pop_back();
								}
						}

						// Append a new item to the current parent's list of children.
						parents.last()->appendChild(new SharesNavigatorTreeItem(columnData, parents.last()));
				}

				number++;
		}
}
示例#2
0
void TreeModel::setupModelData(const QStringList &lines,TreeItem *parent)
{
	QList<TreeItem*> parents;
	QList<int> indentations;
	parents << parent;
	indentations << 0;

	int number = 0;

	while (number < lines.count()) {
		int position = 0;
		while (position < lines[number].length()) {
			if (lines[number].at(position) != ' ')
				break;
			position++;
		}

		QString lineData = lines[number].mid(position).trimmed();

		if (!lineData.isEmpty()) {
			// Read the column data from the rest of the line.
			QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
			QList<QVariant> columnData;
			for (int column = 0; column < columnStrings.count(); ++column)
				columnData << columnStrings[column];

			if (position > indentations.last()) {
				// The last child of the current parent is now the new parent
				// unless the current parent has no children.

				if (parents.last()->childCount() > 0) {
					parents << parents.last()->child(parents.last()->childCount()-1);
					indentations << position;
				}
			} else {
				while (position < indentations.last() && parents.count() > 0) {
					parents.pop_back();
					indentations.pop_back();
				}
			}

			// Append a new item to the current parent's list of children.
			parents.last()->appendChild(new TreeItem(columnData, parents.last()));
		}

		++number;
	}


	foreach (QString e, DataController::getInstance()->getEssences())
	{
		EREssenceData * data = DataController::getInstance()->search(e);
		QString name = data->getId();
		QString type = Support::typeToString(data->getType());
		QList<QString> keys = data->getKeys();
		QList<QString> attrs = data->getAttributes();
		QList<QString> adj = DataController::getInstance()->getAjesencyFor(data->getId());

	}
示例#3
0
void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
{
    QList<TreeItem*> parents;
    QList<int> indentations;
    parents << parent;
    indentations << 0;

    int number = 0;

    while (number < lines.count()) {
        int position = 0;
        while (position < lines[number].length()) {
            if (lines[number].mid(position, 1) != " ")
                break;
            position++;
        }

        QString lineData = lines[number].mid(position).trimmed();

        if (!lineData.isEmpty()) {
            // Read the column data from the rest of the line.
            QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
            QVector<QVariant> columnData;
            for (int column = 0; column < columnStrings.count(); ++column)
                columnData << columnStrings[column];

            if (position > indentations.last()) {
                // The last child of the current parent is now the new parent
                // unless the current parent has no children.

                if (parents.last()->childCount() > 0) {
                    parents << parents.last()->child(parents.last()->childCount()-1);
                    indentations << position;
                }
            } else {
                while (position < indentations.last() && parents.count() > 0) {
                    parents.pop_back();
                    indentations.pop_back();
                }
            }

            // Append a new item to the current parent's list of children.
            TreeItem *parent = parents.last();
            parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
            for (int column = 0; column < columnData.size(); ++column)
                parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
        }

        number++;
    }
}
示例#4
0
bool Wheel::connect(QString portName)
{
    QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
    //Locking for the port
    while (!ports.isEmpty() && ports.last().portName() != portName)
    {
        ports.pop_back();
    }
    port = &ports.last();
    serial->setPort(*port);
    serial->readAll(); // Clear buffer
    if (serial->open(QIODevice::ReadWrite)) {
        serial->setDataTerminalReady(false); // Set DTR to low to reset the arduino board.
        serial->setDataTerminalReady(true);
        //Initialisation sequence
        serial->waitForReadyRead(3000);
        char data[7]; // Read buffer
        serial->read(data, sizeof(wheel_con_report_t));
        wheel_con_report_t w_info;
        memcpy(&w_info, data, sizeof(wheel_con_report_t));
        if (w_info.bDescriptorType == 0x01) { // Device is identified, it seems to be an arduwheel
            vFirmware = QString::fromUtf8(w_info.vFirmware); // Save firmware version
            connected = true;
            QObject::connect(serial, SIGNAL(readyRead()), this, SLOT(processReadyRead())); // Incomming "packets" are now handled by processReadyRead slot
            return true;
        }
        //If it's not a wheel
        serial->close();

    }
    return false;
}
示例#5
0
文件: Git.cpp 项目: ybznek/git-z
void Git::parseStatus() {

  QByteArray all = readStandardOutput();
  QList<QByteArray> items = all.split('\0');
  items.pop_back(); // remove last empty item


  LockHolder<GitFileList> list = fileList.getLock();
  list->clear();
  for (const QString &item : items) {
    // https://www.kernel.org/pub/software/scm/git/docs/git-status.html
    GitFile::state fileState;
    if (item.startsWith("??")) {
      fileState = GitFile::state::CREATED;
    } else if (item.startsWith(" M")) {
      fileState = GitFile::state::MODIFIED;
    } else if (item.startsWith(" D")) {
      fileState = GitFile::state::REMOVED;
    } else {
      fileState = GitFile::state::UNKNOWN;
    }
    QString filename = item.mid(3);

    list->append(GitFile{filename, fileState});
  }
  qDebug() << "emitim status\n";
  onStatusUpdated();
}
QString huffdecotification::TreeHuffmanTreeLeft(QString huff)
{
    QString leftTree;
    QList<char> verification;
    if(huff.at(0).toLatin1()=='*' && huff.at(1).toLatin1()=='*')
    {
        verification.push_back('*');
        for(int i=1; i<huff.size();i++)
        {
            if(huff.at(i).toLatin1()=='*' && huff.at(i-1).toLatin1()!='!')
            {
                verification.push_back('*');
            }
            else
            {
                if(huff.at(i).toLatin1()!='!')
                    verification.pop_back();
            }
            leftTree.append(huff.at(i));
            if(verification.isEmpty())
            {
                break;
            }
        }
    }
    else
    {
        leftTree=huff.at(1);
        if(huff.at(1).toLatin1()=='!')
        {
            leftTree=huff.at(2);
        }
    }
    return leftTree;
}
示例#7
0
QString huffdecoditication::TreeHuffmanDecodificationLeft(QString huff)
{
    QList<char> test;
    QString TreeHuffmanDecodificationLeft;
    if(huff.at(0).toLatin1()=='(')
    {
        test.push_back('(');
        for(int i=1;i<huff.size();i++)
        {
            if(huff.at(i).toLatin1()=='(' && huff.at(i-1).toLatin1()!='-')
            {
                test.push_back('(');
            }
            if(huff.at(i).toLatin1()==')' && huff.at(i-1).toLatin1()!='-')
            {
                test.pop_back();
            }
            if(test.isEmpty())
            {
                break;
            }
            TreeHuffmanDecodificationLeft.append(huff.at(i));
        }
    }
    else
    {
        TreeHuffmanDecodificationLeft=huff.at(0);
        if(huff.at(0).toLatin1()=='-')
        {
            TreeHuffmanDecodificationLeft=huff.at(1);
        }
    }

    return TreeHuffmanDecodificationLeft;
}
示例#8
0
void QgsRecentColorScheme::addRecentColor( const QColor &color )
{
  if ( !color.isValid() )
  {
    return;
  }

  //strip alpha from color
  QColor opaqueColor = color;
  opaqueColor.setAlpha( 255 );

  QgsSettings settings;
  QList< QVariant > recentColorVariants = settings.value( QStringLiteral( "colors/recent" ) ).toList();

  //remove colors by name
  for ( int colorIdx = recentColorVariants.length() - 1; colorIdx >= 0; --colorIdx )
  {
    if ( ( recentColorVariants.at( colorIdx ).value<QColor>() ).name() == opaqueColor.name() )
    {
      recentColorVariants.removeAt( colorIdx );
    }
  }

  //add color
  QVariant colorVariant = QVariant( opaqueColor );
  recentColorVariants.prepend( colorVariant );

  //trim to 20 colors
  while ( recentColorVariants.count() > 20 )
  {
    recentColorVariants.pop_back();
  }

  settings.setValue( QStringLiteral( "colors/recent" ), recentColorVariants );
}
示例#9
0
bool Catalog::getItemsFromQuery(InputList &inputData, QList<CatItem>& outResults,
                                int itemsDesired,
                                int* beginPos){

    QString userKeys = inputData.getUserKeys();
    QList<CatItem> partialList = parseRequest(inputData,itemsDesired, beginPos);
    plugins.getLabels(&inputData);
    plugins.getResults(&inputData, &partialList);

    //outResults = expandStubs(inputData.getUserKeys(), &partialList);
    outResults = partialList;

    //Skipping because it should happen in more detail later...
    //...
    //Sort by single keys ... even if we're on multiple words otherwise
    if(inputData.selectingByKeys()){
        Catalog::curFilterStr = userKeys;
        qSort(outResults.begin(), outResults.end(), CatLessNoPtr);

        while(outResults.count() > itemsDesired ){
            outResults.pop_back();
        }
    }

    return true;
}
示例#10
0
bool ConnectionManager2::applyConfig(QVariant const & config)
{
    if (config.type() != QVariant::List)
        return false;

    QList<Connection *> newConns;
    struct cleanup
    {
        QList<Connection *> & conns;
        cleanup(QList<Connection *> & conns) : conns(conns) {}
        ~cleanup() { for (int i = 0; i < conns.size(); ++i) conns[i]->releaseAll(); }
    } cleanupGuard(newConns);

    QList<QVariant> const & connConfigs = config.toList();

    for (int i = 0; i < connConfigs.size(); ++i)
    {
        if (connConfigs[i].type() != QVariant::Hash)
            return false;
        QHash<QString, QVariant> const & connConfig = connConfigs[i].toHash();

        QVariant typev = connConfig.value("type");
        if (typev.type() != QVariant::String)
            return false;

        QString const & type = typev.toString();

        ConnectionPointer<Connection> conn;
        if (type == "serial_port")
            conn.reset(new SerialPort());
        else if (type == "tcp_client")
            conn.reset(new TcpSocket());
        else if (type == "udp_socket")
            conn.reset(new UdpSocket());
#ifdef HAVE_LIBYB
        else if (type == "usb_yb_acm")
            conn.reset(new UsbAcmConnection2(m_yb_runner));
#endif

        if (!conn)
            return false;

        QVariant settings = connConfig.value("settings");
        if (settings.type() != QVariant::Hash || !conn->applyConfig(settings.toHash()))
            return false;

        newConns.push_back(conn.data());
        conn.take();
    }

    this->clearUserOwnedConns();
    while (!newConns.empty())
    {
        this->addUserOwnedConn(newConns.back());
        newConns.pop_back();
    }

    return true;
}
static void cleanupEffectList(QList<QGLColladaFxEffect*> &effects)
{
    while (effects.count())
    {
        delete effects.back();
        effects.pop_back();
    }
}
示例#12
0
/**
 * @brief TreeModel::deployDocument this function is a recursive implementation of depth-first trasversal in a tree. With the depth-first iterator implemented later, we would be able to make this code shorter
 * @param current the root we begin at
 * @param parents une file des parents
 * @param indent une file des indentation.
 */
void TreeModel::deployDocument(Document* current, QList<TreeItem*>& parents, QList<int>& indent){

    TreeItem *parent = parents.last();
    if(current!=nm->getRootDocument()){
        // current as a child of its parent
        indent.append(indent.last()+1);
        parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
        parent->child(parent->childCount() - 1)->setData(0, current->getTitle(), current);
    }
    // current becomes a new parent
    TreeItem *tmp = parent->child(parent->childCount() - 1);
    if(tmp)
        parents << parent->child(parent->childCount() - 1);
    else{
        parents << rootItem;
    }


    for (nListIt it = current->begin(); it!=current->end(); ++it){
//        qDebug()<<"Note Title: " << current->getTitle()<<" Filtered? :"<<filterKit->isFilteredByFilters(current);
//        qDebug()<<"is ~ Document? " << (current!=nm->getRootDocument());
        if((*it)->isDeleted() || (*it)!=rootItem->getItemId() && filterKit->isFilteredByFilters((*it))){
            // We don't want to filter our root Document.
            // We apply all enabled filters.
            continue;
        }
        // If it is a doc, we deploy this doc.
        if((*it)->isDocument()){
            deployDocument(dynamic_cast<Document*>(*it), parents, indent);
        }
        else{

            // We add it as a child.
            QVector<QVariant> data;
            data << (*it)->getTitle();
            TreeItem *parent = parents.last();
            parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
            for (int column = 0; column < data.size(); ++column)
                parent->child(parent->childCount() - 1)->setData(column, data[column], *it);

        }
    }
    parents.pop_back();
    indent.pop_back();
}
示例#13
0
void VideoWindow::remove(QList<int> rows){
    disconnect(this->ui->sequence,SIGNAL(itemSelectionChanged()),this,SLOT(review()));
    while(rows.size()>0){
        this->eventsPositionInMiliseconds.removeAt(rows.last());
        this->ui->sequence->removeRow(rows.last());
        rows.pop_back();
    }
    connect(this->ui->sequence,SIGNAL(itemSelectionChanged()),this,SLOT(review()));
    this->checkSaveCondition();
}
示例#14
0
void ConnectorOld::readString()
{
  recvBuffer += readAll();
  if (recvBuffer.split('\n').count() == 1)    // Verify for not full message
    return;
  QList<QByteArray> recvStrings = recvBuffer.split('\n'); // Splitting messages
  recvBuffer = recvStrings.last();                        // Save not full on buffer
  recvStrings.pop_back();                                 // Remove not full from list
  QList<QByteArray>::const_iterator it;
  for (it = recvStrings.constBegin(); it != recvStrings.constEnd(); ++it)
    emit readStringReady(*it);
}
示例#15
0
void tst_QList::end() const
{
    QList<QString> list;
    list << "foo" << "bar";

    QCOMPARE(*--list.end(), QLatin1String("bar"));

    // remove an item, make sure it still works
    list.pop_back();
    QVERIFY(list.size() == 1);
    QCOMPARE(*--list.end(), QLatin1String("foo"));
}
示例#16
0
void tst_QList::endsWith() const
{
    QList<QString> list;
    list << "foo" << "bar" << "baz";

    // test it returns correctly in both cases
    QVERIFY(list.endsWith(QLatin1String("baz")));
    QVERIFY(!list.endsWith(QLatin1String("bar")));

    // remove an item and make sure the end item changes
    list.pop_back();
    QVERIFY(list.endsWith(QLatin1String("bar")));
}
void MainWindow::changeEpisodeOrderPressed(){
	QList<QListWidgetItem*> items = episodeList->selectedItems();
	QList<int> itemRows;
	if(items.length()==0) return;
	for(int x=0; x<items.length(); x++){
		itemRows.push_back(episodeList->row(items[x]));
	}
	qSort(itemRows); // make sure it is sorted even though it "should" be

	QObject *sender = QObject::sender();
	if(sender == overrideSettingsWidgets.moveEpisode_Up_button){
		//remove items that can't move up aka like rows 0,1,2,3,4 or just 0
		// so if 0,1,5,6 -> we get 5,6 out
		for(int x=0; itemRows.length()>0 && x==itemRows[0]; x++)
			itemRows.pop_front();
		if(itemRows.length() == 0) return;

		//now go in forward order, swapping rows
		for(int x=0; x<itemRows.length(); x++){
			QListWidgetItem *temp1,*temp2;
			temp1=episodeList->takeItem(itemRows[x]);
			temp2=episodeList->takeItem(itemRows[x]-1);
			episodeList->insertItem(itemRows[x]-1,temp1);
			episodeList->insertItem(itemRows[x]  ,temp2);
			temp1->setSelected(true); // to keep the selected entries selected after moving
		}
	}
	if(sender == overrideSettingsWidgets.moveEpisode_Ignore_button){
		//now go in reverse order, deleting entries
		for(int x=itemRows.length()-1; x>=0; x--){
			delete episodeList->takeItem(itemRows[x]);
		}
	}
	if(sender == overrideSettingsWidgets.moveEpisode_Down_button){
		//remove items that can't move up down past the end of the list
		// so if 7 items total and indicies 0,1,5,6 -> we get 0,1 out
		for(int x=episodeList->count()-1; itemRows.length()>0 && x==itemRows[itemRows.length()-1]; x--)
			itemRows.pop_back();
		if(itemRows.length() == 0) return;

		//now go in reverse order, swapping rows
		for(int x=itemRows.length()-1; x>=0; x--){
			QListWidgetItem *temp1,*temp2;
			temp2=episodeList->takeItem(itemRows[x]+1);
			temp1=episodeList->takeItem(itemRows[x]);
			episodeList->insertItem(itemRows[x]  ,temp2);
			episodeList->insertItem(itemRows[x]+1,temp1);
			temp1->setSelected(true); // to keep the selected entries selected after moving
		}
	}
}
示例#18
0
void tst_QList::count() const
{
    QList<QString> list;

    // starts empty
    QVERIFY(list.count() == 0);

    // goes up
    list.append(QLatin1String("foo"));
    QVERIFY(list.count() == 1);

    // and up
    list.append(QLatin1String("bar"));
    QVERIFY(list.count() == 2);

    // and down
    list.pop_back();
    QVERIFY(list.count() == 1);

    // and empty. :)
    list.pop_back();
    QVERIFY(list.count() == 0);
}
示例#19
0
void tst_QList::empty() const
{
    QList<QString> list;

    // make sure it starts empty
    QVERIFY(list.empty());

    // and doesn't stay empty
    list.append(QLatin1String("foo"));
    QVERIFY(!list.empty());

    // and goes back to being empty
    list.pop_back();
    QVERIFY(list.empty());
}
示例#20
0
    void removeClicked()
    {
        QList<QTreeWidgetItem*> selectedPaths = m_treeView->selectedItems();

        for( int i = selectedPaths.size() - 1; i >= 0; --i )
        {
            m_treeView->takeTopLevelItem( m_treeView->indexOfTopLevelItem( selectedPaths.last() ) );
            selectedPaths.pop_back();
        }

        rebuildRowIndexes();
        updateLabel();

        Q_EMIT signalChanged();
    }
示例#21
0
void TreeModel::addRGBAttr(QList<TreeItem*> & parents, const std::string & attrName, int level, QColor value)
{
	for(int i=0; i < level; i++) 
        parents << parents.last()->child(parents.last()->childCount()-1);

    QList<QVariant> columnData;
    columnData << QString(tr(attrName.c_str()))<< QVariant(value);
    
	TreeItem *parent = parents.last();
	parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
	parent->lastChild()->setValueType(3);
	for (int column = 0; column < columnData.size(); ++column)
		parent->lastChild()->setData(column, columnData[column]);
		
    for(int i=0; i < level; i++) parents.pop_back();
	m_numRows++;
}
void ConnectionCollector::updateIDCounter (QList<int>&usedID)
{
    // reverse sort of usedID
    
    qSort(usedID.begin(), usedID.end(), std::greater<int>());
    
    while (!usedID.empty())
    {
        // add available ID to m_freeID
        for (int i = m_firstFreeID ; i < usedID[usedID.size() -1 ]; i++)
            m_freeID.push_back(i);

        m_firstFreeID = usedID[usedID.size() -1 ] + 1;
        
        usedID.pop_back();
    }
}
示例#23
0
void TreeModel::addBase(QList<TreeItem*> & parents, const std::string & baseName, int level)
{
    for(int i=0; i < level; i++) 
        parents << parents.last()->child(parents.last()->childCount()-1);

    QList<QVariant> columnData;
    columnData << QString(tr(baseName.c_str()));
    
	TreeItem *parent = parents.last();
	parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
	for (int column = 0; column < columnData.size(); ++column)
		parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
    
	for(int i=0; i < level; i++) parents.pop_back();
	m_baseRows[baseName] = 1;
	m_numRows++;
}
示例#24
0
QWidget* IncludeFileData::expandingWidget() const {
  
  DUChainReadLocker lock( DUChain::lock() );
  QString htmlPrefix, htmlSuffix;
  
  QList<KUrl> inclusionPath; //Here, store the shortest way of intermediate includes to the included file.

  if( m_item.pathNumber == -1 ) {
    htmlPrefix = i18n("This file imports the current open document<br/>");
  } else {
    if( !inclusionPath.isEmpty() )
      inclusionPath.pop_back(); //Remove the file itself from the list
    
    htmlSuffix = "<br/>" + i18n( "In include path %1", m_item.pathNumber );
  }
  
  foreach( const KUrl& u, inclusionPath )
    htmlPrefix += i18n("Included through %1 <br/>", QString("KDEV_FILE_LINK{%1}").arg(u.pathOrUrl()) );
  
  return new NavigationWidget( m_item, getCurrentTopDUContext(), htmlPrefix, htmlSuffix );
}
示例#25
0
void TreeModel::clear()
{
  if(_rootItem->childCount())
  {
    QList<TreeItem*> items = QList<TreeItem*>();
    QList<TreeItem*> del = QList<TreeItem*>();

    items << _rootItem;
    del   << _rootItem;
    while(items.count()) {
      
      TreeItem* parent = items.first();
      
      for(int i = 0; i < parent->childCount(); i++) {
        
        del   << parent->child(i);
        items << parent->child(i);
      }
      
      items.pop_front();
      
    }

    // удаляем начиная с конца, т.е. сначала удаляем наследников, потом, 
    // поднимаясь наверх - предков, пока не дойдем до rootItem
    beginResetModel();

    while(1) {
      
//      qDebug() << del.last()->data(0).toString();
      del.last()->removeChildren(0, del.last()->childCount());
      if(_rootItem == del.last()) break;
      del.pop_back();
    }
//    rootItem->removeChildren(0, 3/*rootItem->childCount()*/); //! !!!!!!!!!
    endResetModel();
    
  }
}
	void load( const QString& filename )
	{
		QFile file( filename );

		if ( !file.open( QIODevice::ReadOnly ) )
		{
			Console::instance()->send( tr( "Unable to open %1!\n" ).arg( filename ) );
			return;
		}

		filenames.push_back( filename );

		QXmlInputSource input( &file );
		QXmlSimpleReader reader;
		reader.setFeature( "http://trolltech.com/xml/features/report-whitespace-only-CharData", false );

		reader.setContentHandler( this );
		reader.setErrorHandler( this );
		reader.parse( &input, false );

		filenames.pop_back();
	}
示例#27
0
bool PhotoEffectsGroup::moveRows(int sourcePosition, int sourceCount, int destPosition)
{
    if (  (sourcePosition <= destPosition && sourcePosition+sourceCount >= destPosition) ||
            sourceCount <= 0 ||
            m_effects_list.count() <= sourcePosition+sourceCount-1 ||
            sourcePosition < 0 ||
            destPosition < 0 ||
            m_effects_list.count() < destPosition)
        return false;

    beginMoveRows(QModelIndex(), sourcePosition, sourcePosition+sourceCount-1, QModelIndex(), destPosition);
    QList<AbstractPhotoEffectInterface*> movingItems;
    if (destPosition > sourcePosition)
        destPosition -= sourceCount;
    while(sourceCount--)
        movingItems.push_back(m_effects_list.takeAt(sourcePosition));
    for ( ; movingItems.count() ; movingItems.pop_back())
        m_effects_list.insert(destPosition, movingItems.last());
    endMoveRows();
    this->emitEffectsChanged();
    emit layoutChanged();
    return true;
}
bool ProtobufTree::addTreeData(QTreeWidgetItem* parent,
                               const google::protobuf::Message& msg) {
    const Reflection* ref = msg.GetReflection();

    // Get fields in the message
    vector<const FieldDescriptor*> fields;
    ref->ListFields(msg, &fields);

    // Get map of field numbers to child items
    FieldMap fieldMap =
        parent->data(Column_Tag, FieldMapRole).value<FieldMap>();

    bool newFields = false;

    // Clear data for missing fields
    const Descriptor* desc = msg.GetDescriptor();
    for (FieldMap::const_iterator i = fieldMap.begin(); i != fieldMap.end();
         ++i) {
        const FieldDescriptor* field = desc->FindFieldByNumber(i.key());
        if (!field) {
            // Field has left the descriptor - should never happen
            printf("Lost field %s.%d\n", desc->name().c_str(), i.key());
            continue;
        }

        QTreeWidgetItem* item = i.value();

        bool hasData;
        if (field->is_repeated()) {
            hasData = ref->FieldSize(msg, field);

            if (!hasData && item->childCount()) {
                // Remove and delete children
                for (QTreeWidgetItem* child : item->takeChildren()) {
                    delete child;
                }
            }
        } else {
            hasData = ref->HasField(msg, field);
        }

        if (!hasData) {
            item->setText(Column_Value, QString());
            item->setData(Column_Value, Qt::CheckStateRole, QVariant());
        }
    }

    for (const FieldDescriptor* field : fields) {
        // Get the item for this field if the field has been seen before
        QTreeWidgetItem* item;
        FieldMap::iterator fieldIter = fieldMap.find(field->number());
        if (fieldIter != fieldMap.end()) {
            // Field is already in parent
            item = *fieldIter;
        } else {
            // New field
            item = new QTreeWidgetItem(parent);
            fieldMap.insert(field->number(), item);

            item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            parent->setData(Column_Tag, FieldMapRole,
                            QVariant::fromValue<FieldMap>(fieldMap));
            item->setData(Column_Tag, Qt::DisplayRole, field->number());
            item->setData(Column_Tag, FieldDescriptorRole,
                          QVariant::fromValue(field));
            item->setText(Column_Field, QString::fromStdString(field->name()));

            if (field->type() == FieldDescriptor::TYPE_MESSAGE &&
                !field->is_repeated()) {
                // Singular messages are expanded by default
                expandItem(item);
            }

            newFields = true;
        }

        if (field->is_repeated()) {
            // Repeated field
            int n = ref->FieldSize(msg, field);

            // Show the number of elements as the value for the field itself
            item->setData(Column_Value, Qt::DisplayRole, n);

            // Make sure we have enough children
            int children = item->childCount();
            if (children < n) {
                // Add children
                for (int i = children; i < n; ++i) {
                    QTreeWidgetItem* child = new QTreeWidgetItem(item);
                    child->setText(Column_Field, QString("[%1]").arg(i));

                    child->setData(Column_Tag, FieldDescriptorRole, field);

                    // For repeated items, the tag column holds the index in the
                    // field
                    child->setData(Column_Tag, Qt::DisplayRole, i);

                    // A FieldMap is not used here because the items don't
                    // actually have tags. The item's position in its parent is
                    // its position in the repeated field.
                }

                newFields = true;
            } else if (children > n) {
                // Remove excess children
                // Internally, QTreeWidgetItem stores a QList of children.
                // Hopefully this is efficient.
                QList<QTreeWidgetItem*> kids = item->takeChildren();
                for (int i = 0; i < (children - n); ++i) {
                    delete kids.back();
                    kids.pop_back();
                }
                item->addChildren(kids);
            }

            // Set data for children
            for (int i = 0; i < n; ++i) {
                QTreeWidgetItem* child = item->child(i);

                switch (field->type()) {
                    case FieldDescriptor::TYPE_INT32:
                    case FieldDescriptor::TYPE_SINT32:
                    case FieldDescriptor::TYPE_FIXED32:
                    case FieldDescriptor::TYPE_SFIXED32:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedInt32(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_INT64:
                    case FieldDescriptor::TYPE_SINT64:
                    case FieldDescriptor::TYPE_FIXED64:
                    case FieldDescriptor::TYPE_SFIXED64:
                        child->setData(
                            Column_Value, Qt::DisplayRole,
                            (qlonglong)ref->GetRepeatedInt64(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_UINT32:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedUInt32(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_UINT64:
                        child->setData(
                            Column_Value, Qt::DisplayRole,
                            (qulonglong)ref->GetRepeatedUInt64(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_FLOAT:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedFloat(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_DOUBLE:
                        child->setData(Column_Value, Qt::DisplayRole,
                                       ref->GetRepeatedDouble(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_BOOL:
                        child->setCheckState(Column_Value,
                                             ref->GetRepeatedBool(msg, field, i)
                                                 ? Qt::Checked
                                                 : Qt::Unchecked);
                        break;

                    case FieldDescriptor::TYPE_ENUM: {
                        const EnumValueDescriptor* ev =
                            ref->GetRepeatedEnum(msg, field, i);
                        child->setText(Column_Value,
                                       QString::fromStdString(ev->name()));
                        break;
                    }

                    case FieldDescriptor::TYPE_STRING:
                        child->setText(Column_Value, QString::fromStdString(
                                                         ref->GetRepeatedString(
                                                             msg, field, i)));
                        break;

                    case FieldDescriptor::TYPE_MESSAGE:
                        child->setData(Column_Tag, IsMessageRole, true);
                        newFields |= addTreeData(
                            child, ref->GetRepeatedMessage(msg, field, i));
                        break;

                    case FieldDescriptor::TYPE_BYTES:
                        addBytes(child, ref->GetRepeatedString(msg, field, i));
                        break;

                    default:
                        child->setText(Column_Value,
                                       QString("??? %1").arg(field->type()));
                        break;
                }
            }
        } else
            switch (field->type()) {
                case FieldDescriptor::TYPE_INT32:
                case FieldDescriptor::TYPE_SINT32:
                case FieldDescriptor::TYPE_FIXED32:
                case FieldDescriptor::TYPE_SFIXED32:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetInt32(msg, field));
                    break;

                case FieldDescriptor::TYPE_INT64:
                case FieldDescriptor::TYPE_SINT64:
                case FieldDescriptor::TYPE_FIXED64:
                case FieldDescriptor::TYPE_SFIXED64:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  (qlonglong)ref->GetInt64(msg, field));
                    break;

                case FieldDescriptor::TYPE_UINT32:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetUInt32(msg, field));
                    break;

                case FieldDescriptor::TYPE_UINT64:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  (qulonglong)ref->GetUInt64(msg, field));
                    break;

                case FieldDescriptor::TYPE_FLOAT:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetFloat(msg, field));
                    break;

                case FieldDescriptor::TYPE_DOUBLE:
                    item->setData(Column_Value, Qt::DisplayRole,
                                  ref->GetDouble(msg, field));
                    break;

                case FieldDescriptor::TYPE_BOOL:
                    item->setCheckState(Column_Value, ref->GetBool(msg, field)
                                                          ? Qt::Checked
                                                          : Qt::Unchecked);
                    break;

                case FieldDescriptor::TYPE_ENUM: {
                    const EnumValueDescriptor* ev = ref->GetEnum(msg, field);
                    item->setText(Column_Value,
                                  QString::fromStdString(ev->name()));
                    break;
                }

                case FieldDescriptor::TYPE_STRING:
                    item->setText(
                        Column_Value,
                        QString::fromStdString(ref->GetString(msg, field)));
                    break;

                case FieldDescriptor::TYPE_MESSAGE:
                    item->setData(Column_Tag, IsMessageRole, true);
                    newFields |= addTreeData(item, ref->GetMessage(msg, field));
                    break;

                case FieldDescriptor::TYPE_BYTES:
                    addBytes(item, ref->GetString(msg, field));
                    break;

                default:
                    item->setText(Column_Value,
                                  QString("??? %1").arg(field->type()));
                    break;
            }
    }

    return newFields;
}
示例#29
0
文件: JsonParser.cpp 项目: KDE/marble
bool JsonParser::read( QIODevice* device )
{
    // Assert previous document got released.
    delete m_document;
    m_document = new GeoDataDocument;
    Q_ASSERT( m_document );

    // Read file data
    QJsonParseError error;
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(device->readAll(), &error);

    if (jsonDoc.isNull()) {
        qDebug() << "Error parsing GeoJSON : " << error.errorString();
        return false;
    }

    // Start parsing
    const QJsonValue featuresValue = jsonDoc.object().value(QStringLiteral("features"));

    // In GeoJSON format, geometries are stored in features, so we iterate on features
    if (featuresValue.isArray()) {
        const QJsonArray featureArray = featuresValue.toArray();

        // Parse each feature
        for (int featureIndex = 0; featureIndex < featureArray.size(); ++featureIndex) {
            const QJsonObject featureObject = featureArray[featureIndex].toObject();

            // Check if the feature contains a geometry
            const QJsonValue geometryValue = featureObject.value(QStringLiteral("geometry"));
            if (geometryValue.isObject()) {
                const QJsonObject geometryObject = geometryValue.toObject();

                // Variables for creating the geometry
                QList<GeoDataGeometry*> geometryList;
                QList<GeoDataPlacemark*> placemarkList;

                // Create the different geometry types
                const QString geometryType = geometryObject.value(QStringLiteral("type")).toString().toUpper();

                if (geometryType == QLatin1String("POLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                        // Coordinates first array will be the outer boundary, if there are more
                        // positions those will be inner holes
                        for (int ringIndex = 0 ; ringIndex < coordinateArray.size(); ++ringIndex) {
                            const QJsonArray ringArray = coordinateArray[ringIndex].toArray();

                            GeoDataLinearRing linearRing;

                            for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }

                            // Outer ring
                            if (ringIndex == 0) {
                                geom->setOuterBoundary( linearRing );
                            }
                            // Inner holes
                            else {
                                geom->appendInnerBoundary( linearRing );
                            }
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTIPOLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int polygonIndex = 0; polygonIndex < coordinateArray.size(); ++polygonIndex) {
                            const QJsonArray polygonArray = coordinateArray[polygonIndex].toArray();

                            GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                            // Coordinates first array will be the outer boundary, if there are more
                            // positions those will be inner holes
                            for (int ringIndex = 0 ; ringIndex < polygonArray.size(); ++ringIndex) {
                                const QJsonArray ringArray = polygonArray[ringIndex].toArray();

                                GeoDataLinearRing linearRing;

                                for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                    const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                    const qreal longitude = coordinatePairArray.at(0).toDouble();
                                    const qreal latitude = coordinatePairArray.at(1).toDouble();

                                    linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                                }

                                // Outer ring
                                if (ringIndex == 0) {
                                    geom->setOuterBoundary( linearRing );
                                }
                                // Inner holes
                                else {
                                    geom->appendInnerBoundary( linearRing );
                                }
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("LINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                        for (int coordinatePairIndex = 0; coordinatePairIndex < coordinateArray.size(); ++coordinatePairIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[coordinatePairIndex].toArray();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTILINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int lineStringIndex = 0; lineStringIndex < coordinateArray.size(); ++lineStringIndex) {
                            const QJsonArray lineStringArray = coordinateArray[lineStringIndex].toArray();

                            GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                            for (int coordinatePairIndex = 0; coordinatePairIndex < lineStringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = lineStringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("POINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinatePairArray = coordinatesValue.toArray();

                        GeoDataPoint * geom = new GeoDataPoint();

                        const qreal longitude = coordinatePairArray.at(0).toDouble();
                        const qreal latitude = coordinatePairArray.at(1).toDouble();

                        geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                        geometryList.append( geom );
                    }
                } else if (geometryType == QLatin1String("MULTIPOINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int pointIndex = 0; pointIndex < coordinateArray.size(); ++pointIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[pointIndex].toArray();

                            GeoDataPoint * geom = new GeoDataPoint();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                            geometryList.append( geom );
                        }
                    }
                }


                // Parse the features properties
                const QJsonValue propertiesValue = featureObject.value(QStringLiteral("properties"));
                if (!geometryList.isEmpty() && propertiesValue.isObject()) {
                    const QJsonObject propertiesObject = propertiesValue.toObject();

                    // First create a placemark for each geometry, there could be multi geometries
                    // that are translated into more than one geometry/placemark
                    for ( int numberGeometries = 0 ; numberGeometries < geometryList.length() ; numberGeometries++ ) {
                        GeoDataPlacemark * placemark = new GeoDataPlacemark();
                        placemarkList.append( placemark );
                    }

                    OsmPlacemarkData osmData;

                    QJsonObject::ConstIterator it = propertiesObject.begin();
                    const QJsonObject::ConstIterator end = propertiesObject.end();
                    for ( ; it != end; ++it) {
                        if (it.value().isObject() || it.value().isArray()) {
                            qDebug() << "Skipping property, values of type arrays and objects not supported:" << it.key();
                            continue;
                        }

                        // pass value through QVariant to also get bool & numbers
                        osmData.addTag(it.key(), it.value().toVariant().toString());
                    }

                    // If the property read, is the features name
                    const auto tagIter = osmData.findTag(QStringLiteral("name"));
                    if (tagIter != osmData.tagsEnd()) {
                        const QString& name = tagIter.value();
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setName(name);
                        }
                    }

                    const GeoDataPlacemark::GeoDataVisualCategory category = StyleBuilder::determineVisualCategory(osmData);
                    if (category != GeoDataPlacemark::None) {
                        // Add the visual category to all the placemarks
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setVisualCategory(category);
                            placemarkList.at(pl)->setOsmData(osmData);
                        }
                    }
                }

                // Add the geometry to the document
                if ( geometryList.length() == placemarkList.length() ) {

                    while( placemarkList.length() > 0 ) {

                        GeoDataPlacemark * placemark = placemarkList.last();
                        placemarkList.pop_back();

                        GeoDataGeometry * geom = geometryList.last();
                        geometryList.pop_back();

                        placemark->setGeometry( geom );
                        placemark->setVisible( true );
                        m_document->append( placemark );
                    }
                }

                // If geometries or placemarks missing inside the lists, delete them
                qDeleteAll( geometryList.begin(), geometryList.end() );
                geometryList.clear();
                qDeleteAll( placemarkList.begin(), placemarkList.end() );
                placemarkList.clear();
            }
        }
    }
    return true;
}
示例#30
0
 void ProjectsModel::setupModelData(const QStringList &lines, ProjectsItem *parent)
 {
     QList<ProjectsItem*> parents;
     QList<QString> dirs;
     parents << parent;
     dirs << "rootihopenobodynamestheirdirectorythisinsanename";

	int number = 0;
	while (number < lines.count()-1) {
                // In conflicts we get three exactly same listing for files
                if(number) {
                    if(lines[number] == lines[number-1]) {
                        if(number > 1 && lines[number] == lines[number-2]) {
                            //Mark the original entry as conflict
                            parents.last()->child(parents.last()->childCount()-1)->status = MERGE_CONFLICT;
                        }
                        number++;
                        continue;
                    }
                }
		QStringList pathItems;
		pathItems << "rootihopenobodynamestheirdirectorythisinsanename";
		pathItems << lines[number].split("/");
		//Find out if pathItems parents and dir parents are same
		for(int j=1;j<dirs.size()||j<(pathItems.size()-1);j++) {
			if(j>=(pathItems.size()-1)) {
				//We found a partial path so pop back few parents
				for(int k=j;k<dirs.size();k++) {
					dirs.pop_back();
					parents.pop_back();
				}
				break;
			} else if(j>=dirs.size()) {
                                //We found addotional dir subchild(ren)
				for(int k=j;k<(pathItems.size()-1);k++) {
					dirs << pathItems[k];
					QList<QVariant> data;
					data << pathItems[k];
					parents.last()->appendChild(new ProjectsItem(data, parents.last()));
					parents << parents.last()->child(parents.last()->childCount()-1);
				}
				break;
			} else if(dirs[j] != pathItems[j]) {
				//pop remaining dirs and then add remaining paths items
				for(int k=j;k<=dirs.size();k++) {
					dirs.pop_back();
					parents.pop_back();
				}
				for(int k=j;k<(pathItems.size()-1);k++) {
					dirs << pathItems[k];
					QList<QVariant> data;
					data << pathItems[k];
					parents.last()->appendChild(new ProjectsItem(data, parents.last()));
					parents << parents.last()->child(parents.last()->childCount()-1);
				}
				break;
			}

		}
		//add the new child
		QList<QVariant> data2;
		data2 << pathItems.last();
		parents.last()->appendChild(new ProjectsItem(data2, parents.last()));

		number++;
	}

}