Beispiel #1
0
 int State::nextFree(const QSet<int>& lst, int id) const
 {
   while (lst.contains(id)) ++id;
   return id;
 }
Beispiel #2
0
void QgsWFSProjectParser::featureTypeList( QDomElement& parentElement, QDomDocument& doc ) const
{
  const QList<QDomElement>& projectLayerElements = mProjectParser->projectLayerElements();
  if ( projectLayerElements.size() < 1 )
  {
    return;
  }

  QStringList wfsLayersId = mProjectParser->wfsLayers();
  QSet<QString> wfstUpdateLayersId = wfstUpdateLayers();
  QSet<QString> wfstInsertLayersId = wfstInsertLayers();
  QSet<QString> wfstDeleteLayersId = wfstDeleteLayers();

  QMap<QString, QgsMapLayer *> layerMap;

  Q_FOREACH ( const QDomElement &elem, projectLayerElements )
  {
    QString type = elem.attribute( "type" );
    if ( type == "vector" )
    {
      QString layerId = mProjectParser->layerId( elem );
      if ( !wfsLayersId.contains( layerId ) )
      {
        continue;
      }
      QgsMapLayer *layer = mProjectParser->createLayerFromElement( elem );
      if ( !layer )
      {
        continue;
      }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
      if ( !mAccessControl->layerReadPermission( layer ) )
      {
        continue;
      }
#endif
      QgsDebugMsg( QString( "add layer %1 to map" ).arg( layer->id() ) );
      layerMap.insert( layer->id(), layer );

      QDomElement layerElem = doc.createElement( "FeatureType" );
      QDomElement nameElem = doc.createElement( "Name" );
      //We use the layer name even though it might not be unique.
      //Because the id sometimes contains user/pw information and the name is more descriptive
      QString typeName = layer->name();
      typeName = typeName.replace( " ", "_" );
      QDomText nameText = doc.createTextNode( typeName );
      nameElem.appendChild( nameText );
      layerElem.appendChild( nameElem );

      QDomElement titleElem = doc.createElement( "Title" );
      QString titleName = layer->title();
      if ( titleName.isEmpty() )
      {
        titleName = layer->name();
      }
      QDomText titleText = doc.createTextNode( titleName );
      titleElem.appendChild( titleText );
      layerElem.appendChild( titleElem );

      QDomElement abstractElem = doc.createElement( "Abstract" );
      QString abstractName = layer->abstract();
      if ( abstractName.isEmpty() )
      {
        abstractName = "";
      }
      QDomText abstractText = doc.createTextNode( abstractName );
      abstractElem.appendChild( abstractText );
      layerElem.appendChild( abstractElem );

      //keyword list
      if ( !layer->keywordList().isEmpty() )
      {
        QDomElement keywordsElem = doc.createElement( "Keywords" );
        QDomText keywordsText = doc.createTextNode( layer->keywordList() );
        keywordsElem.appendChild( keywordsText );
        layerElem.appendChild( keywordsElem );
      }

      //appendExGeographicBoundingBox( layerElem, doc, layer->extent(), layer->crs() );

      QDomElement srsElem = doc.createElement( "SRS" );
      QDomText srsText = doc.createTextNode( layer->crs().authid() );
      srsElem.appendChild( srsText );
      layerElem.appendChild( srsElem );

      //wfs:Operations element
      QDomElement operationsElement = doc.createElement( "Operations"/*wfs:Operations*/ );
      //wfs:Query element
      QDomElement queryElement = doc.createElement( "Query"/*wfs:Query*/ );
      operationsElement.appendChild( queryElement );

      QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( layer );
      QgsVectorDataProvider* provider = vlayer->dataProvider();
      if (( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) && wfstInsertLayersId.contains( layer->id() ) )
      {
        //wfs:Insert element
        QDomElement insertElement = doc.createElement( "Insert"/*wfs:Insert*/ );
        operationsElement.appendChild( insertElement );
      }
      if (( provider->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) &&
          ( provider->capabilities() & QgsVectorDataProvider::ChangeGeometries ) &&
          wfstUpdateLayersId.contains( layer->id() ) )
      {
        //wfs:Update element
        QDomElement updateElement = doc.createElement( "Update"/*wfs:Update*/ );
        operationsElement.appendChild( updateElement );
      }
      if (( provider->capabilities() & QgsVectorDataProvider::DeleteFeatures ) && wfstDeleteLayersId.contains( layer->id() ) )
      {
        //wfs:Delete element
        QDomElement deleteElement = doc.createElement( "Delete"/*wfs:Delete*/ );
        operationsElement.appendChild( deleteElement );
      }

      layerElem.appendChild( operationsElement );

      QgsRectangle layerExtent = layer->extent();
      QDomElement bBoxElement = doc.createElement( "LatLongBoundingBox" );
      bBoxElement.setAttribute( "minx", QString::number( layerExtent.xMinimum() ) );
      bBoxElement.setAttribute( "miny", QString::number( layerExtent.yMinimum() ) );
      bBoxElement.setAttribute( "maxx", QString::number( layerExtent.xMaximum() ) );
      bBoxElement.setAttribute( "maxy", QString::number( layerExtent.yMaximum() ) );
      layerElem.appendChild( bBoxElement );

      // layer metadata URL
      QString metadataUrl = layer->metadataUrl();
      if ( !metadataUrl.isEmpty() )
      {
        QDomElement metaUrlElem = doc.createElement( "MetadataURL" );
        QString metadataUrlType = layer->metadataUrlType();
        metaUrlElem.setAttribute( "type", metadataUrlType );
        QString metadataUrlFormat = layer->metadataUrlFormat();
        if ( metadataUrlFormat == "text/xml" )
        {
          metaUrlElem.setAttribute( "format", "XML" );
        }
        else
        {
          metaUrlElem.setAttribute( "format", "TXT" );
        }
        QDomText metaUrlText = doc.createTextNode( metadataUrl );
        metaUrlElem.appendChild( metaUrlText );
        layerElem.appendChild( metaUrlElem );
      }

      parentElement.appendChild( layerElem );
    }
  }
void PowerDevilRunner::match(Plasma::RunnerContext &context)
{
    const QString term = context.query();
    if (term.length() < m_shortestCommand) {
        return;
    }

    QList<Plasma::QueryMatch> matches;

    QString parameter;

    if (parseQuery(term,
                   QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "power profile %1", "(.*)"), Qt::CaseInsensitive)
                                    << QRegExp(i18nc("Note this is a KRunner keyword", "power profile"), Qt::CaseInsensitive),
                   parameter)) {
        for (StringStringMap::const_iterator i = m_availableProfiles.constBegin(); i != m_availableProfiles.constEnd(); ++i) {
            if (!parameter.isEmpty()) {
                if (!i.value().startsWith(parameter, Qt::CaseInsensitive)) {
                    continue;
                }
            }
            Plasma::QueryMatch match(this);
            match.setType(Plasma::QueryMatch::ExactMatch);
            match.setIcon(KIcon(m_profileIcon[i.key()]));
            match.setText(i18n("Set Profile to '%1'", i.value()));
            match.setData(i.key());
            match.setRelevance(1);
            match.setId("ProfileChange "+ i.key());
            matches.append(match);
        }
    } else if (parseQuery(term,
                          QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "screen brightness %1", "(.*)"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword", "screen brightness"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "dim screen %1", "(.*)"), Qt::CaseInsensitive)
                                           << QRegExp(i18nc("Note this is a KRunner keyword", "dim screen"), Qt::CaseInsensitive),
                          parameter)) {
        if (!parameter.isEmpty()) {
            bool test;
            int b = parameter.toInt(&test);
            if (test) {
                int brightness = qBound(0, b, 100);
                Plasma::QueryMatch match(this);
                match.setType(Plasma::QueryMatch::ExactMatch);
                match.setIcon(KIcon("preferences-system-power-management"));
                match.setText(i18n("Set Brightness to %1", brightness));
                match.setData(brightness);
                match.setRelevance(1);
                match.setId("BrightnessChange");
                matches.append(match);
            }
        } else {
            Plasma::QueryMatch match1(this);
            match1.setType(Plasma::QueryMatch::ExactMatch);
            match1.setIcon(KIcon("preferences-system-power-management"));
            match1.setText(i18n("Dim screen totally"));
            match1.setRelevance(1);
            match1.setId("DimTotal");
            matches.append(match1);

            Plasma::QueryMatch match2(this);
            match2.setType(Plasma::QueryMatch::ExactMatch);
            match2.setIcon(KIcon("preferences-system-power-management"));
            match2.setText(i18n("Dim screen by half"));
            match2.setRelevance(1);
            match2.setId("DimHalf");
            matches.append(match2);

            Plasma::QueryMatch match3(this);
            match3.setType(Plasma::QueryMatch::ExactMatch);
            match3.setIcon(KIcon("video-display"));
            match3.setText(i18n("Turn off screen"));
            match3.setRelevance(1);
            match3.setId("TurnOffScreen");
            matches.append(match3);
        }
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "suspend"), Qt::CaseInsensitive) == 0) {
        QSet< Solid::PowerManagement::SleepState > states = Solid::PowerManagement::supportedSleepStates();

        if (states.contains(Solid::PowerManagement::SuspendState)) {
            addSuspendMatch(Solid::PowerManagement::SuspendState, matches);
        }

        if (states.contains(Solid::PowerManagement::HibernateState)) {
            addSuspendMatch(Solid::PowerManagement::HibernateState, matches);
        }
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "sleep"), Qt::CaseInsensitive) == 0 ||
               term.compare(i18nc("Note this is a KRunner keyword", "to ram"), Qt::CaseInsensitive) == 0) {
        addSuspendMatch(Solid::PowerManagement::SuspendState, matches);
    } else if (term.compare(i18nc("Note this is a KRunner keyword", "hibernate"), Qt::CaseInsensitive) == 0 ||
               term.compare(i18nc("Note this is a KRunner keyword", "to disk"), Qt::CaseInsensitive) == 0) {
        addSuspendMatch(Solid::PowerManagement::HibernateState, matches);
    }

    if (!matches.isEmpty()) {
        context.addMatches(term, matches);
    }
}
bool SectionEditor::editDetailGroup(ReportSectionDetailGroup * rsdg)
{
    DetailGroupSectionDialog * dgsd = new DetailGroupSectionDialog(this);

    // add the current column and all columns not yet used for groups
    const QStringList keys = m_reportDesigner->fieldKeys();
    const QStringList columnNames = m_reportDesigner->fieldNames();
    // in case of to-be-added group that column needs to be added to the used
    const QSet<QString> usedColumns = groupingColumns() << rsdg->column();
    // if the current column is not among the keys, something is broken.
    // for now just simply select no column in the combobox, achieved by -1
    int indexOfCurrentColumn = -1;
    for (int i = 0; i < keys.count(); ++i) {
        const QString &key = keys.at(i);
        // skip any editor helper fields
        if (isEditorHelperField(key)) {
            continue;
        }
        // already used?
        if (usedColumns.contains(key)) {
            // and not the one of the group?
            if (key != rsdg->column()) {
                continue;
            }
            // remember index
            indexOfCurrentColumn = dgsd->cbColumn->count();
        }
        dgsd->cbColumn->insertItem( i, columnNames.value(i), key);
    }
    dgsd->cbColumn->setCurrentIndex(indexOfCurrentColumn);

    dgsd->cbSort->addItem(i18n("Ascending"), Qt::AscendingOrder);
    dgsd->cbSort->addItem(i18n("Descending"), Qt::DescendingOrder);
    dgsd->cbSort->setCurrentIndex(dgsd->cbSort->findData(rsdg->sort()));

    dgsd->breakAfterFooter->setChecked(rsdg->pageBreak() == ReportSectionDetailGroup::BreakAfterGroupFooter);
    dgsd->cbHead->setChecked(rsdg->groupHeaderVisible());
    dgsd->cbFoot->setChecked(rsdg->groupFooterVisible());

    const bool isOkayed = (dgsd->exec() == QDialog::Accepted);

    if (isOkayed) {
        const QString newColumn =
            dgsd->cbColumn->itemData(dgsd->cbColumn->currentIndex()).toString();
        const QString oldColumn = rsdg->column();
        if (newColumn != oldColumn) {
            rsdg->setColumn(newColumn);
        }

        rsdg->setGroupHeaderVisible(dgsd->cbHead->isChecked());
        rsdg->setGroupFooterVisible(dgsd->cbFoot->isChecked());

        const ReportSectionDetailGroup::PageBreak pageBreak = dgsd->breakAfterFooter->isChecked() ?
            ReportSectionDetailGroup::BreakAfterGroupFooter : ReportSectionDetailGroup::BreakNone;
        rsdg->setPageBreak(pageBreak);

        const Qt::SortOrder sortOrder =
            static_cast<Qt::SortOrder>(dgsd->cbSort->itemData(dgsd->cbSort->currentIndex()).toInt());
        rsdg->setSort(sortOrder);
    }

    delete dgsd;

    return isOkayed;
}
Beispiel #5
0
/*!
* Считать и построить дерево
* \param[in] xmlStream - покок чтения на вводный XML-файл
* \param[in] treeNum - номер дерева, которое считываются
* \param[out] root - указатель на корень входного дерева
*/
void readTree(QXmlStreamReader& xmlStream, node*& root, int treeNum){
	QXmlStreamAttributes attr;
	root = NULL;

	QSet<int> setOfData;
	// Размер дерева
	int treeSize = 0;

	// 1. Проверить верный ли идентификатор дерева. Если нет, то выбросить исключение (ошибка WRONG_TREE_ID)
	xmlStream.readNext();
	attr = xmlStream.attributes();
	QString treeID = attr.value("id").toString();
	if (treeNum == 1 && treeID != "1" || treeNum == 2 && treeID != "2")
		throw error(WRONG_TREE_ID, treeNum == 1 ? 1 : 2, treeID);
	xmlStream.readNext();
	// 2. Создать указатель current - указатель на текущую вершину
	node *current = NULL;

	// 3. Считать каждую вершину дерева с помощью функции readNode
	for (int cnt = 0;;){
		node* newNode = NULL;
		int newDepth;
		try{
			newDepth = readNode(xmlStream, treeNum, newNode);
		} catch (const error& e){
			// 3.1. Если возникла ошибка, то выбросить исключение
			throw;
		}

		// 3.2. Если новая вершина создана
		if (newDepth == 1){
			// 3.1.1. Увеличить размер дерева
			treeSize++;
			// 3.1.2. Если цифра новой вершины уже существует, то выбросить исключение (ошибка COINCIDED_NUMBERS)
			if (setOfData.contains(newNode->data))
				throw error(COINCIDED_NUMBERS, treeNum == 1 ? 1 : 2, QString::number(newNode->data));
			// 3.1.3. Добавить новую вершину в дерево, его родитель будет вершина current
			setOfData.insert(newNode->data);
			if (root == NULL)
				root = newNode;
			else
				current->addChild(newNode);
			// 3.1.4. Установить указатель current на новую вершину
			current = newNode;
			cnt++;
		} else 
		// 3.3. Иначе вернуть указатель current на его родителя
		if (newDepth == -1){
			if (current == NULL){
				xmlStream.readNext();
				return;
			}
			current = current->parent;
			cnt--;
		}

		// Если глубина текущей вершины равен 0, это показывает, что текущее дерево было прочитать
		// затем закончить читать текущее дерево
		if (cnt == 0){
			xmlStream.readNext();
			break;
		}
	}

	// 4. Проверить количество вершин дерева. Если превышает максимальный размер, то выбросить исключение (ошибка OVER_SIZE)
	if (treeSize > MAX_TREE_SIZE)
		throw error(OVER_SIZE, treeNum == 1 ? 1 : 2, QString::number(treeSize));

	xmlStream.readNext();
	xmlStream.readNext();
}
Beispiel #6
0
int main (){	
	QMap<int,QString> pos[25][25];
	char map[25][25];
	int testcases;
	scanf("%i\n", &testcases);
	for (int TC=1; TC<=testcases;TC++){
		for (int i=0;i<25;i++)
			for (int j=0;j<25;j++) {
				map[i][j]='\0';
				pos[i][j].clear();
			}
		int wide; int queries;
		QList<int> queryo;
		QSet<int> query;
		QMap<int, QString> res;
		scanf("%i %i\n",&wide,&queries);
		for (int i=1;i<=wide;i++)
			scanf("%s\n",&map[i][1]);
		for (int i=0;i<queries;i++) {
			int q;
			scanf("%i",&q);
			queryo << q;
			query << q;
		}
		scanf("\n");
		//for (int i=0;i<wide;i++) printf("check: %s\n",&map[i][0]);
		for (int i=1;i<=wide;i++)
			for (int j=1;j<=wide;j++) 
				if (map[i][j]>='0' && map[i][j]<='9') {
					pos[i][j].insert((int)(map[i][j]-'0'),QChar(map[i][j]));			
					if (query.contains((int)(map[i][j]-'0')) &&
						!res.contains((int)(map[i][j]-'0'))) 
						res.insert(map[i][j]-'0',QChar(map[i][j]));
				}
		while (res.size()!=query.size()) {
			//fprintf(stderr,"TEST\n");
			for (int i=1;i<=wide;i++)
				for (int j=1;j<=wide;j++) 
					if (map[i][j]=='+' || map[i][j]=='-') {
						for (int k=0;k<4;k++) {
							//fprintf(stderr,"  %i %i %i\n",i,j,k);
							QMap<int,QString>::iterator end=pos[i+dx[k]][j+dy[k]].end();
							for (QMap<int,QString>::iterator it=pos[i+dx[k]][j+dy[k]].begin(); it!=end; it++){
								int myval=it.key();
								if (myval > 1500 || myval<-1500) continue;
								if (map[i][j]=='-') myval-=2*(map[i+dx[k]][j+dy[k]]-'0');
								if (!pos[i][j].contains(myval) ||
									(newsolbetter(pos[i][j].value(myval),it.value()))) {
									pos[i][j].insert(myval,it.value());
								}
							}
						}
					}
			//fprintf(stderr,"TEST++\n");

			for (int i=1;i<=wide;i++)
				for (int j=1;j<=wide;j++) 
					if (map[i][j]>='0' && map[i][j]<='9') {
						for (int k=0;k<4;k++) {
							//fprintf(stderr,"   %i %i %i\n",i,j,k);
							QMap<int,QString>::iterator end=pos[i+dx[k]][j+dy[k]].end();
							for (QMap<int,QString>::iterator it=pos[i+dx[k]][j+dy[k]].begin(); it!=end; it++){
								int myval=(int)(map[i][j]-'0')+it.key();
								if (myval > 1500 || myval<-1500) continue;
								QString news = QString(QChar(map[i][j]))+
												QString(QChar(map[i+dx[k]][j+dy[k]]))+it.value();
								if (!pos[i][j].contains(myval) ||
									(newsolbetter(pos[i][j].value(myval),news))) {
									pos[i][j].insert(myval,news);
									//fprintf (stderr,"DEB: %i<-%s\n",myval,qPrintable(news));
									if (query.contains(myval) &&
										(!res.contains(myval) || (newsolbetter(res.value(myval),news)))){
										res.insert(myval,news);
										//fprintf (stderr,"DEBUG: %i<-%s\n",myval,qPrintable(news));
									}
								}
							}
						}
					}
		}
		printf("Case #%i:\n",TC);
		for (int i=0;i<queryo.size();i++)
			printf("%s\n",qPrintable(res.value(queryo[i])));
	}
	//std::cout << "test\n";
	return 0;
}
Beispiel #7
0
void SvgParser::applyFilter(KoShape *shape)
{
    SvgGraphicsContext *gc = m_context.currentGC();
    if (! gc)
        return;

    if (gc->filterId.isEmpty())
        return;

    SvgFilterHelper *filter = findFilter(gc->filterId);
    if (! filter)
        return;

    KoXmlElement content = filter->content();

    // parse filter region
    QRectF bound(shape->position(), shape->size());
    // work on bounding box without viewbox tranformation applied
    // so user space coordinates of bounding box and filter region match up
    bound = gc->viewboxTransform.inverted().mapRect(bound);

    QRectF filterRegion(filter->position(bound), filter->size(bound));

    // convert filter region to boundingbox units
    QRectF objectFilterRegion;
    objectFilterRegion.setTopLeft(SvgUtil::userSpaceToObject(filterRegion.topLeft(), bound));
    objectFilterRegion.setSize(SvgUtil::userSpaceToObject(filterRegion.size(), bound));

    KoFilterEffectLoadingContext context(m_context.xmlBaseDir());
    context.setShapeBoundingBox(bound);
    // enable units conversion
    context.enableFilterUnitsConversion(filter->filterUnits() == SvgFilterHelper::UserSpaceOnUse);
    context.enableFilterPrimitiveUnitsConversion(filter->primitiveUnits() == SvgFilterHelper::UserSpaceOnUse);

    KoFilterEffectRegistry *registry = KoFilterEffectRegistry::instance();

    KoFilterEffectStack *filterStack = 0;

    QSet<QString> stdInputs;
    stdInputs << "SourceGraphic" << "SourceAlpha";
    stdInputs << "BackgroundImage" << "BackgroundAlpha";
    stdInputs << "FillPaint" << "StrokePaint";

    QMap<QString, KoFilterEffect*> inputs;

    // create the filter effects and add them to the shape
    for (KoXmlNode n = content.firstChild(); !n.isNull(); n = n.nextSibling()) {
        KoXmlElement primitive = n.toElement();
        KoFilterEffect *filterEffect = registry->createFilterEffectFromXml(primitive, context);
        if (!filterEffect) {
            debugFlake << "filter effect" << primitive.tagName() << "is not implemented yet";
            continue;
        }

        const QString input = primitive.attribute("in");
        if (!input.isEmpty()) {
            filterEffect->setInput(0, input);
        }
        const QString output = primitive.attribute("result");
        if (!output.isEmpty()) {
            filterEffect->setOutput(output);
        }

        QRectF subRegion;
        // parse subregion
        if (filter->primitiveUnits() == SvgFilterHelper::UserSpaceOnUse) {
            const QString xa = primitive.attribute("x");
            const QString ya = primitive.attribute("y");
            const QString wa = primitive.attribute("width");
            const QString ha = primitive.attribute("height");

            if (xa.isEmpty() || ya.isEmpty() || wa.isEmpty() || ha.isEmpty()) {
                bool hasStdInput = false;
                bool isFirstEffect = filterStack == 0;
                // check if one of the inputs is a standard input
                foreach(const QString &input, filterEffect->inputs()) {
                    if ((isFirstEffect && input.isEmpty()) || stdInputs.contains(input)) {
                        hasStdInput = true;
                        break;
                    }
                }
                if (hasStdInput || primitive.tagName() == "feImage") {
                    // default to 0%, 0%, 100%, 100%
                    subRegion.setTopLeft(QPointF(0, 0));
                    subRegion.setSize(QSizeF(1, 1));
                } else {
                    // defaults to bounding rect of all referenced nodes
                    foreach(const QString &input, filterEffect->inputs()) {
                        if (!inputs.contains(input))
                            continue;

                        KoFilterEffect *inputFilter = inputs[input];
                        if (inputFilter)
                            subRegion |= inputFilter->filterRect();
                    }
                }
            } else {
                const qreal x = parseUnitX(xa);
                const qreal y = parseUnitY(ya);
                const qreal w = parseUnitX(wa);
                const qreal h = parseUnitY(ha);
                subRegion.setTopLeft(SvgUtil::userSpaceToObject(QPointF(x, y), bound));
                subRegion.setSize(SvgUtil::userSpaceToObject(QSizeF(w, h), bound));
            }
        } else {
Beispiel #8
0
void RowHeader::paint(QPainter* painter, const QRectF& painterRect)
{
    register Sheet * const sheet = m_pCanvas->activeSheet();
    if (!sheet)
        return;

//     ElapsedTime et( "Painting vertical header", ElapsedTime::PrintOnlyTime );

    // FIXME Stefan: Make use of clipping. Find the repaint call after the scrolling.
    // kDebug(36004) << event->rect();

    // painting rectangle
    const QRectF paintRect = m_pCanvas->zoomHandler()->viewToDocument(painterRect);

    // the painter
    painter->scale(m_pCanvas->zoomHandler()->zoomedResolutionX(), m_pCanvas->zoomHandler()->zoomedResolutionY());
    painter->setRenderHint(QPainter::TextAntialiasing);

    // fonts
    QFont normalFont(KoGlobal::defaultFont());
    QFont boldFont(normalFont);
    boldFont.setBold(true);

    // background brush/color
    const QBrush backgroundBrush(palette().window());
    const QColor backgroundColor(backgroundBrush.color());

    // selection brush/color
    QColor selectionColor(palette().highlight().color());
    selectionColor.setAlpha(127);
    const QBrush selectionBrush(selectionColor);

    painter->setClipRect(paintRect);

    double yPos;
    // Get the top row and the current y-position
    int y = sheet->topRow(paintRect.y() + m_pCanvas->yOffset(), yPos);
    // Align to the offset
    yPos = yPos - m_pCanvas->yOffset();

    const KoViewConverter *converter = m_pCanvas->zoomHandler();
    const double width = converter->viewToDocumentX(this->width() - 1);

    QSet<int> selectedRows;
    QSet<int> affectedRows;
    if (!m_pCanvas->selection()->referenceSelectionMode() && m_cellToolIsActive) {
        selectedRows = m_pCanvas->selection()->rowsSelected();
        affectedRows = m_pCanvas->selection()->rowsAffected();
    }
    // Loop through the rows, until we are out of range
    while (yPos <= paintRect.bottom() && y <= KS_rowMax) {
        const bool selected = (selectedRows.contains(y));
        const bool highlighted = (!selected && affectedRows.contains(y));

        if (sheet->rowFormats()->isHiddenOrFiltered(y)) {
            ++y;
            continue;
        }
        const double height = sheet->rowFormats()->rowHeight(y);

        if (selected || highlighted) {
            painter->setPen(selectionColor.dark(150));
            painter->setBrush(selectionBrush);
        } else {
            painter->setPen(backgroundColor.dark(150));
            painter->setBrush(backgroundBrush);
        }
        painter->drawRect(QRectF(0, yPos, width, height));

        QString rowText = QString::number(y);

        // Reset painter
        painter->setFont(normalFont);
        painter->setPen(palette().text().color());

        if (selected)
            painter->setPen(palette().highlightedText().color());
        else if (highlighted)
            painter->setFont(boldFont);

        const int ascent = painter->fontMetrics().ascent();
        if (height >= ascent - painter->fontMetrics().descent()) {
#if 0
            const double len = painter->fontMetrics().width(rowText);

            switch (y % 3) {
            case 0: rowText = QString::number(height) + 'h'; break;
            case 1: rowText = QString::number(painter.fontMetrics().ascent()) + 'a'; break;
            case 2: rowText = QString::number(painter.fontMetrics().descent()) + 'd'; break;
            }
            //kDebug() << "font height: " << painter.fontMetrics().ascent();
            painter.drawLine(1, yPos, 4, yPos + 3);
#endif
            drawText(painter,
                     painter->font(),
                     yPos + (height - ascent) / 2,
//                            yPos + ( height - painter.fontMetrics().ascent() - painter.fontMetrics().descent() ) / 2 ),
                     width,
                     rowText);
        }

        yPos += height;
        y++;
    }
}
Beispiel #9
0
void ColumnHeader::paint(QPainter* painter, const QRectF& painterRect)
{
    register Sheet * const sheet = m_pCanvas->activeSheet();
    if (!sheet)
        return;

//     ElapsedTime et( "Painting horizontal header", ElapsedTime::PrintOnlyTime );

    // FIXME Stefan: Make use of clipping. Find the repaint call after the scrolling.
    // kDebug(36004) << event->rect();

    // painting rectangle
    const QRectF paintRect = m_pCanvas->zoomHandler()->viewToDocument(painterRect);

    // the painter
    painter->scale(m_pCanvas->zoomHandler()->zoomedResolutionX(), m_pCanvas->zoomHandler()->zoomedResolutionY());
    painter->setRenderHint(QPainter::TextAntialiasing);

    // fonts
    QFont normalFont(KoGlobal::defaultFont());
    QFont boldFont(normalFont);
    boldFont.setBold(true);

    // background brush/color
    const QBrush backgroundBrush(palette().window());
    const QColor backgroundColor(backgroundBrush.color());

    // selection brush/color
    QColor selectionColor(palette().highlight().color());
    selectionColor.setAlpha(127);
    const QBrush selectionBrush(selectionColor);

    painter->setClipRect(paintRect);

    double xPos;
    int x;

    if (sheet->layoutDirection() == Qt::RightToLeft) {
        //Get the left column and the current x-position
        x = sheet->leftColumn(int(m_pCanvas->zoomHandler()->unzoomItX(width()) - paintRect.x() + m_pCanvas->xOffset()), xPos);
        //Align to the offset
        xPos = m_pCanvas->zoomHandler()->unzoomItX(width()) - xPos + m_pCanvas->xOffset();
    } else {
        //Get the left column and the current x-position
        x = sheet->leftColumn(int(paintRect.x() + m_pCanvas->xOffset()), xPos);
        //Align to the offset
        xPos = xPos - m_pCanvas->xOffset();
    }

    const KoViewConverter *converter = m_pCanvas->zoomHandler();
    const double height = converter->viewToDocumentY(this->height() - 1);

    if (sheet->layoutDirection() == Qt::RightToLeft) {
        if (x > KS_colMax)
            x = KS_colMax;

        xPos -= sheet->columnFormat(x)->width();

        QSet<int> selectedColumns;
        QSet<int> affectedColumns;
        if (!m_pCanvas->selection()->referenceSelectionMode() && m_cellToolIsActive) {
            selectedColumns = m_pCanvas->selection()->columnsSelected();
            affectedColumns = m_pCanvas->selection()->columnsAffected();
        }
        //Loop through the columns, until we are out of range
        while (xPos <= paintRect.right() && x <= KS_colMax) {
            bool selected = (selectedColumns.contains(x));
            bool highlighted = (!selected && affectedColumns.contains(x));

            const ColumnFormat* columnFormat = sheet->columnFormat(x);
            if (columnFormat->isHiddenOrFiltered()) {
                ++x;
                continue;
            }
            double width = columnFormat->width();

            if (selected || highlighted) {
                painter->setPen(selectionColor.dark(150));
                painter->setBrush(selectionBrush);
            } else {
                painter->setPen(backgroundColor.dark(150));
                painter->setBrush(backgroundBrush);
            }
            painter->drawRect(QRectF(xPos, 0, width, height));

            // Reset painter
            painter->setFont(normalFont);
            painter->setPen(palette().text().color());

            if (selected)
                painter->setPen(palette().highlightedText().color());
            else if (highlighted)
                painter->setFont(boldFont);

            QString colText = sheet->getShowColumnNumber() ? QString::number(x) : Cell::columnName(x);
            double len = painter->fontMetrics().width(colText);
            if (width >= len) {
                drawText(painter,
                         painter->font(),
                         QPointF(xPos,
                                 (height - painter->fontMetrics().ascent() - painter->fontMetrics().descent()) / 2),
                         colText,
                         width);
            }
            xPos += columnFormat->width();
            --x;
        }
    } else { // if ( sheet->layoutDirection() == Qt::LeftToRight )
        QSet<int> selectedColumns;
        QSet<int> affectedColumns;
        if (!m_pCanvas->selection()->referenceSelectionMode() && m_cellToolIsActive) {
            selectedColumns = m_pCanvas->selection()->columnsSelected();
            affectedColumns = m_pCanvas->selection()->columnsAffected();
        }
        //Loop through the columns, until we are out of range
        while (xPos <= paintRect.right() && x <= KS_colMax) {
            bool selected = (selectedColumns.contains(x));
            bool highlighted = (!selected && affectedColumns.contains(x));

            const ColumnFormat *columnFormat = sheet->columnFormat(x);
            if (columnFormat->isHiddenOrFiltered()) {
                ++x;
                continue;
            }
            double width = columnFormat->width();

            QColor backgroundColor = palette().window().color();

            if (selected || highlighted) {
                painter->setPen(selectionColor.dark(150));
                painter->setBrush(selectionBrush);
            } else {
                painter->setPen(backgroundColor.dark(150));
                painter->setBrush(backgroundBrush);
            }
            painter->drawRect(QRectF(xPos, 0, width, height));

            // Reset painter
            painter->setFont(normalFont);
            painter->setPen(palette().text().color());

            if (selected)
                painter->setPen(palette().highlightedText().color());
            else if (highlighted)
                painter->setFont(boldFont);

            QString colText = sheet->getShowColumnNumber() ? QString::number(x) : Cell::columnName(x);
            int len = painter->fontMetrics().width(colText);
            if (width >= len) {
#if 0
                switch (x % 3) {
                case 0: colText = QString::number(height) + 'h'; break;
                case 1: colText = QString::number(painter->fontMetrics().ascent()) + 'a'; break;
                case 2: colText = QString::number(painter->fontMetrics().descent()) + 'd'; break;
                }
#endif
                drawText(painter,
                         painter->font(),
                         QPointF(xPos,
                                 (height - painter->fontMetrics().ascent() - painter->fontMetrics().descent()) / 2),
                         colText,
                         width);
            }

            xPos += columnFormat->width();
            ++x;
        }
    }
}
void AsemanQtTools::registerTypes(const char *uri, bool exportMode)
{
    static QSet<QByteArray> register_list;
    if(register_list.contains(uri) && !exportMode)
        return;
    qRegisterMetaType<AsemanMimeData*>("AsemanMimeData*");

    registerType<AsemanMimeData>(uri, 1, 0, "MimeData", exportMode);
    registerType<AsemanDragObject>(uri, 1, 0, "DragObject", exportMode);
    registerType<AsemanHashObject>(uri, 1,0, "HashObject", exportMode);
    registerType<AsemanListObject>(uri, 1,0, "ListObject", exportMode);
    registerType<AsemanDownloader>(uri, 1,0, "Downloader", exportMode);
    registerType<AsemanEncrypter>(uri, 1,0, "Encrypter", exportMode);
#ifndef DISABLE_KEYCHAIN
    registerType<AsemanKeychain>(uri, 1,0, "Keychain", exportMode);
#endif
#ifdef QT_WIDGETS_LIB
    registerType<AsemanSystemTray>(uri, 1,0, "SystemTray", exportMode);
#endif
    registerType<AsemanWindowDetails>(uri, 1,0, "WindowDetails", exportMode);
    registerType<AsemanQuickObject>(uri, 1,0, "AsemanObject", exportMode);
    registerType<AsemanImageColorAnalizor>(uri, 1,0, "ImageColorAnalizor", exportMode);
    registerType<AsemanNotification>(uri, 1,0, "Notification", exportMode);
    registerType<AsemanAutoStartManager>(uri, 1,0, "AutoStartManager", exportMode);
    registerType<AsemanSettings>(uri, 1,0, "Settings", exportMode);
    registerType<AsemanStoreManager>(uri, 1,0, "StoreManager", exportMode);
    registerType<AsemanQuickItemImageGrabber>(uri, 1,0, "ItemImageGrabber", exportMode);
    registerType<AsemanFileDownloaderQueueItem>(uri, 1,0, "FileDownloaderQueueItem", exportMode);
    registerType<AsemanFileDownloaderQueue>(uri, 1,0, "FileDownloaderQueue", exportMode);
    registerType<AsemanFontHandler>(uri, 1,0, "FontHandler", exportMode);
    registerType<AsemanApplicationItem>(uri, 1,0, "AsemanApplication", exportMode);
    registerType<AsemanQmlSmartComponent>(uri, 1,0, "SmartComponentCore", exportMode);
#ifdef DESKTOP_LINUX
    registerType<AsemanMimeApps>(uri, 1,0, "MimeApps", exportMode);
#endif
    registerType<AsemanWebPageGrabber>(uri, 1,0, "WebPageGrabber", exportMode);
    registerType<AsemanHostChecker>(uri, 1,0, "HostChecker", exportMode);
    registerType<AsemanNetworkManager>(uri, 1,0, "NetworkManager", exportMode);
    registerType<AsemanNetworkSleepManager>(uri, 1,0, "NetworkSleepManager", exportMode);
    registerType<AsemanTitleBarColorGrabber>(uri, 1,0, "TitleBarColorGrabber", exportMode);
    registerType<AsemanTaskbarButton>(uri, 1,0, "TaskbarButton", exportMode);
    registerType<AsemanMapDownloader>(uri, 1,0, "MapDownloader", exportMode);
    registerType<AsemanDragArea>(uri, 1,0, "MouseDragArea", exportMode);
    registerType<AsemanCalendarModel>(uri, 1,0, "CalendarModel", exportMode);
#if defined(Q_OS_LINUX) && defined(QT_DBUS_LIB)
    registerType<AsemanKdeWallet>(uri, 1,0, "KdeWallet", exportMode);
#endif

#ifdef ASEMAN_SENSORS
    registerType<AsemanSensors>(uri, 1,0, "AsemanSensors", exportMode);
#endif
#ifdef ASEMAN_MULTIMEDIA
    registerType<AsemanAudioRecorder>(uri, 1,0, "AudioRecorder", exportMode);
    registerType<AsemanAudioEncoderSettings>(uri, 1,0, "AudioEncoderSettings", exportMode);
#endif

    registerModel<AsemanMixedListModel>(uri, 1,0, "MixedListModel", exportMode);
    registerModel<AsemanCountriesModel>(uri, 1,0, "CountriesModel", exportMode);
    registerModel<AsemanFileSystemModel>(uri, 1,0, "FileSystemModel", exportMode);
    registerModel<AsemanStoreManagerModel>(uri, 1,0, "StoreManagerModel", exportMode);
    registerModel<AsemanContributorsModel>(uri, 1,0, "ContributorsModel", exportMode);

    registerSingletonType<AsemanDevices>(uri, 1, 0, "Devices", aseman_devices_singleton, exportMode);
    registerSingletonType<AsemanTextTools>(uri, 1, 0, "TextTools", aseman_text_tools_singleton, exportMode);
    registerSingletonType<AsemanTools>(uri, 1, 0, "Tools", aseman_tools_singleton, exportMode);
    registerSingletonType<AsemanDesktopTools>(uri, 1, 0, "Desktop", aseman_desktoptools_singleton, exportMode);
    registerSingletonType<AsemanCalendarConverter>(uri, 1, 0, "CalendarConv", aseman_calendarconv_singleton, exportMode);
    registerSingletonType<AsemanBackHandler>(uri, 1, 0, "BackHandler", aseman_backhandler_singleton, exportMode);
    registerSingletonType<AsemanApplication>(uri, 1, 0, "AsemanApp", aseman_app_singleton, exportMode);
    registerSingletonType<AsemanQtLogger>(uri, 1, 0, "Logger", aseman_logger_singleton, exportMode);
    registerSingletonType<AsemanQuickViewWrapper>(uri, 1, 0, "View", aseman_qview_singleton, exportMode);
#ifdef Q_OS_ANDROID
    registerSingletonType<AsemanJavaLayer>(uri, 1, 0, "JavaLayer", aseman_javalayer_singleton, exportMode);
#endif

    registerUncreatableType<QScreen>(uri, 1, 0, "Screen", "", exportMode);
    registerUncreatableType<AsemanDesktopTools>(uri, 1,0, "AsemanDesktopTools", "It's a singleton class", exportMode);
    registerUncreatableType<AsemanNetworkManagerItem>(uri, 1,0, "NetworkManagerItem", "It must create using NetworkManager component.", exportMode);

    register_list.insert(uri);
}
Beispiel #11
0
void Song::processAutomations(const TrackList &tracklist, MidiTime timeStart, fpp_t)
{
	AutomatedValueMap values;

	QSet<const AutomatableModel*> recordedModels;

	TrackContainer* container = this;
	int tcoNum = -1;

	switch (m_playMode)
	{
	case Mode_PlaySong:
		break;
	case Mode_PlayBB:
	{
		Q_ASSERT(tracklist.size() == 1);
		Q_ASSERT(tracklist.at(0)->type() == Track::BBTrack);
		auto bbTrack = dynamic_cast<BBTrack*>(tracklist.at(0));
		auto bbContainer = Engine::getBBTrackContainer();
		container = bbContainer;
		tcoNum = bbTrack->index();
	}
		break;
	default:
		return;
	}

	values = container->automatedValuesAt(timeStart, tcoNum);
	TrackList tracks = container->tracks();

	Track::tcoVector tcos;
	for (Track* track : tracks)
	{
		if (track->type() == Track::AutomationTrack) {
			track->getTCOsInRange(tcos, 0, timeStart);
		}
	}

	// Process recording
	for (TrackContentObject* tco : tcos)
	{
		auto p = dynamic_cast<AutomationPattern *>(tco);
		MidiTime relTime = timeStart - p->startPosition();
		if (p->isRecording() && relTime >= 0 && relTime < p->length())
		{
			const AutomatableModel* recordedModel = p->firstObject();
			p->recordValue(relTime, recordedModel->value<float>());

			recordedModels << recordedModel;
		}
	}

	// Apply values
	for (auto it = values.begin(); it != values.end(); it++)
	{
		if (! recordedModels.contains(it.key()))
		{
			it.key()->setAutomatedValue(it.value());
		}
	}
}
Beispiel #12
0
void PeerListModel::updatePeers(const google::protobuf::RepeatedPtrField<Protos::GUI::State::Peer>& peers, const QSet<Common::Hash>& peersDownloadingOurData)
{
   Common::SortedArray<Peer*> peersToRemove = this->orderedPeers;
   QList<Peer*> peersToAdd;

   for (int i = 0; i < peers.size(); i++)
   {
      const Common::Hash peerID(peers.Get(i).peer_id().hash());
      const QString& nick = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::nick);
      const QString& coreVersion = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::core_version);
      const quint64 sharingAmount(peers.Get(i).sharing_amount());
      const TransferInformation transferInformation { peers.Get(i).download_rate(), peers.Get(i).upload_rate(),  peersDownloadingOurData.contains(peerID) };
      const QHostAddress ip =
         peers.Get(i).has_ip() ?
            Common::ProtoHelper::getIP(peers.Get(i).ip()) :
            QHostAddress();

      Peer* peer = this->indexedPeers[peerID];
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         peersToRemove.remove(peer);
         if (peer->nick != nick)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_NICK)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->nick = nick;
               peersToAdd << peer;
            }
            else
            {
               peer->nick = nick;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->sharingAmount != sharingAmount)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_SHARING_AMOUNT)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->sharingAmount = sharingAmount;
               peersToAdd << peer;
            }
            else
            {
               peer->sharingAmount = sharingAmount;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->transferInformation != transferInformation)
         {
            peer->transferInformation = transferInformation;
            emit dataChanged(this->createIndex(j, 0), this->createIndex(j, 0));
         }

         peer->ip = ip;
         peer->coreVersion = coreVersion;
      }
      else
      {
         peersToAdd << new Peer(peerID, nick, coreVersion, sharingAmount, ip, transferInformation);
      }
   }

   QList<Common::Hash> peerIDsRemoved;
   for (Common::SortedArray<Peer*>::Iterator i(peersToRemove); i.hasNext();)
   {
      Peer* const peer = i.next();
      peerIDsRemoved << peer->peerID;
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         this->beginRemoveRows(QModelIndex(), j, j);
         this->indexedPeers.remove(peer->peerID);
         this->orderedPeers.remove(peer);
         delete peer;
         this->endRemoveRows();
      }
   }

   if (!peerIDsRemoved.isEmpty())
      emit peersRemoved(peerIDsRemoved);

   for (QListIterator<Peer*> i(peersToAdd); i.hasNext();)
   {
      Peer* const peer = i.next();
      int pos = this->orderedPeers.insert(peer);
      this->beginInsertRows(QModelIndex(), pos, pos);
      this->indexedPeers.insert(peer->peerID, peer);
      this->endInsertRows();
   }
}
void MapController::botMove()
{
    int index;
    QSet<int> continuedMove;
    //continue the move
    index=0;
    while(index<botList.size())
    {
        if(botList.at(index).inMove)
        {
            if(!botMoveStepSlot(&botList[index]))
            {
                delete botList.at(index).mapObject;
                botList.removeAt(index);
                index--;
            }
            continuedMove << index;
        }
        index++;
    }
    //start move
    index=0;
    while(index<botList.size())
    {
        if(!botList.at(index).inMove && !continuedMove.contains(index))
        {
            QList<CatchChallenger::Direction> directions_allowed;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_left,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_left;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_right,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_right;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_top,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_top;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_bottom,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_bottom;
            if(directions_allowed.size()>0)
            {
                int random = rand()%directions_allowed.size();
                CatchChallenger::Direction final_direction=directions_allowed.at(random);

                botList[index].direction=final_direction;
                botList[index].inMove=true;
                botList[index].moveStep=1;
                switch(final_direction)
                {
                    case CatchChallenger::Direction_move_at_left:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_right:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_top:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_bottom:
                        botMoveStepSlot(&botList[index]);
                    break;
                    default:
                    qDebug() << QStringLiteral("transformLookToMove(): wrong direction");
                    return;
                }
            }
        }
        index++;
    }
}
Beispiel #14
0
QDomDocument QgsWFSServer::describeFeatureType()
{
  QgsDebugMsg( "Entering." );
  QDomDocument doc;
  //xsd:schema
  QDomElement schemaElement = doc.createElement( "schema"/*xsd:schema*/ );
  schemaElement.setAttribute( "xmlns", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" );
  schemaElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" );
  schemaElement.setAttribute( "xmlns:qgs", "http://www.qgis.org/gml" );
  schemaElement.setAttribute( "targetNamespace", "http://www.qgis.org/gml" );
  doc.appendChild( schemaElement );

  //xsd:import
  QDomElement importElement = doc.createElement( "import"/*xsd:import*/ );
  importElement.setAttribute( "namespace", "http://www.opengis.net/gml" );
  importElement.setAttribute( "schemaLocation", "http://schemas.opengis.net/gml/2.1.2/feature.xsd" );
  schemaElement.appendChild( importElement );

  //read TYPENAME
  QString typeName;
  QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" );
  if ( type_name_it != mParameterMap.end() )
  {
    typeName = type_name_it.value();
  }
  else
  {
    return doc;
  }

  QStringList wfsLayersId = mConfigParser->wfsLayers();
  QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
  QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();

  QList<QgsMapLayer*> layerList;
  QgsMapLayer* currentLayer = 0;

  layerList = mConfigParser->mapLayerFromStyle( typeName, "" );
  currentLayer = layerList.at( 0 );

  QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer );
  if ( layer && wfsLayersId.contains( layer->id() ) )
  {
    //is there alias info for this vector layer?
    QMap< int, QString > layerAliasInfo;
    QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
    if ( aliasIt != aliasInfo.constEnd() )
    {
      layerAliasInfo = aliasIt.value();
    }

    //hidden attributes for this layer
    QSet<QString> layerHiddenAttributes;
    QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
    if ( hiddenIt != hiddenAttributes.constEnd() )
    {
      layerHiddenAttributes = hiddenIt.value();
    }

    //do a select with searchRect and go through all the features
    QgsVectorDataProvider* provider = layer->dataProvider();
    if ( !provider )
    {
      return doc;
    }

    typeName = typeName.replace( QString( " " ), QString( "_" ) );

    //xsd:element
    QDomElement elementElem = doc.createElement( "element"/*xsd:element*/ );
    elementElem.setAttribute( "name", typeName );
    elementElem.setAttribute( "type", "qgs:" + typeName + "Type" );
    elementElem.setAttribute( "substitutionGroup", "gml:_Feature" );
    schemaElement.appendChild( elementElem );

    //xsd:complexType
    QDomElement complexTypeElem = doc.createElement( "complexType"/*xsd:complexType*/ );
    complexTypeElem.setAttribute( "name", typeName + "Type" );
    schemaElement.appendChild( complexTypeElem );

    //xsd:complexType
    QDomElement complexContentElem = doc.createElement( "complexContent"/*xsd:complexContent*/ );
    complexTypeElem.appendChild( complexContentElem );

    //xsd:extension
    QDomElement extensionElem = doc.createElement( "extension"/*xsd:extension*/ );
    extensionElem.setAttribute( "base", "gml:AbstractFeatureType" );
    complexContentElem.appendChild( extensionElem );

    //xsd:sequence
    QDomElement sequenceElem = doc.createElement( "sequence"/*xsd:sequence*/ );
    extensionElem.appendChild( sequenceElem );

    //xsd:element
    QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
    geomElem.setAttribute( "name", "geometry" );
    geomElem.setAttribute( "type", "gml:GeometryPropertyType" );
    geomElem.setAttribute( "minOccurs", "0" );
    geomElem.setAttribute( "maxOccurs", "1" );
    sequenceElem.appendChild( geomElem );

    const QgsFieldMap& fields = provider->fields();
    for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
    {

      QString attributeName = it.value().name();
      //skip attribute if it has edit type 'hidden'
      if ( layerHiddenAttributes.contains( attributeName ) )
      {
        continue;
      }

      //xsd:element
      QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
      geomElem.setAttribute( "name", attributeName );
      if ( it.value().type() == 2 )
        geomElem.setAttribute( "type", "integer" );
      else if ( it.value().type() == 6 )
        geomElem.setAttribute( "type", "double" );
      else
        geomElem.setAttribute( "type", "string" );

      sequenceElem.appendChild( geomElem );

      //check if the attribute name should be replaced with an alias
      QMap<int, QString>::const_iterator aliasIt = layerAliasInfo.find( it.key() );
      if ( aliasIt != layerAliasInfo.constEnd() )
      {
        geomElem.setAttribute( "alias", aliasIt.value() );
      }

    }
  }

  return doc;
}
GraphicsPortItem::GraphicsPortItem(GraphicsClientItemsClient *client_, const QString &fullPortName_, int style_, QFont font_, int padding, QGraphicsItem *parent) :
    QGraphicsPathItem(parent),
    client(client_),
    fullPortName(fullPortName_),
    shortPortName(fullPortName.split(":")[1]),
    dataType(client->getPortType(fullPortName)),
    isInput(client->getPortFlags(fullPortName) & JackPortIsInput),
    style(style_),
    font(font_),
    showMenu(false)
{
    bool gradient = false;
    QColor captionColor(0xfc, 0xf9, 0xc2);
    setPen(QPen(QBrush(Qt::black), 2));
    setBrush(QBrush(captionColor));
    setFlags(QGraphicsItem::ItemSendsScenePositionChanges);
    setCursor(Qt::ArrowCursor);
    font.setStyleStrategy(QFont::PreferAntialias);
    QFontMetrics fontMetrics(font);
    int portPadding = padding;

    QGraphicsSimpleTextItem *portTextItem = new QGraphicsSimpleTextItem(shortPortName, this);
    portTextItem->setFont(font);
    portTextItem->setPos(portPadding, 0);
    portRect = portTextItem->boundingRect().adjusted(-portPadding, -portPadding, portPadding, portPadding).translated(portTextItem->pos());

    QPainterPath portPath;
    if (style == 0) {
        portPath = portPath.united(EllipsePath(portRect));
    } else if (style == 1) {
        portPath = portPath.united(SpeechBubblePath(portRect, portRect.height() / 4, portRect.height() / 4, Qt::AbsoluteSize));
    } else if (style == 2) {
        portPath = portPath.united(RoundedRectanglePath(portRect, portPadding + fontMetrics.height() / 2, portPadding + fontMetrics.height() / 2));
    } else if (style == 3) {
        portPath = portPath.united(RectanglePath(portRect));
    }
    setPath(portPath);

    // register the port registration callback at the jack server:
    QObject::connect(client, SIGNAL(portRegistered(QString,QString,int)), this, SLOT(onPortRegistered(QString,QString,int)), Qt::QueuedConnection);
    QObject::connect(client, SIGNAL(portUnregistered(QString,QString,int)), this, SLOT(onPortUnregistered(QString,QString,int)), Qt::QueuedConnection);
    QObject::connect(client, SIGNAL(portConnected(QString,QString)), this, SLOT(onPortConnected(QString,QString)), Qt::QueuedConnection);
    QObject::connect(client, SIGNAL(portDisconnected(QString,QString)), this, SLOT(onPortDisconnected(QString,QString)), Qt::QueuedConnection);

    if (gradient) {
        QLinearGradient gradient(portRect.topLeft(), portRect.bottomRight());
        gradient.setColorAt(0, Qt::white);
        gradient.setColorAt(1, QColor("wheat"));
        setBrush(QBrush(gradient));
    }

    // create the context menu:
    connectMenu = contextMenu.addMenu("Connect");
    disconnectMenu = contextMenu.addMenu("Disconnect");
    // create the entries in connect- and disconnect-menus, as well as graphical representations of existing connections:
    QStringList connectedPorts = client->getConnectedPorts(fullPortName);
    QSet<QString> connectedPortsSet;
    for (int i = 0; i < connectedPorts.size(); i++) {
        // create an entry in the disconnect-menu:
        QAction *action = disconnectMenu->addAction(connectedPorts[i]);
        action->setData(connectedPorts[i]);
        QObject::connect(action, SIGNAL(triggered()), this, SLOT(onDisconnectAction()));
        mapPortNamesToActions[connectedPorts[i]] = action;
        connectedPortsSet.insert(connectedPorts[i]);
        // create a graphical representation of the connection:
        if (isInput) {
            client->getPortConnectionItem(connectedPorts[i], fullPortName)->setPos(fullPortName, getConnectionScenePos());
        } else {
            client->getPortConnectionItem(fullPortName, connectedPorts[i])->setPos(fullPortName, getConnectionScenePos());
        }
    }
    // get all available ports that can be connected to this:
    QStringList connectablePorts = client->getPorts(0, dataType.toAscii().data(), isInput ? JackPortIsOutput : JackPortIsInput);
    for (int i = 0; i < connectablePorts.size(); i++) {
        // skip ports that are already connected:
        if (!connectedPortsSet.contains(connectablePorts[i])) {
            // create an entry in the connect-menu:
            QAction *action = connectMenu->addAction(connectablePorts[i]);
            action->setData(connectablePorts[i]);
            QObject::connect(action, SIGNAL(triggered()), this, SLOT(onConnectAction()));
            mapPortNamesToActions[connectablePorts[i]] = action;
        }
    }
    disconnectMenu->setEnabled(disconnectMenu->actions().size());
    connectMenu->setEnabled(connectMenu->actions().size());
}
Beispiel #16
0
bool reducesToEpsilon(Model::Node *node, QSet<Model::Node*>& v)
{
  if (node == 0)
    return true;
  if (v.contains(node))
    return true;
  v.insert(node);
  if (Model::ConsItem *c = nodeCast<Model::ConsItem*>(node))
    {
      return reducesToEpsilon(c->mLeft, v) && reducesToEpsilon(c->mRight, v);
    }
  else if (nodeCast<Model::OperatorItem*>(node))
    {
      return false;
    }
  else if (Model::AlternativeItem *a = nodeCast<Model::AlternativeItem*>(node))
    {
      return reducesToEpsilon(a->mLeft, v) || reducesToEpsilon(a->mRight, v);
    }
  else if (Model::ActionItem *a = nodeCast<Model::ActionItem*>(node))
    {
      if(a->mItem)
        return reducesToEpsilon(a->mItem, v);
      else
        return true;
    }
  else if (Model::ConditionItem *c = nodeCast<Model::ConditionItem*>(node))
    {
      return reducesToEpsilon(c->mItem, v);
    }
  else if (Model::TryCatchItem *t = nodeCast<Model::TryCatchItem*>(node))
    {
      return reducesToEpsilon(t->mTryItem, v)
             || (t->mCatchItem && reducesToEpsilon(t->mCatchItem, v));
    }
  else if (Model::AnnotationItem *a = nodeCast<Model::AnnotationItem*>(node))
    {
      return reducesToEpsilon(a->mItem, v);
    }
  else if (Model::NonTerminalItem *n = nodeCast<Model::NonTerminalItem*>(node))
    {
      return reducesToEpsilon(n->mSymbol, v);
    }
  else if (Model::InlinedNonTerminalItem *n = nodeCast<Model::InlinedNonTerminalItem*>(node))
    {
      return reducesToEpsilon(n->mSymbol, v);
    }
  else if (Model::SymbolItem *s = nodeCast<Model::SymbolItem*>(node))
    {
      return globalSystem.first(s).find(globalSystem.zero()) != globalSystem.first(s).end(); // hmm
    }
  else if (Model::PlusItem *p = nodeCast<Model::PlusItem*>(node))
    {
      return reducesToEpsilon(p->mItem, v);
    }
  else if (nodeCast<Model::StarItem*>(node))
    {
      return true;
    }
  else if (nodeCast<Model::ZeroItem*>(node))
    {
      return true;
    }

  return false;
}
Beispiel #17
0
void KTreeWidgetPrivate::doLayout()
{
	Q_Q(KTreeWidget);

	if(m_itemsTree.isEmpty())
	{
		/*直接回收所有资源,并返回。*/
		QHash<qint64, QPointer<KTreeItem>> items = m_widgetItems;
		m_widgetItems.clear();
		m_indexWidgetItemBegin = 0;
		int iLeft = 0;
		for(QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin(); iter != items.end(); iter++,iLeft++)
		{
			KTreeItem *pli = iter.value();
			if(iLeft <= 3)
			{
				m_creator->recycle(pli);
				pli->hide();
			}
			else
			{
				delete pli;
			}
		}
		return;
	}
	/*至少有一个元素。*/
	//显示在列表中的第一个Item
	//计算下边框是否隐藏为列表可见区的第一项。
	qreal itemPosVisibleFirst = -m_valueCurrentScroll;
	int itemIdxFirst = 0;
	calcLayoutFirstItem(itemIdxFirst, itemPosVisibleFirst, 0, m_itemsTree.size());
	//最后一个元素显示在列表中的。
	//计算上边框是否隐藏来判断是否为列表可见区中最后一项
	qreal itemPosVisibleLast = itemPosVisibleFirst;
	int itemIdxLast = m_itemsTree.count() - 1;
	for(int i = itemIdxFirst; i < m_itemsTree.count(); i++)
	{
		if(itemPosVisibleLast + m_heightItem > m_contentArea.bottom())
		{
			itemIdxLast = i;
			break;
		}
		else
		{
			itemPosVisibleLast += m_heightItem;
		}
	}
	QHash<qint64, QPointer<KTreeItem>> items = m_widgetItems;
	m_widgetItems.clear();
	m_indexWidgetItemBegin = itemIdxFirst;

	/*处理已经重复的对象*/
	bool bdepth = m_styleTree & KTreeWidget::HasBranch;
	qreal itemPosVisible = itemPosVisibleFirst;
	QSet<int> itemsok;
	for(int i = itemIdxFirst; !items.isEmpty() && i <= itemIdxLast; i++)
	{
		qint64 nodeid = m_itemsTree.at(i);
		KTreeItem *pli = items.take(nodeid);
		if(pli == NULL)
		{
			itemPosVisible += m_heightItem;
			continue;
		}
		QRectF itemRt;
		itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightItem);
		itemPosVisible += m_heightItem;
		QMargins margins = m_itemMargins;
		if(bdepth)
		{
			int ndepth = m_model->nodeDepth(nodeid);
			ndepth *= m_depthIndentation;
			margins = QMargins(m_itemMargins.left() + ndepth, m_itemMargins.top(), m_itemMargins.right(), m_itemMargins.bottom());
		}
		pli->setMargins(margins);
		pli->setGeometry(itemRt);
		pli->setFixSize(itemRt.size());
		if(nodeid == m_nodeIdSelect)
		{
			pli->setSelected(m_variantSelected);
		}
		else if(pli->isUnderMouse())
		{
			pli->setHovered(m_variantHovered);
		}
		else
		{
			pli->setUnselected(m_variantUnselect);
		}
		pli->show();
		m_widgetItems.insert(nodeid, pli);
		itemsok.insert(i);
	}

	/*处理没有设置的对象。*/
	itemPosVisible = itemPosVisibleFirst;
	for(int i = itemIdxFirst; i <= itemIdxLast; i++)
	{
		if(itemsok.contains(i))
		{
			itemPosVisible += m_heightItem;
			continue;
		}
		qint64 nodeid = m_itemsTree.at(i);
		KTreeItem *pli = NULL;
		if(items.isEmpty())
		{
			pli = m_creator->create(q);
		}
		else
		{
			QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin();
			pli = iter.value();
			items.erase(iter);
		}
		QRectF itemRt;
		itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightItem);
		itemPosVisible += m_heightItem;
		pli->resetNodeId(nodeid);
		QMargins margins = m_itemMargins;
		if(bdepth)
		{
			int ndepth = m_model->nodeDepth(nodeid);
			ndepth *= m_depthIndentation;
			margins = QMargins(m_itemMargins.left() + ndepth, m_itemMargins.top(), m_itemMargins.right(), m_itemMargins.bottom());
		}
		pli->setMargins(margins);
		pli->setGeometry(itemRt);
		pli->setFixSize(itemRt.size());
		if(nodeid == m_nodeIdSelect)
		{
			pli->setSelected(m_variantSelected);
		}
		else if(pli->isUnderMouse())
		{
			pli->setHovered(m_variantHovered);
		}
		else
		{
			pli->setUnselected(m_variantUnselect);
		}
		pli->show();
		m_widgetItems.insert(nodeid, pli);
	}

	int iLeft = 0;
	for(QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin(); iter != items.end(); iter++,iLeft++)
	{
		KTreeItem *pli = iter.value();
		if(iLeft <= 3)
		{
			m_creator->recycle(pli);
			pli->hide();
		}
		else
		{
			delete pli;
		}
	}
}
Beispiel #18
0
QList<CatItem> Catalog::expandStubs(QString userKeys, QList<CatItem>* inList){

    QList<CatItem> stubs; QList<CatItem> oldStubs;
    QList<CatItem>* workingList = inList;
    QList<CatItem> res;
    bool refreshNeeded =false;
    int rep=0;

    QSet<QString> updated;
    while((workingList->length()>0)) {
        cat_store.beginAddGroup();
        for(int i=0; i<workingList->count();i++){
            CatItem toAdd = workingList->at(i);
            bool atStub = toAdd.isStub();
            if(plugins.itemLoading(&toAdd, UserEvent::BECOMING_VISIBLE)){
                if(toAdd.isForDelete()) {
                    cat_store.removeItem(workingList->at(i));
                    continue;
                }
                if(atStub) {
                    refreshNeeded = true;
                    //toAdd.setStub(false);
                    cat_store.addItemInGroup(toAdd);
                }
            }
            QList<CatItem> newStubs = extractStubs(toAdd);
            for(int j=0; j<newStubs.count(); j++){
                if(!updated.contains(newStubs[j].getPath())){
                    updated.insert(newStubs[j].getPath());
                    stubs.append(newStubs[j]);
                }
            }
        }
        oldStubs = stubs;
        workingList = &oldStubs;
        cat_store.endAddGroup();
        stubs.clear();
        Q_ASSERT(workingList->count() <1000);
        rep++;
        Q_ASSERT(rep<10);
    }

    cat_store.beginAddGroup();
    for(int i=0; i<inList->count();i++){
        CatItem toAdd = inList->at(i);
        if(toAdd.isForDBInsertOnly()){
            cat_store.addItemInGroup(toAdd);
            continue;
        }
        if(userKeys.isEmpty() || matches(&toAdd, userKeys) || toAdd.getTakesAnykeys()) {
            if(refreshNeeded){
                CatItem refreshed = cat_store.getItemByPath(toAdd.getPath());
                if(!refreshed.isEmpty()){
                    toAdd.mergeItem(refreshed,true);
                }
                toAdd.setMatchIndex(QList<int>());
            }
            if(!toAdd.hasLabel(BUILTIN))
                { res.append(toAdd);}
        }}
    cat_store.endAddGroup();
    return res;
}
Beispiel #19
0
/**
 * Shows the context menu for map objects. The menu allows you to duplicate and
 * remove the map objects, or to edit their properties.
 */
void AbstractObjectTool::showContextMenu(MapObjectItem *clickedObjectItem,
                                         QPoint screenPos)
{
    QSet<MapObjectItem *> selection = mMapScene->selectedObjectItems();
    if (clickedObjectItem && !selection.contains(clickedObjectItem)) {
        selection.clear();
        selection.insert(clickedObjectItem);
        mMapScene->setSelectedObjectItems(selection);
    }
    if (selection.isEmpty())
        return;

    const QList<MapObject*> &selectedObjects = mapDocument()->selectedObjects();
    const QList<ObjectGroup*> objectGroups = mapDocument()->map()->objectGroups();

    QMenu menu;
    QAction *duplicateAction = menu.addAction(tr("Duplicate %n Object(s)", "", selection.size()),
                                              this, SLOT(duplicateObjects()));
    QAction *removeAction = menu.addAction(tr("Remove %n Object(s)", "", selection.size()),
                                           this, SLOT(removeObjects()));

    duplicateAction->setIcon(QIcon(QLatin1String(":/images/16x16/stock-duplicate-16.png")));
    removeAction->setIcon(QIcon(QLatin1String(":/images/16x16/edit-delete.png")));

    bool anyTileObjectSelected = std::any_of(selectedObjects.begin(),
                                             selectedObjects.end(),
                                             isTileObject);

    if (anyTileObjectSelected) {
        auto resetTileSizeAction = menu.addAction(tr("Reset Tile Size"), this, SLOT(resetTileSize()));
        resetTileSizeAction->setEnabled(std::any_of(selectedObjects.begin(),
                                                    selectedObjects.end(),
                                                    isResizedTileObject));
    }

    menu.addSeparator();
    menu.addAction(tr("Flip Horizontally"), this, SLOT(flipHorizontally()), QKeySequence(tr("X")));
    menu.addAction(tr("Flip Vertically"), this, SLOT(flipVertically()), QKeySequence(tr("Y")));

    ObjectGroup *objectGroup = RaiseLowerHelper::sameObjectGroup(selection);
    if (objectGroup && objectGroup->drawOrder() == ObjectGroup::IndexOrder) {
        menu.addSeparator();
        menu.addAction(tr("Raise Object"), this, SLOT(raise()), QKeySequence(tr("PgUp")));
        menu.addAction(tr("Lower Object"), this, SLOT(lower()), QKeySequence(tr("PgDown")));
        menu.addAction(tr("Raise Object to Top"), this, SLOT(raiseToTop()), QKeySequence(tr("Home")));
        menu.addAction(tr("Lower Object to Bottom"), this, SLOT(lowerToBottom()), QKeySequence(tr("End")));
    }

    if (objectGroups.size() > 1) {
        menu.addSeparator();
        QMenu *moveToLayerMenu = menu.addMenu(tr("Move %n Object(s) to Layer",
                                                 "", selectedObjects.size()));
        for (ObjectGroup *objectGroup : objectGroups) {
            QAction *action = moveToLayerMenu->addAction(objectGroup->name());
            action->setData(QVariant::fromValue(objectGroup));
        }
    }

    menu.addSeparator();
    QIcon propIcon(QLatin1String(":images/16x16/document-properties.png"));
    QAction *propertiesAction = menu.addAction(propIcon,
                                               tr("Object &Properties..."));

    Utils::setThemeIcon(removeAction, "edit-delete");
    Utils::setThemeIcon(propertiesAction, "document-properties");

    QAction *action = menu.exec(screenPos);
    if (!action)
        return;

    if (action == propertiesAction) {
        MapObject *mapObject = selectedObjects.first();
        mapDocument()->setCurrentObject(mapObject);
        mapDocument()->emitEditCurrentObject();
        return;
    }

    if (ObjectGroup *objectGroup = action->data().value<ObjectGroup*>()) {
        mapDocument()->moveObjectsToGroup(mapDocument()->selectedObjects(),
                                          objectGroup);
    }
}
Beispiel #20
0
bool OnlineService::showLogoAsCover(const Song &s)
{
    return s.isFromOnlineService() && !servicesWithCovers.contains(s.onlineService())
           && (!servicesWithCoversIfCached.contains(s.onlineService()) || s.extraField(Song::OnlineImageCacheName).isEmpty());
}
void tst_QScriptValueGenerated::isError_makeData(const char* expr)
{
    static QSet<QString> isError =
        charArrayToQStringSet(isError_array, int(sizeof(isError_array) / sizeof(const char *)));
    newRow(expr) << isError.contains(expr);
}
bool OsmAnd::BinaryMapDataProvider_P::obtainData(
    const TileId tileId,
    const ZoomLevel zoom,
    std::shared_ptr<MapTiledData>& outTiledData,
    BinaryMapDataProvider_Metrics::Metric_obtainData* const metric_,
    const IQueryController* const queryController)
{
#if OSMAND_PERFORMANCE_METRICS
    BinaryMapDataProvider_Metrics::Metric_obtainData localMetric;
    const auto metric = metric_ ? metric_ : &localMetric;
#else
    const auto metric = metric_;
#endif

    std::shared_ptr<TileEntry> tileEntry;

    for (;;)
    {
        // Try to obtain previous instance of tile
        _tileReferences.obtainOrAllocateEntry(tileEntry, tileId, zoom,
            []
            (const TiledEntriesCollection<TileEntry>& collection, const TileId tileId, const ZoomLevel zoom) -> TileEntry*
            {
                return new TileEntry(collection, tileId, zoom);
            });

        // If state is "Undefined", change it to "Loading" and proceed with loading
        if (tileEntry->setStateIf(TileState::Undefined, TileState::Loading))
            break;

        // In case tile entry is being loaded, wait until it will finish loading
        if (tileEntry->getState() == TileState::Loading)
        {
            QReadLocker scopedLcoker(&tileEntry->_loadedConditionLock);

            // If tile is in 'Loading' state, wait until it will become 'Loaded'
            while (tileEntry->getState() != TileState::Loaded)
                REPEAT_UNTIL(tileEntry->_loadedCondition.wait(&tileEntry->_loadedConditionLock));
        }

        // Try to lock tile reference
        outTiledData = tileEntry->_tile.lock();

        // If successfully locked, just return it
        if (outTiledData)
            return true;

        // Otherwise consider this tile entry as expired, remove it from collection (it's safe to do that right now)
        // This will enable creation of new entry on next loop cycle
        _tileReferences.removeEntry(tileId, zoom);
        tileEntry.reset();
    }

    const Stopwatch totalTimeStopwatch(
#if OSMAND_PERFORMANCE_METRICS
        true
#else
        metric != nullptr
#endif // OSMAND_PERFORMANCE_METRICS
        );

    // Obtain OBF data interface
    const Stopwatch obtainObfInterfaceStopwatch(metric != nullptr);
    const auto& dataInterface = owner->obfsCollection->obtainDataInterface();
    if (metric)
        metric->elapsedTimeForObtainingObfInterface += obtainObfInterfaceStopwatch.elapsed();

    // Get bounding box that covers this tile
    const auto tileBBox31 = Utilities::tileBoundingBox31(tileId, zoom);

    // Perform read-out
    const Stopwatch totalReadTimeStopwatch(metric != nullptr);
    QList< std::shared_ptr< const ObfMapSectionReader::DataBlock > > referencedMapDataBlocks;
    QList< std::shared_ptr<const Model::BinaryMapObject> > referencedMapObjects;
    QList< proper::shared_future< std::shared_ptr<const Model::BinaryMapObject> > > futureReferencedMapObjects;
    QList< std::shared_ptr<const Model::BinaryMapObject> > loadedMapObjects;
    QSet< uint64_t > loadedSharedMapObjects;
    auto tileFoundation = MapFoundationType::Undefined;
    dataInterface->loadMapObjects(
        &loadedMapObjects,
        &tileFoundation,
        zoom,
        &tileBBox31,
        [this, zoom, &referencedMapObjects, &futureReferencedMapObjects, &loadedSharedMapObjects, tileBBox31, metric]
        (const std::shared_ptr<const ObfMapSectionInfo>& section, const uint64_t id, const AreaI& bbox, const ZoomLevel firstZoomLevel, const ZoomLevel lastZoomLevel) -> bool
        {
            const Stopwatch objectsFilteringStopwatch(metric != nullptr);

            // This map object may be shared only in case it crosses bounds of a tile
            const auto canNotBeShared = tileBBox31.contains(bbox);

            // If map object can not be shared, just read it
            if (canNotBeShared)
            {
                if (metric)
                    metric->elapsedTimeForObjectsFiltering += objectsFilteringStopwatch.elapsed();

                return true;
            }

            // Otherwise, this map object can be shared, so it should be checked for
            // being present in shared mapObjects storage, or be reserved there
            std::shared_ptr<const Model::BinaryMapObject> sharedMapObjectReference;
            proper::shared_future< std::shared_ptr<const Model::BinaryMapObject> > futureSharedMapObjectReference;
            if (_sharedMapObjects.obtainReferenceOrFutureReferenceOrMakePromise(id, zoom, Utilities::enumerateZoomLevels(firstZoomLevel, lastZoomLevel), sharedMapObjectReference, futureSharedMapObjectReference))
            {
                if (sharedMapObjectReference)
                {
                    // If map object is already in shared objects cache and is available, use that one
                    referencedMapObjects.push_back(qMove(sharedMapObjectReference));
                }
                else
                {
                    futureReferencedMapObjects.push_back(qMove(futureSharedMapObjectReference));
                }

                if (metric)
                    metric->elapsedTimeForObjectsFiltering += objectsFilteringStopwatch.elapsed();

                return false;
            }

            // This map object was reserved, and is going to be shared, but needs to be loaded
            loadedSharedMapObjects.insert(id);
            return true;
        },
        _dataBlocksCache.get(),
        &referencedMapDataBlocks,
        nullptr,// query controller
        metric ? &metric->loadMapObjectsMetric : nullptr);

    // Process loaded-and-shared map objects
    for (auto& mapObject : loadedMapObjects)
    {
        // Check if this map object is shared
        if (!loadedSharedMapObjects.contains(mapObject->id))
            continue;

        // Add unique map object under lock to all zoom levels, for which this map object is valid
        assert(mapObject->level);
        _sharedMapObjects.fulfilPromiseAndReference(
            mapObject->id,
            Utilities::enumerateZoomLevels(mapObject->level->minZoom, mapObject->level->maxZoom),
            mapObject);
    }

    for (auto& futureMapObject : futureReferencedMapObjects)
    {
        auto mapObject = futureMapObject.get();

        referencedMapObjects.push_back(qMove(mapObject));
    }

    if (metric)
        metric->elapsedTimeForRead += totalReadTimeStopwatch.elapsed();

    // Prepare data for the tile
    const auto sharedMapObjectsCount = referencedMapObjects.size() + loadedSharedMapObjects.size();
    const auto allMapObjects = loadedMapObjects + referencedMapObjects;

    // Create tile
    const std::shared_ptr<BinaryMapDataTile> newTile(new BinaryMapDataTile(
        _dataBlocksCache,
        referencedMapDataBlocks,
        tileFoundation,
        allMapObjects,
        tileId,
        zoom));
    newTile->_p->_weakLink = _link->getWeak();
    newTile->_p->_refEntry = tileEntry;

    // Publish new tile
    outTiledData = newTile;

    // Store weak reference to new tile and mark it as 'Loaded'
    tileEntry->_tile = newTile;
    tileEntry->setState(TileState::Loaded);

    // Notify that tile has been loaded
    {
        QWriteLocker scopedLcoker(&tileEntry->_loadedConditionLock);
        tileEntry->_loadedCondition.wakeAll();
    }

    if (metric)
    {
        metric->elapsedTime += totalTimeStopwatch.elapsed();
        metric->objectsCount += allMapObjects.size();
        metric->uniqueObjectsCount += allMapObjects.size() - sharedMapObjectsCount;
        metric->sharedObjectsCount += sharedMapObjectsCount;
    }

#if OSMAND_PERFORMANCE_METRICS
#if OSMAND_PERFORMANCE_METRICS <= 1
    LogPrintf(LogSeverityLevel::Info,
        "%d map objects (%d unique, %d shared) read from %dx%d@%d in %fs",
        allMapObjects.size(),
        allMapObjects.size() - sharedMapObjectsCount,
        sharedMapObjectsCount,
        tileId.x,
        tileId.y,
        zoom,
        totalTimeStopwatch.elapsed());
#else
    LogPrintf(LogSeverityLevel::Info,
        "%d map objects (%d unique, %d shared) read from %dx%d@%d in %fs:\n%s",
        allMapObjects.size(),
        allMapObjects.size() - sharedMapObjectsCount,
        sharedMapObjectsCount,
        tileId.x,
        tileId.y,
        zoom,
        totalTimeStopwatch.elapsed(),
        qPrintable(metric ? metric->toString(QLatin1String("\t - ")) : QLatin1String("(null)")));
#endif // OSMAND_PERFORMANCE_METRICS <= 1
#endif // OSMAND_PERFORMANCE_METRICS

    return true;
}
Beispiel #23
0
void JSHighlighter::highlightBlock(const QString &text)
{
    // parsing state
    enum {
        Start = 0,
        Number = 1,
        Identifier = 2,
        String = 3,
        Comment = 4,
        Regex = 5
    };

    QList<int> bracketPositions;

    int blockState = previousBlockState();
    int bracketLevel = blockState >> 4;
    int state = blockState & 15;
    if (blockState < 0) {
        bracketLevel = 0;
        state = Start;
    }

    int start = 0;
    int i = 0;
    while (i <= text.length()) {
        QChar ch = (i < text.length()) ? text.at(i) : QChar();
        QChar next = (i < text.length() - 1) ? text.at(i + 1) : QChar();

        switch (state) {

        case Start:
            start = i;
            if (ch.isSpace()) {
                ++i;
            } else if (ch.isDigit()) {
                ++i;
                state = Number;
            } else if (ch.isLetter() || ch == '_') {
                ++i;
                state = Identifier;
            } else if (ch == '\'' || ch == '\"') {
                ++i;
                state = String;
            } else if (ch == '/' && next == '*') {
                ++i;
                ++i;
                state = Comment;
            } else if (ch == '/' && next == '/') {
                i = text.length();
                setFormat(start, text.length(), m_colors[JSEdit::Comment]);
            } else if (ch == '/' && next != '*') {
                ++i;
                state = Regex;
            } else {
                if (!QString("(){}[]").contains(ch))
                    setFormat(start, 1, m_colors[JSEdit::Operator]);
                if (ch =='{' || ch == '}') {
                    bracketPositions += i;
                    if (ch == '{')
                        bracketLevel++;
                    else
                        bracketLevel--;
                }
                ++i;
                state = Start;
            }
            break;

        case Number:
            if (ch.isSpace() || !ch.isDigit()) {
                setFormat(start, i - start, m_colors[JSEdit::Number]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case Identifier:
            if (ch.isSpace() || !(ch.isDigit() || ch.isLetter() || ch == '_')) {
                QString token = text.mid(start, i - start).trimmed();
                if (m_keywords.contains(token))
                    setFormat(start, i - start, m_colors[JSEdit::Keyword]);
                else if (m_knownIds.contains(token))
                    setFormat(start, i - start, m_colors[JSEdit::BuiltIn]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case String:
            if (ch == text.at(start)) {
                QChar prev = (i > 0) ? text.at(i - 1) : QChar();
                if (prev != '\\') {
                    ++i;
                    setFormat(start, i - start, m_colors[JSEdit::String]);
                    state = Start;
                } else {
                    ++i;
                }
            } else {
                ++i;
            }
            break;

        case Comment:
            if (ch == '*' && next == '/') {
                ++i;
                ++i;
                setFormat(start, i - start, m_colors[JSEdit::Comment]);
                state = Start;
            } else {
                ++i;
            }
            break;

        case Regex:
            if (ch == '/') {
                QChar prev = (i > 0) ? text.at(i - 1) : QChar();
                if (prev != '\\') {
                    ++i;
                    setFormat(start, i - start, m_colors[JSEdit::String]);
                    state = Start;
                } else {
                    ++i;
                }
            } else {
                ++i;
            }
            break;

        default:
            state = Start;
            break;
        }
    }

    if (state == Comment)
        setFormat(start, text.length(), m_colors[JSEdit::Comment]);
    else
        state = Start;

    if (!m_markString.isEmpty()) {
        int pos = 0;
        int len = m_markString.length();
        QTextCharFormat markerFormat;
        markerFormat.setBackground(m_colors[JSEdit::Marker]);
        markerFormat.setForeground(m_colors[JSEdit::Normal]);
        for (;;) {
            pos = text.indexOf(m_markString, pos, m_markCaseSensitivity);
            if (pos < 0)
                break;
            setFormat(pos, len, markerFormat);
            ++pos;
        }
    }

    if (!bracketPositions.isEmpty()) {
        JSBlockData *blockData = reinterpret_cast<JSBlockData*>(currentBlock().userData());
        if (!blockData) {
            blockData = new JSBlockData;
            currentBlock().setUserData(blockData);
        }
        blockData->bracketPositions = bracketPositions;
    }

    blockState = (state & 15) | (bracketLevel << 4);
    setCurrentBlockState(blockState);
}
Beispiel #24
0
void DatabaseTabWidget::checkReloadDatabases()
{
    QSet<QString> changedFiles;

    changedFiles = m_changedFiles.subtract(m_expectedFileChanges);
    m_changedFiles.clear();

    if (changedFiles.isEmpty())
        return;

    Q_FOREACH (DatabaseManagerStruct dbStruct, m_dbList) {
        QString filePath = dbStruct.filePath;
        Database * db = dbStruct.dbWidget->database();

        if (!changedFiles.contains(filePath))
            continue;

        QFileInfo fi(filePath);
        QDateTime lastModified = fi.lastModified();
        if (dbStruct.lastModified == lastModified)
            continue;

        DatabaseWidget::Mode mode = dbStruct.dbWidget->currentMode();
        if (mode == DatabaseWidget::None || mode == DatabaseWidget::LockedMode || !db->hasKey())
            continue;

        ReloadBehavior reloadBehavior = ReloadBehavior(config()->get("ReloadBehavior").toInt());
        if (   (reloadBehavior == AlwaysAsk)
            || (reloadBehavior == ReloadUnmodified && mode == DatabaseWidget::EditMode)
            || (reloadBehavior == ReloadUnmodified && dbStruct.modified)) {
            int res = QMessageBox::warning(this, fi.exists() ? tr("Database file changed") : tr("Database file removed"),
                                           tr("Do you want to discard your changes and reload?"),
                                           QMessageBox::Yes|QMessageBox::No);
            if (res == QMessageBox::No)
                continue;
        }

        if (fi.exists()) {
            //Ignore/cancel all edits
            dbStruct.dbWidget->switchToView(false);
            dbStruct.modified = false;

            //Save current group/entry
            Uuid currentGroup;
            if (Group* group = dbStruct.dbWidget->currentGroup())
                currentGroup = group->uuid();
            Uuid currentEntry;
            if (Entry* entry = dbStruct.dbWidget->entryView()->currentEntry())
                currentEntry = entry->uuid();
            QString searchText = dbStruct.dbWidget->searchText();
            bool caseSensitive = dbStruct.dbWidget->caseSensitiveSearch();
            bool allGroups =     dbStruct.dbWidget->isAllGroupsSearch();

            //Reload updated db
            CompositeKey key = db->key();
            int tabPos = databaseIndex(db);
            closeDatabase(db);
            openDatabase(filePath, QString(), QString(), key, tabPos);

            //Restore current group/entry
            dbStruct = indexDatabaseManagerStruct(count() - 1);
            if (dbStruct.dbWidget && dbStruct.dbWidget->currentMode() == DatabaseWidget::ViewMode) {
                Database * db = dbStruct.dbWidget->database();
                if (!currentGroup.isNull())
                    if (Group* group = db->resolveGroup(currentGroup))
                        dbStruct.dbWidget->groupView()->setCurrentGroup(group);
                if (!searchText.isEmpty())
                    dbStruct.dbWidget->search(searchText, caseSensitive, allGroups);
                if (!currentEntry.isNull())
                    if (Entry* entry = db->resolveEntry(currentEntry))
                        dbStruct.dbWidget->entryView()->setCurrentEntry(entry);
            }
        } else {
            //Ignore/cancel all edits
            dbStruct.dbWidget->switchToView(false);
            dbStruct.modified = false;

            //Close database
            closeDatabase(dbStruct.dbWidget->database());
        }
    }
Beispiel #25
0
bool PathStrokeRenderer::event(QEvent *e)
{
    bool touchBegin = false;
    switch (e->type()) {
    case QEvent::TouchBegin:
        touchBegin = true;
    case QEvent::TouchUpdate:
        {
            const QTouchEvent *const event = static_cast<const QTouchEvent*>(e);
            const QList<QTouchEvent::TouchPoint> points = event->touchPoints();
            foreach (const QTouchEvent::TouchPoint &touchPoint, points) {
                const int id = touchPoint.id();
                switch (touchPoint.state()) {
                case Qt::TouchPointPressed:
                    {
                        // find the point, move it
                        QSet<int> activePoints = QSet<int>::fromList(m_fingerPointMapping.values());
                        int activePoint = -1;
                        qreal distance = -1;
                        const int pointsCount = m_points.size();
                        for (int i=0; i<pointsCount; ++i) {
                            if (activePoints.contains(i))
                                continue;

                            qreal d = QLineF(touchPoint.pos(), m_points.at(i)).length();
                            if ((distance < 0 && d < 12 * m_pointSize) || d < distance) {
                                distance = d;
                                activePoint = i;
                            }
                        }
                        if (activePoint != -1) {
                            m_fingerPointMapping.insert(touchPoint.id(), activePoint);
                            m_points[activePoint] = touchPoint.pos();
                        }
                    }
                    break;
                case Qt::TouchPointReleased:
                    {
                        // move the point and release
                        QHash<int,int>::iterator it = m_fingerPointMapping.find(id);
                        m_points[it.value()] = touchPoint.pos();
                        m_fingerPointMapping.erase(it);
                    }
                    break;
                case Qt::TouchPointMoved:
                    {
                        // move the point
                        const int pointIdx = m_fingerPointMapping.value(id, -1);
                        if (pointIdx >= 0)
                            m_points[pointIdx] = touchPoint.pos();
                    }
                    break;
                default:
                    break;
                }
            }
            if (m_fingerPointMapping.isEmpty()) {
                e->ignore();
                return false;
            } else {
                if (touchBegin) {
                    m_wasAnimated = m_timer.isActive();
                    setAnimation(false);
                }
                update();
                return true;
            }
        }
        break;
    case QEvent::TouchEnd:
        if (m_fingerPointMapping.isEmpty()) {
            e->ignore();
            return false;
        }
        m_fingerPointMapping.clear();
        setAnimation(m_wasAnimated);
        return true;
        break;
    default:
        break;
    }
    return QWidget::event(e);
}
Beispiel #26
0
void Query::run(sc::SearchReplyProxy const& reply)
{
    try {
        // Start by getting information about the query
        const sc::CannedQuery &query(sc::SearchQueryBase::query());

        // Get the query string
        string query_string = query.query_string();
        qCDebug(Qry) << "Query string is:" << QString::fromStdString(query_string);

        // Checking out which sources are enabled.
        QList<BaseClient*> sources;
        if (settings().at("coursera").get_bool())
            sources.append(&m_coursera);
        if (settings().at("udemy").get_bool())
            sources.append(&m_udemy);
        if (settings().at("edx").get_bool())
            sources.append(&m_edx);
        if (settings().at("udacity").get_bool())
            sources.append(&m_udacity);
        if (settings().at("iversity").get_bool())
            sources.append(&m_iversity);
        if (settings().at("openLearning").get_bool())
            sources.append(&m_openLearning);
        qCDebug(Qry) << "Source count:" << sources.count();

        // Working with departments.
        sc::Department::SPtr all_depts = sc::Department::create("", query, _("All"));
        sc::DepartmentList depList;
        QList<Department> list = DepartmentManager::departments();
        for (int i = 0; i < list.length(); i++)
            depList.push_back(sc::Department::create(list[i].id.toStdString(), query, list[i].label.toStdString()));
        all_depts->set_subdepartments(depList);

        // Register the root department on the reply
        reply->register_departments(all_depts);

        QString selectedDepartment = QString::fromStdString(query.department_id());
        qCDebug(Qry) << "Selected department:" << selectedDepartment;

        QSet<QString> uniqueSet;
        for(int i = 0; i < sources.count(); ++i)
        {
            QString sourceCatName = sources[i]->name();
            auto sourceList = sources[i]->courses(QString::fromStdString(query_string));

            auto templ = settings().at("textPosition").get_int() ? CURRENT_TEMPLATE_OV : CURRENT_TEMPLATE;
            auto sourceCategory = reply->register_category(sourceCatName.toLower().toStdString(),
                                                             sourceCatName.toStdString(),
                                                             "", sc::CategoryRenderer(templ));

            //qCDebug(Qry) << "Processing source:" << sourceCatName;

            for (const auto &course : sourceList)
            {

                // Department check.
                if (!selectedDepartment.isEmpty() && !DepartmentManager::isMatch(course, selectedDepartment))
                    continue;

                // Duplicate results cause Dash to crash.
                if (uniqueSet.contains(course.link))
                {
                    qCDebug(Qry) << "Duplicate:" << course.link;
                    continue;
                }
                uniqueSet.insert(course.link);


                sc::CategorisedResult res(sourceCategory);

                // We must have a URI
                res.set_uri(course.link.toStdString());
                res.set_title(course.title.toStdString());
                res.set_art(course.art.toStdString());
                res["headline"] = course.headline.toStdString();
                res["description"] = course.description.toStdString();
                res["source"] = sourceCatName.toStdString();
                res["extra"] = course.extra.toStdString();
                if (!course.video.isEmpty())
                    res["video_url"] = course.video.toStdString();
                res["departments"] = course.departments.join(';').toStdString();

                // Add instructors to map.
                if (course.instructors.count() > 0)
                {
                    std::vector<sc::Variant> images, names, bios;
                    for (auto j = course.instructors.begin(); j != course.instructors.end(); ++j)
                    {
                        images.push_back(sc::Variant(j->image.toStdString()));
                        names.push_back(sc::Variant(j->name.toStdString()));
                        bios.push_back(sc::Variant((j->bio.length() < 150 ? j->bio : j->bio.left(150) + "...").toStdString()));
                    }
                    res["instr_images"] = images;
                    res["instr_names"] = names;
                    res["instr_bios"] = bios;
                }

                // Push the result
                if (!reply->push(res))
                    return;
            }

            qCDebug(Qry) << "Finished with source:" << sourceCatName;
        }

    } catch (domain_error &e) {
        // Handle exceptions being thrown by the client API
        cerr << e.what() << endl;
        reply->error(current_exception());
    }
}
QSet<QString> QgsServerProjectParser::findRestrictedLayers() const
{
  QSet<QString> restrictedLayerSet;

  if ( !mXMLDoc )
  {
    return restrictedLayerSet;
  }

  //names of unpublished layers / groups
  QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( "WMSRestrictedLayers" );
    if ( !wmsLayerRestrictionElem.isNull() )
    {
      QStringList restrictedLayersAndGroups;
      QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( "value" );
      for ( int i = 0; i < wmsLayerRestrictionValues.size(); ++i )
      {
        restrictedLayerSet.insert( wmsLayerRestrictionValues.at( i ).toElement().text() );
      }
    }
  }

  //get legend dom element
  if ( restrictedLayerSet.size() < 1 || !mXMLDoc )
  {
    return restrictedLayerSet;
  }

  QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( "legend" );
  if ( legendElem.isNull() )
  {
    return restrictedLayerSet;
  }

  //go through all legend groups and insert names of subgroups / sublayers if there is a match
  QDomNodeList legendGroupList = legendElem.elementsByTagName( "legendgroup" );
  for ( int i = 0; i < legendGroupList.size(); ++i )
  {
    //get name
    QDomElement groupElem = legendGroupList.at( i ).toElement();
    QString groupName = groupElem.attribute( "name" );
    if ( restrictedLayerSet.contains( groupName ) ) //match: add names of subgroups and sublayers to set
    {
      //embedded group? -> also get names of subgroups and sublayers from embedded projects
      if ( groupElem.attribute( "embedded" ) == "1" )
      {
        sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( "project" ) ), groupName, restrictedLayerSet );
      }
      else //local group
      {
        QDomNodeList subgroupList = groupElem.elementsByTagName( "legendgroup" );
        for ( int j = 0; j < subgroupList.size(); ++j )
        {
          restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( "name" ) );
        }
        QDomNodeList sublayerList = groupElem.elementsByTagName( "legendlayer" );
        for ( int k = 0; k < sublayerList.size(); ++k )
        {
          restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( "name" ) );
        }
      }
    }
  }
  return restrictedLayerSet;
}
Beispiel #28
0
bool BanPair::isBanned(const QString &general) {
    return AllBanSet.contains(general);
}
Beispiel #29
0
void QScriptHighlighter::highlightBlock(const QString &text)
{
    // states
    enum {
        StateStandard,
        StateCommentStart1,
        StateCCommentStart2,
        StateCppCommentStart2,
        StateCComment,
        StateCppComment,
        StateCCommentEnd1,
        StateCCommentEnd2,
        StateStringStart,
        StateString,
        StateStringEnd,
        StateString2Start,
        StateString2,
        StateString2End,
        StateNumber,
        StatePreProcessor,
        NumStates
    };
    // tokens
    enum {
        InputAlpha,
        InputNumber,
        InputAsterix,
        InputSlash,
        InputParen,
        InputSpace,
        InputHash,
        InputQuotation,
        InputApostrophe,
        InputSep,
        NumInputs
    };

    static const uchar table[NumStates][NumInputs] = {
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStandard
        { StateStandard,      StateNumber,   StateCCommentStart2, StateCppCommentStart2, StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCommentStart1
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentStart2
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // CppCommentStart2
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCComment
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // StateCppComment
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCCommentEnd2,     StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentEnd1
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCCommentEnd2
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateStringStart
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateString
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStringEnd
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2Start
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateString2End
        { StateNumber,        StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateNumber
        { StatePreProcessor,  StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard } // StatePreProcessor
    };

    QString buffer;
    buffer.reserve(text.length());
    QTextCharFormat emptyFormat;

    int state = StateStandard;
    const int previousState = previousBlockState();
    if (previousState != -1)
        state = previousState;

    if (text.isEmpty()) {
        setCurrentBlockState(previousState);
        return;
    }

    int input = -1;
    int i = 0;
    bool lastWasBackSlash = false;
    bool makeLastStandard = false;

    static const QSet<QChar> alphabeth = alphaChars();
    static const QString mathChars = QString::fromLatin1("xXeE");
    static const QString numbers = QString::fromLatin1("0123456789");
    bool questionMark = false;
    QChar lastChar;
    QString firstWord;
    forever {
        const QChar c = text.at(i);

        if (lastWasBackSlash) {
            input = InputSep;
        } else {
            switch (c.toLatin1()) {
                case '*':
                    input = InputAsterix;
                    break;
                case '/':
                    input = InputSlash;
                    break;
                case '(': case '[': case '{':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       )
                        //blockData->parentheses << Parenthesis(Parenthesis::Open, c, i);
                    break;
                case ')': case ']': case '}':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       ) {
                        //blockData->parentheses << Parenthesis(Parenthesis::Closed, c, i);
                    }
                    break;
                case '#':
                    input = InputHash;
                    break;
                case '"':
                    input = InputQuotation;
                    break;
                case '\'':
                    input = InputApostrophe;
                    break;
                case ' ':
                    input = InputSpace;
                    break;
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9': case '0':
                    if (alphabeth.contains(lastChar)
                        && (!mathChars.contains(lastChar) || !numbers.contains(text.at(i - 1)))) {
                        input = InputAlpha;
                    } else {
                        if (input == InputAlpha && numbers.contains(lastChar))
                            input = InputAlpha;
                        else
                            input = InputNumber;
                    }
                    break;
                case ':': {
                              input = InputAlpha;
                              QChar nextChar = QLatin1Char(' ');
                              if (i < text.length() - 1)
                                  nextChar = text.at(i + 1);
                              if (state == StateStandard && !questionMark &&
                                  lastChar != QLatin1Char(':') && nextChar != QLatin1Char(':')) {
                                  for (int j = 0; j < i; ++j) {
                                      if (format(j) == emptyFormat)
                                          setFormat(j, 1, m_labelFormat);
                                  }
                              }
                              break;
                          }
                default: {
                             if (!questionMark && c == QLatin1Char('?'))
                                 questionMark = true;
                             if (c.isLetter() || c == QLatin1Char('_'))
                                 input = InputAlpha;
                             else
                                 input = InputSep;
                         } break;
            }
        }

        lastWasBackSlash = !lastWasBackSlash && c == QLatin1Char('\\');

        if (input == InputAlpha)
            buffer += c;

        state = table[state][input];

        switch (state) {
            case StateStandard: {
                                    setFormat(i, 1, emptyFormat);
                                    if (makeLastStandard)
                                        setFormat(i - 1, 1, emptyFormat);
                                    makeLastStandard = false;
                                    if (!buffer.isEmpty() && input != InputAlpha ) {
                                        highlightKeyword(i, buffer);
                                        buffer.clear();
                                    }
                                } break;
            case StateCommentStart1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = true;
                                buffer.resize(0);
                                break;
            case StateCCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCppCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCppComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateStringStart:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateStringEnd:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2Start:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateString2End:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateNumber:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat( i, 1, m_numberFormat);
                                buffer.resize(0);
                                break;
            case StatePreProcessor:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_preProcessorFormat);
                                buffer.resize(0);
                                break;
        }

        lastChar = c;
        i++;
        if (i >= text.length())
            break;
    }

    highlightKeyword(text.length(), buffer);

    if (state == StateCComment
        || state == StateCCommentEnd1
        || state == StateCCommentStart2
       ) {
        state = StateCComment;
    } else if (state == StateString) {
        state = StateString;
    } else if (state == StateString2) {
        state =  StateString2;
    } else {
        state = StateStandard;
    }

    setCurrentBlockState(state);
}
Beispiel #30
0
void ResourceTopLevelNode::update()
{
    QList<ProjectExplorer::FolderNode *> newFolderList;
    QMap<QPair<QString, QString>, QList<ProjectExplorer::FileNode *> > filesToAdd;

    ResourceFile file(filePath().toString());
    if (file.load() == Core::IDocument::OpenResult::Success) {
        QSet<QPair<QString, QString > > prefixes;

        int prfxcount = file.prefixCount();
        for (int i = 0; i < prfxcount; ++i) {
            const QString &prefix = file.prefix(i);
            const QString &lang = file.lang(i);
            // ensure that we don't duplicate prefixes
            if (!prefixes.contains(qMakePair(prefix, lang))) {
                ProjectExplorer::FolderNode *fn = new ResourceFolderNode(file.prefix(i), file.lang(i), this);
                newFolderList << fn;

                prefixes.insert(qMakePair(prefix, lang));
            }

            QSet<QString> fileNames;
            int filecount = file.fileCount(i);
            for (int j = 0; j < filecount; ++j) {
                const QString &fileName = file.file(i, j);
                QString alias = file.alias(i, j);
                if (alias.isEmpty())
                    alias = filePath().toFileInfo().absoluteDir().relativeFilePath(fileName);
                if (fileNames.contains(fileName)) {
                    // The file name is duplicated, skip it
                    // Note: this is wrong, but the qrceditor doesn't allow it either
                    // only aliases need to be unique
                } else {
                    QString prefixWithSlash = prefix;
                    if (!prefixWithSlash.endsWith(QLatin1Char('/')))
                        prefixWithSlash.append(QLatin1Char('/'));
                    const QString qrcPath = QDir::cleanPath(prefixWithSlash + alias);
                    fileNames.insert(fileName);
                    filesToAdd[qMakePair(prefix, lang)]
                            << new ResourceFileNode(Utils::FileName::fromString(fileName),
                                                    qrcPath, this);
                }

            }
        }
    }

    QList<ProjectExplorer::FolderNode *> oldFolderList = subFolderNodes();
    QList<ProjectExplorer::FolderNode *> foldersToAdd;
    QList<ProjectExplorer::FolderNode *> foldersToRemove;

    std::sort(oldFolderList.begin(), oldFolderList.end(), sortByPrefixAndLang);
    std::sort(newFolderList.begin(), newFolderList.end(), sortByPrefixAndLang);

    ProjectExplorer::compareSortedLists(oldFolderList, newFolderList, foldersToRemove, foldersToAdd, sortByPrefixAndLang);

    removeFolderNodes(foldersToRemove);
    addFolderNodes(foldersToAdd);

    // delete nodes that weren't added
    qDeleteAll(ProjectExplorer::subtractSortedList(newFolderList, foldersToAdd, sortByPrefixAndLang));

    foreach (FolderNode *fn, subFolderNodes()) {
        ResourceFolderNode *rn = static_cast<ResourceFolderNode *>(fn);
        rn->updateFiles(filesToAdd.value(qMakePair(rn->prefix(), rn->lang())));
    }