Beispiel #1
0
// Draw self edge
void LineGraphEdge::drawSelf(Widget w,
			     const BoxRegion& exposed,
			     const GraphGC& gc) const
{
    assert(from() == to());

    // Get region
    BoxRegion region = from()->region(gc);
    if (from()->selected())
	region.origin() += gc.offsetIfSelected;

    LineGraphEdgeSelfInfo info(region, gc);

    XDrawArc(XtDisplay(w), XtWindow(w), gc.edgeGC, info.arc_pos[X],
	     info.arc_pos[Y], info.diameter, info.diameter,
	     info.arc_start * 64, info.arc_extend * 64);

    if (annotation() != 0)
    {
	// Draw annotation
	annotation()->draw(w, info.anno_pos, exposed, gc);
    }

    // Find arrow angle
    drawArrowHead(w, exposed, gc, info.arrow_pos, info.arrow_alpha);
}
Beispiel #2
0
// Region occupied by edge
BoxRegion LineGraphEdge::region(const GraphGC& gc) const
{
    BoxRegion r;
    if (gc.drawAnnotations && annotation() != 0)
    {
	BoxPoint anno_pos = annotationPosition(gc);
	if (anno_pos.isValid())
	{
	    BoxRegion anno_region = annotation()->region(anno_pos, gc);
	    if (r.origin().isValid())
		r = r | anno_region;
	    else
		r = anno_region;
	}
    }

    if (from() == to())
    {
	BoxRegion region = from()->region(gc);
       	if (from()->selected())
	    region.origin() += gc.offsetIfSelected;

	LineGraphEdgeSelfInfo info(region, gc);

	BoxRegion self_region(info.arc_pos,
			      BoxSize(info.diameter, info.diameter));

	if (r.origin().isValid())
	    r = r | self_region;
	else
	    r = self_region;
    }

    return r;
}
Beispiel #3
0
void LineGraphEdge::printSelf(ostream& os, const GraphGC &gc) const
{
    assert(from() == to());

    // Get region
    BoxRegion region = from()->region(gc);
    if (from()->selected())
	region.origin() += gc.offsetIfSelected;

    LineGraphEdgeSelfInfo info(region, gc);

    if (gc.printGC->isPostScript())
    {
	int start = (720 - info.arc_start - info.arc_extend) % 360 ;
	int end   = (720 - info.arc_start) % 360 ;

	BoxCoordinate line_width = 1;

	// Draw arc
	os << start << " " << end << " " 
	   << info.radius << " " << info.radius << " "
	   << info.arc_center[X] << " " << info.arc_center[Y] << " " 
	   << line_width << " arc*\n";

	// Now draw the arrow head
	int angle = (720 - info.arrow_angle) % 360;

	os << gc.arrowAngle << " " << gc.arrowLength << " " << angle << " "
	   << info.arrow_pos[X] << " " << info.arrow_pos[Y] << " arrowhead*\n";
    }
    else if (gc.printGC->isFig())
    {
	BoxCoordinate line_width = 1;

	os << ARCARROWHEAD1 << line_width << ARCARROWHEAD2;
	switch (gc.selfEdgeDirection)
	{
	case Clockwise:
	    os << ARCCLOCKWISE;
	    break;
	case Counterclockwise:
	    os << ARCCOUNTERCLOCKWISE;
	    break;
	}
	os << ARCARROWHEAD3
	   << float(info.arc_center[X]) << " " 
	   << float(info.arc_center[Y]) << " ";
	for (int i = 0; i < 3; i++)
	    os << info.fig_pos[i][X] << " " << info.fig_pos[i][Y] << " ";
	os << ARCARROWHEAD4;
    }

    if (annotation() != 0)
    {
	// Print annotation
	annotation()->_print(os, info.anno_pos, gc);
    }
}
Beispiel #4
0
void interface_1(List *list)
{
    annotation();

    while (1)
    {
        int interact = 0;
        int key = 0;

        printf("Num of actinon:\n");
        scanf("%d", &interact);

        if (interact == 0)
            break;

        if (interact == 1) {
            interface_2(list);
            continue;
        }

        if (interact == 2) {
            if (list_is_empty(list)) {
                printf("Nothing to delete, enter element, just press 1\n");
                continue;
            }
            printf("Key of delete element?\n");
            scanf("%d", &key);

            list_delete_elem(list, find_elem(list, key));
            continue;
        }

        if (interact == 3) {
            list = merge_sort(list);
            continue;
        }

        if (interact == 4) {
            list_print(list);
            continue;
        }

        if (interact == 9) {
            annotation();
            continue;
        }

        printf("Wrong input try again\n");
    }
}
Beispiel #5
0
void LineGraphEdge::drawLine(Widget w, 
			     const BoxRegion& exposed, 
			     const GraphGC& gc) const
{
    // Get node starting points
    BoxPoint pos1     = from()->pos();
    BoxRegion region1 = from()->region(gc);
    if (from()->selected())
    {
	pos1             += gc.offsetIfSelected;
	region1.origin() += gc.offsetIfSelected;
    }

    BoxPoint pos2     = to()->pos();
    BoxRegion region2 = to()->region(gc);
    if (to()->selected())
    {
	pos2             += gc.offsetIfSelected;
	region2.origin() += gc.offsetIfSelected;
    }

    // If nodes overlap, don't draw the edge.
    if (region1 <= region2)
	return;

    // Get the line points
    BoxPoint l1, l2;
    findLine(pos1, pos2, region1, region2, l1, l2, gc);

    // If there is no edge (adjacent nodes), don't draw it.
    if (l1 == l2)
	return;

    XDrawLine(XtDisplay(w), XtWindow(w), gc.edgeGC,
	      l1[X], l1[Y], l2[X], l2[Y]);

    // Draw annotation
    BoxPoint anno_pos = annotationPosition(gc);
    if (annotation() != 0 && anno_pos.isValid())
    {
	annotation()->draw(w, anno_pos, exposed, gc);
    }

    // Get arrow angle
    double alpha = atan2(double(l1[Y] - l2[Y]), double(l1[X] - l2[X]));

    // Draw arrow head at L2
    drawArrowHead(w, exposed, gc, l2, alpha);
}
Beispiel #6
0
bool Rank1Constraint::isSatisfied(const VariableAssignment& assignment,
                                  const PrintOptions& printOnFail) const {
    const FElem ares = a_.eval(assignment);
    const FElem bres = b_.eval(assignment);
    const FElem cres = c_.eval(assignment);
    if (ares*bres != cres) {
#       ifdef DEBUG
        if (printOnFail == PrintOptions::DBG_PRINT_IF_NOT_SATISFIED) {
            cerr << GADGETLIB2_FMT("Constraint named \"%s\" not satisfied. Constraint is:",
                name().c_str()) << endl;
            cerr << annotation() << endl;
            cerr << "Variable assignments are:" << endl;
            const Variable::set varSet = getUsedVariables();
            for(const Variable& var : varSet) {
                cerr <<  var.name() << ": " << assignment.at(var).asString() << endl;
            }
            cerr << "a:   " << ares.asString() << endl;
            cerr << "b:   " << bres.asString() << endl;
            cerr << "a*b: " << (ares*bres).asString() << endl;
            cerr << "c:   " << cres.asString() << endl;
        }
#       endif
        return false;
    }
    return true;
}
Beispiel #7
0
bool canSerializeItem(const GMetaArchiveConfig & config, IMetaItem * item)
{
	if(item == NULL) {
		return false;
	}

	GScopedInterface<IMetaAnnotation> annotation(item->getAnnotation(SerializationAnnotation));

	if(! annotation) {
	}
	else {
		GScopedInterface<IMetaAnnotationValue> annotationValue(annotation->getValue(SerializationAnnotationEnable));
		if(annotationValue) {
			if(! annotationValue->toBoolean()) {
				return false;
			}
		}
	}

	if(! config.defaultSerializeAll()) {
		return false;
	}

	return true;
}
Beispiel #8
0
void AnnotationItem::update()
{
    QMT_CHECK(!m_isUpdating);
    m_isUpdating = true;

    prepareGeometryChange();

    const Style *style = adaptedStyle();

    // text
    if (!m_textItem) {
        m_textItem = new AnnotationTextItem(this);
        m_textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
        m_textItem->installSceneEventFilter(this);
        QObject::connect(m_textItem->document(), &QTextDocument::contentsChanged, m_textItem,
                         [=]() { this->onContentsChanged(); } );
    }
    m_textItem->setFont(style->normalFont());
    m_textItem->setDefaultTextColor(style->textBrush().color());
    if (!m_isChanged)
        m_textItem->setPlainText(annotation()->text());

    // item shown if annotation has no text and is not selected
    if (!m_noTextItem)
        m_noTextItem = new QGraphicsRectItem(this);
    m_noTextItem->setPen(QPen(QBrush(QColor(192, 192, 192)), 1, Qt::DashDotLine));
    m_noTextItem->setVisible(!isSelected() && m_textItem->document()->isEmpty());

    updateSelectionMarker();
    updateGeometry();
    setZValue(ANNOTATION_ITEMS_ZVALUE);

    m_isUpdating = false;
}
Beispiel #9
0
bool SemanticRelationData::addRelations(AnalysisContent& analysis)
{
#ifdef DEBUG_LP
  SEMANTICANALYSISLOGINIT;
#endif
  auto annotationData = static_cast< AnnotationData* >(
    analysis.getData("AnnotationData"));

  if (annotationData->dumpFunction("SemanticRelation") == 0)
  {
    annotationData->dumpFunction("SemanticRelation", 
                                 new DumpSemanticRelation());
  }
  auto recoData=static_cast<RecognizerData*>(
    analysis.getData("RecognizerData"));

  for (auto i = m_relations.begin(); i != m_relations.end(); i++) 
  {
    LinguisticGraphVertex vertex1 = i->get<0>();
    LinguisticGraphVertex vertex2 = i->get<1>();

    auto matchesVtx1 = annotationData->matches(recoData->getGraphId(),
                                               vertex1,
                                               "annot");
    auto matchesVtx2 = annotationData->matches(recoData->getGraphId(),
                                               vertex2,
                                               "annot");

    if (!annotationData->hasAnnotation(*(matchesVtx1.begin()), 
                                       *(matchesVtx2.begin()),
                                       "SemanticRelation"))
    {
      SemanticRelationAnnotation annot(i->get<2>());
      GenericAnnotation ga(annot);
      annotationData->annotate(*(matchesVtx1.begin()), 
                               *(matchesVtx2.begin()),
                               "SemanticRelation", 
                               ga);
    }
    else
    {
      auto annot = annotationData->annotation(*(matchesVtx1.begin()), 
                               *(matchesVtx2.begin()),
                               "SemanticRelation").pointerValue<SemanticRelationAnnotation>();
      SEMANTICANALYSISLOGINIT;
      LWARN << "SemanticRelationData::addRelations There is already a SemanticRelation between" 
            << *(matchesVtx1.begin()) << "and" << *(matchesVtx2.begin()) << annot->type();
      LWARN << "Adding new type" << i->get<2>();
      QString type = QString::fromUtf8(annot->type().c_str());
      QStringList typeList = type.split(',');
      typeList << i->get<2>().c_str();
      typeList.sort();
      typeList.removeDuplicates();
      annot->type(typeList.join(',').toUtf8().constData());
      LWARN << "Adding type is now" << annot->type();
    }
  }
  m_relations.clear();
  return true;
}
Beispiel #10
0
void AnnotationItem::updateGeometry()
{
    prepareGeometryChange();

    QSizeF geometry = calcMinimumGeometry();
    qreal width = geometry.width();
    qreal height = geometry.height();

    if (annotation()->isAutoSized()) {
        if (m_textItem) {
            m_textItem->setTextWidth(-1);
            QSizeF textSize = m_textItem->document()->size();
            width = textSize.width() + 2 * CONTENTS_BORDER_HORIZONTAL;
            height = textSize.height() + 2 * CONTENTS_BORDER_VERTICAL;
        }
    } else {
        QRectF rect = annotation()->rect();
        width = rect.width();
        if (m_textItem) {
            m_textItem->setTextWidth(width - 2 * CONTENTS_BORDER_HORIZONTAL);
            height = m_textItem->document()->size().height() + 2 * CONTENTS_BORDER_VERTICAL;
        }
    }

    // update sizes and positions
    double left = 0.0;
    double top = 0.0;

    setPos(annotation()->pos());

    QRectF rect(left, top, width, height);

    // the object is updated without calling DiagramController intentionally.
    // attribute rect is not a real attribute stored on DObject but
    // a backup for the graphics item used for manual resized and persistency.
    annotation()->setRect(rect);

    if (m_noTextItem)
        m_noTextItem->setRect(rect);

    if (m_textItem)
        m_textItem->setPos(left + CONTENTS_BORDER_HORIZONTAL, top + CONTENTS_BORDER_VERTICAL);

    updateSelectionMarkerGeometry(rect);
}
Beispiel #11
0
QVariant Annotations::rosterData(int AOrder, const IRosterIndex *AIndex, int ARole) const
{
	if (AOrder==RDHO_ANNOTATIONS && ARole==RDR_ANNOTATIONS && AnnotationRosterKinds.contains(AIndex->kind()))
	{
		QString note = annotation(AIndex->data(RDR_STREAM_JID).toString(),AIndex->data(RDR_PREP_BARE_JID).toString());
		return note;
	}
	return QVariant();
}
Beispiel #12
0
GMetaArchiveConfig getItemMetaArchiveConfig(IMetaItem * item)
{
	GMetaArchiveConfig config;

	if(item != NULL) {
		GScopedInterface<IMetaAnnotation> annotation(item->getAnnotation(SerializationAnnotation));

		if(annotation) {
			GScopedInterface<IMetaAnnotationValue> annotationValue;
		
			annotationValue.reset(annotation->getValue(SerializationAnnotationEnable));
			if(annotationValue) {
				if(! annotationValue->toBoolean()) {
					config.setAllowSerialize(false);
				}
			}

			annotationValue.reset(annotation->getValue(SerializationAnnotationDefaultAll));
			if(annotationValue) {
				if(! annotationValue->toBoolean()) {
					config.setDefaultSerializeAll(false);
				}
			}
		
			annotationValue.reset(annotation->getValue(SerializationAnnotationFields));
			if(annotationValue) {
				if(! annotationValue->toBoolean()) {
					config.setAllowSerializeField(false);
				}
			}
		
			annotationValue.reset(annotation->getValue(SerializationAnnotationProperties));
			if(annotationValue) {
				if(! annotationValue->toBoolean()) {
					config.setAllowSerializeProperty(false);
				}
			}
		
			annotationValue.reset(annotation->getValue(SerializationAnnotationTrackPointers));
			if(annotationValue) {
				if(! annotationValue->toBoolean()) {
					config.setAllowTrackPointer(false);
				}
			}
		
			annotationValue.reset(annotation->getValue(SerializationAnnotationVersion));
			if(annotationValue) {
				uint32_t version = annotationValue->toInt32();
				config.setVersion(version);
			}
		}
	}
	
	return config;
}
Beispiel #13
0
void LineGraphEdge::_print(ostream& os, const GraphGC &gc) const
{
    if (from() == to())
    {
	printSelf(os, gc);
	return;
    }

    GraphEdge::_print(os, gc);

    // Print annotation
    if (annotation() != 0)
    {
	BoxPoint anno_pos = annotationPosition(gc);
	if (anno_pos.isValid())
	{
	    annotation()->_print(os, anno_pos, gc);
	}
    }
}
Beispiel #14
0
QSizeF AnnotationItem::calcMinimumGeometry() const
{
    qreal width = MINIMUM_TEXT_WIDTH + 2 * CONTENTS_BORDER_HORIZONTAL;
    qreal height = 0.0; // irrelevant; cannot be modified by user and will always be overwritten

    if (annotation()->isAutoSized()) {
        if (m_textItem) {
            m_textItem->setTextWidth(-1);
            QSizeF textSize = m_textItem->document()->size();
            width = textSize.width() + 2 * CONTENTS_BORDER_HORIZONTAL;
        }
    }
    return QSizeF(width, height);
}
static SkPaint make_paint() {
    SkPaint paint;
    paint.setHinting(make_paint_hinting());
    paint.setAntiAlias(make_bool());
    paint.setDither(make_bool());
    paint.setLinearText(make_bool());
    paint.setSubpixelText(make_bool());
    paint.setLCDRenderText(make_bool());
    paint.setEmbeddedBitmapText(make_bool());
    paint.setAutohinted(make_bool());
    paint.setVerticalText(make_bool());
    paint.setUnderlineText(make_bool());
    paint.setStrikeThruText(make_bool());
    paint.setFakeBoldText(make_bool());
    paint.setDevKernText(make_bool());
    paint.setFilterQuality(make_filter_quality());
    paint.setStyle(make_paint_style());
    paint.setColor(make_color());
    paint.setStrokeWidth(make_scalar());
    paint.setStrokeMiter(make_scalar());
    paint.setStrokeCap(make_paint_cap());
    paint.setStrokeJoin(make_paint_join());
    paint.setColorFilter(make_color_filter());
    paint.setXfermodeMode(make_xfermode());
    paint.setPathEffect(make_path_effect());
    paint.setMaskFilter(make_mask_filter());
    SkAutoTUnref<SkTypeface> typeface(
        SkTypeface::CreateFromName(make_font_name().c_str(), make_typeface_style()));
    paint.setTypeface(typeface);
    SkLayerRasterizer::Builder rasterizerBuilder;
    SkPaint paintForRasterizer;
    if (R(2) == 1) {
        paintForRasterizer = make_paint();
    }
    rasterizerBuilder.addLayer(paintForRasterizer);
    SkAutoTUnref<SkRasterizer> rasterizer(rasterizerBuilder.detachRasterizer());
    paint.setRasterizer(rasterizer);
    paint.setImageFilter(make_image_filter());
    SkAutoDataUnref data(make_3Dlut(nullptr, make_bool(), make_bool(), make_bool()));
    SkAutoTUnref<SkAnnotation> annotation(
        SkAnnotation::Create(make_string().c_str(), data));
    paint.setAnnotation(annotation);
    paint.setTextAlign(make_paint_align());
    paint.setTextSize(make_scalar());
    paint.setTextScaleX(make_scalar());
    paint.setTextSkewX(make_scalar());
    paint.setTextEncoding(make_paint_text_encoding());
    return paint;
}
		/**
		 * Finds the sentence annotation containing the given token.
		 *
		 * \param token the token
		 * \return the sentence or an invalid sentence if not found
		 */
		SentenceAnnotation SentenceAnnotation::findSentenceContainingToken(TokenAnnotation& token)
		{
			FSIterator iterator = token.getView().getAnnotationIndex(tSentenceAnnotation).iterator();
			if (iterator.isValid()) {
				iterator.moveToFirst();
				while (iterator.isValid()) {
					AnnotationFS annotation(iterator.get());
					SentenceAnnotation sentence(annotation);
					if ((sentence.getFirstToken().getIndex() <= token.getIndex()) && (sentence.getLastToken().getIndex() >= token.getIndex()))
						return sentence;
					iterator.moveToNext();
				}
			}
			return SentenceAnnotation();
		}
Beispiel #17
0
/*
 * this function makes a random maze with exactly one path between
 * any two points in the maze
 *
 * If you're curious about the algorithm, come talk to me.  It's not very
 * complicated (although the code might be confusing)
 */
void makeMaze() {
	int num_visited = 1;
	int first;
	int finish_col;
	makeAllWalls();
	markCell(0, 0);  // mark the first cell as visited
	
	/* add the first cell (row 0, col 0) to the linked list of visited cells */
	first = cellID(0, 0);
	annotateCell(0, 0, 0);
	
	while(num_visited < MAZE_SIZE * MAZE_SIZE) {
		int visit = rand() % num_visited;
		int cell = first; 
		int row, col;
		int d;
		int nrow, ncol;

		findCell(cell, &row, &col);
		while (visit > 0) {
			cell = annotation(row, col);
			findCell(cell, &row, &col);
			visit -= 1;
		}
		d = rand() % 4;
		nrow = row; // row of neighbor cell
		ncol = col; // col of neighbor cell
		interpretDir(&nrow, &ncol, d);
		if (nrow >= 0 && nrow < MAZE_SIZE
			&& ncol >= 0 && ncol < MAZE_SIZE
			&& !isMarked(nrow, ncol)) {
			clearWall(row, col, d);
			num_visited += 1;
			markCell(nrow, ncol);
			annotateCell(nrow, ncol, first);
			first = cellID(nrow, ncol);	
		}
	}
	
	start_col = rand() % MAZE_SIZE;
	start_col = 2 * start_col + 1;
	maze[0][start_col] &= ~WALL;
	finish_col = rand() % MAZE_SIZE;
	maze[MATRIX_SIZE - 1][2 * finish_col + 1] &= ~WALL;
	//maze[MATRIX_SIZE - 1][0] &= ~WALL;
}
Beispiel #18
0
/**
 * @param tokens message tokens
 */
bool SessionState::handleMessage(const QStringList& tokens)
{
    if(tokens[0] == "SAY") {
        int userid = tokens.at(1).toInt();
        if(hasUser(userid))
            emit chatMessage(user(userid).name(), tokens.at(2));
        else
            qWarning() << "Got chat message from unknown user:"******"USER") {
        updateUser(tokens);
    } else if(tokens[0] == "PART") {
        partUser(tokens);
    } else if(tokens[0] == "SLOCK") {
        emit syncWait();
    } else if(tokens[0] == "SUNLOCK") {
        emit syncDone();
    } else if(tokens[0] == "BOARD") {
        update(Session(tokens));
    } else if(tokens[0] == "RASTER") {
        releaseRaster();
        expectRaster_ = tokens.at(1).toInt();
        if(expectRaster_ == 0)
            emit rasterReceived(100);
    } else if(tokens[0] == "GIVERASTER") {
        emit syncRequest();
    } else if(tokens[0] == "MORE") {
        if(isUploading())
            sendRasterChunk();
        else
            qWarning() << "Got request for more raster data, but we're not uploading anything!";
    } else if(tokens[0] == "ANNOTATE") {
        protocol::Annotation a(tokens);
        if(!a.isValid())
            qWarning() << "Received an invalid annotation";
        else
            emit annotation(a);
    } else if(tokens[0] == "RMANNOTATION") {
        emit rmAnnotation(tokens.at(1).toInt());
    } else
        return false;
    return true;
}
Beispiel #19
0
bool PolynomialConstraint::isSatisfied(const VariableAssignment& assignment,
                                       const PrintOptions& printOnFail) const {
    const FElem aEval = a_.eval(assignment);
    const FElem bEval = b_.eval(assignment);
    if (aEval != bEval) {
#       ifdef DEBUG
            if(printOnFail == PrintOptions::DBG_PRINT_IF_NOT_SATISFIED) {
                cerr << GADGETLIB2_FMT("Constraint named \"%s\" not satisfied. Constraint is:",
                    name().c_str()) << endl;
                cerr << annotation() << endl;
				cerr << "Expecting: " << aEval << " == " << bEval << endl;
                cerr << "Variable assignments are:" << endl;
                const Variable::set varSet = getUsedVariables();
                for(const Variable& var : varSet) {
                    cerr <<  var.name() << ": " << assignment.at(var).asString() << endl;
                }
            }
#       endif

        return false;
    }
    return true;
}
Beispiel #20
0
void EcgEntry::LoadAnnotations(QFile *file)
{
    this->entity->annotations = new QList<EcgAnnotation>();

    QTextStream *in = new QTextStream(file);
    QString line = in->readLine();
    bool stop = in->atEnd();

    while(!stop)
    {
        QStringList elements = line.split(" ");
        elements.removeAll("");
        EcgAnnotation annotation(elements.at(0),
                                  elements.at(1).toInt(),
                                  elements.at(2).at(0));
        annotation.sub = elements.at(3).toInt();
        annotation.chan = elements.at(4).toInt();
        QString temp = elements.at(5);
        if(temp.length() == 1)
        {
            annotation.num = temp.toInt();
        }
        else
        {
            QString s(temp.at(0));
            annotation.num = s.toInt();
            annotation.aux = temp.mid(2);
        }
        EcgAnnotation* ptr = &annotation;

        this->entity->annotations->append(*ptr);
        line = in->readLine();
        stop = in->atEnd();
    }

    file->close();
}
  //not really tuple but fonction arguments
  void SignatureConvertor::visitTuple(const Signature &sig) {
    std::vector<std::string> annot;
    std::string annotation(sig.annotation());
    boost::algorithm::split(annot, annotation, boost::algorithm::is_any_of(","));

    if (!annotation.empty() && !annot.empty()) {
      //the first elem is the name
      _result += annot[0];
      return;
    }
    _result += "(";
    const qi::SignatureVector& csig = sig.children();

    qi::SignatureVector::const_iterator it = csig.begin();
    while (it != csig.end()) {
      visit(*it);
      ++it;
      if (it != csig.end())
        _result += ",";
      else
        break;
    }
    _result += ")";
  }
Beispiel #22
0
void ArcGraphEdge::makeLine(Widget w,
			    const BoxRegion& exposed,
			    std::ostream& os,
			    const GraphGC& gc) const
{
    HintGraphNode   *arc_hint = 0;
    RegionGraphNode *arc_from = 0;
    RegionGraphNode *arc_to   = 0;

    bool make_arc = true;
    if (from()->isHint() && to()->isHint())
    {
	// Edge between two hints
	make_arc = false;
    }
    else if (from()->isHint() && from()->firstTo() != 0)
    {
	arc_hint = ptr_cast(HintGraphNode, from());
	arc_from = ptr_cast(RegionGraphNode, arc_hint->firstTo()->from());
	arc_to   = ptr_cast(RegionGraphNode, to());

	if (arc_hint == 0 || arc_from == 0 || arc_to == 0 
	    || arc_hint->nextTo(arc_hint->firstTo()) != 0)
	{
	    // Bad nodes or hint with multiple edges
	    make_arc = false;
	}
    }
    else if (to()->isHint() && to()->firstFrom() != 0)
    {
	arc_hint = ptr_cast(HintGraphNode, to());
	arc_to   = ptr_cast(RegionGraphNode, arc_hint->firstFrom()->to());
	arc_from = ptr_cast(RegionGraphNode, from());

	if (arc_hint == 0 || arc_from == 0 || arc_to == 0
	    || arc_hint->nextFrom(arc_hint->firstFrom()) != 0)
	{
	    // Bad nodes or hint with multiple edges
	    make_arc = false;
	}
    }
    else
    {
	// Edge between two ordinary nodes
	make_arc = false;
    }

    if (!make_arc)
    {
 	if (w != 0)
	    LineGraphEdge::drawLine(w, exposed, gc);
	else
	    LineGraphEdge::_print(os, gc);
	return;
    }

    BoxPoint pos_from     = arc_from->pos();
    BoxRegion region_from = arc_from->region(gc);
    if (arc_from->selected())
    {
	pos_from             += gc.offsetIfSelected;
	region_from.origin() += gc.offsetIfSelected;
    }

    BoxPoint pos_to     = arc_to->pos();
    BoxRegion region_to = arc_to->region(gc);
    if (arc_to->selected())
    {
	pos_to             += gc.offsetIfSelected;
	region_to.origin() += gc.offsetIfSelected;
    }

    BoxPoint pos_hint     = arc_hint->pos();
    BoxRegion region_hint = arc_hint->region(gc);
    if (arc_hint->selected())
    {
	pos_hint             += gc.offsetIfSelected;
	region_hint.origin() += gc.offsetIfSelected;
    }

    if (pos_hint <= region_from || pos_hint <= region_to)
    {
	// Hint within region
 	if (w != 0)
	    LineGraphEdge::drawLine(w, exposed, gc);
	else
	    LineGraphEdge::_print(os, gc);
	return;
    }

    BoxPoint new_pos_from, new_pos_to, dummy;
    findLine(pos_from, pos_hint, region_from, region_hint,
	     new_pos_from, dummy, gc);
    findLine(pos_hint, pos_to, region_hint, region_to,
	     dummy, new_pos_to, gc);
    pos_from = new_pos_from;
    pos_to   = new_pos_to;

    // Draw circle segment POS_FROM -> POS_HINT or POS_HINT -> POS_TO

    // Determine the arc center
    double cx, cy;
    bool ok = center(pos_from, pos_hint, pos_to, cx, cy);
    if (!ok)
    {
	// Nodes form a line
 	if (w != 0)
	    LineGraphEdge::drawLine(w, exposed, gc);
	else
	    LineGraphEdge::_print(os, gc);
	return;
    }

    // Determine radius (easy when you have the center)
    double radius = hypot(cx - pos_to[X], cy - pos_to[Y]);

    // Determine start and path of arc
    double alpha_from = -atan2(pos_from[Y] - cy, pos_from[X] - cx);
    double alpha_hint = -atan2(pos_hint[Y] - cy, pos_hint[X] - cx);
    double alpha_to   = -atan2(pos_to[Y]   - cy, pos_to[X]   - cx);

    const int base = 360 * 64;

    int angle_from = (int(alpha_from * base / (PI * 2.0)) + base) % base;
    int angle_to   = (int(alpha_to   * base / (PI * 2.0)) + base) % base;
    int angle_hint = (int(alpha_hint * base / (PI * 2.0)) + base) % base;

    int path_from_hint = (base + angle_hint - angle_from) % base;
    int path_hint_to   = (base + angle_to - angle_hint) % base;

    if (abs(path_from_hint) > base / 2)
	path_from_hint = (path_from_hint - base) % base;
    if (abs(path_hint_to) > base / 2)
	path_hint_to = (path_hint_to - base) % base;

    if (sgn(path_from_hint) * sgn(path_hint_to) == -1)
    {
	// Hint is not between FROM and TO
 	if (w != 0)
	    LineGraphEdge::drawLine(w, exposed, gc);
	else
	    LineGraphEdge::_print(os, gc);
	return;
    }

    int angle, path;
    if (to()->isHint())
    {
	angle = angle_from;
	path  = path_from_hint;
    }
    else
    {
	angle = angle_hint;
	path  = path_hint_to;
    }

    if (w != 0)
    {
	XDrawArc(XtDisplay(w), XtWindow(w), gc.edgeGC,
		 int(cx - radius), int(cy - radius),
		 unsigned(radius) * 2, unsigned(radius) * 2, angle, path);
    }
    else if (gc.printGC->isPostScript())
    {
	BoxCoordinate line_width = 1;

	int arc_start  = angle / 64;
	int arc_extend = path / 64;

	int start, end;
	if (arc_extend > 0)
	{
	    start = (720 - arc_start - arc_extend) % 360;
	    end   = (720 - arc_start) % 360;
	}
	else
	{
	    start = (720 - arc_start) % 360;
	    end   = (720 - arc_start - arc_extend) % 360;
	}

	os << start << " " << end << " " 
	   << int(radius) << " " << int(radius) << " "
	   << int(cx) << " " << int(cy) << " " << line_width << " arc*\n";
    }
    else if (gc.printGC->isFig())
    {
	// We draw the entire arc in one stroke.
	if (from()->isHint())
	{
	    BoxCoordinate line_width = 1;

	    os << ARCARROWHEAD1 << line_width << ARCARROWHEAD2;
	    if (path > 0)
		os << ARCCOUNTERCLOCKWISE;
	    else
		os << ARCCLOCKWISE;
	    os << ARCARROWHEAD3
	       << cx << " " << cy << " "
	       << pos_from[X] << " " << pos_from[Y] << " "
	       << pos_hint[X] << " " << pos_hint[Y] << " "
	       << pos_to[X]   << " " << pos_to[Y]   << " "
	       << ARCARROWHEAD4;
	}
    }

    if (from()->isHint())
    {
	// Draw arrow head at POS_TO
	double alpha = atan2(pos_to[Y] - cy, pos_to[X] - cx);

	if (w != 0)
	{
	    if (path > 0)
		alpha += PI / 2.0;
	    else
		alpha -= PI / 2.0;

	    drawArrowHead(w, exposed, gc, pos_to, alpha);
	}
	else if (gc.printGC->isPostScript())
	{
	    if (path > 0)
		alpha -= PI / 2.0;
	    else
		alpha += PI / 2.0;

	    os << gc.arrowAngle << " " << gc.arrowLength << " " 
	       << (360 + int(alpha * 360.0 / (PI * 2.0))) % 360 << " "
	       << pos_to[X] << " " << pos_to[Y] << " arrowhead*\n";
	}
    }

    if (to()->isHint() && annotation() != 0)
    {
	if (w != 0)
	{
	    annotation()->draw(w, to()->pos(), exposed, gc);
	}
	else
	{
	    annotation()->_print(os, to()->pos(), gc);
	}
    }
}
Beispiel #23
0
/*******************************************************************************************************************//**
 * @brief Program entry point
 *
 * Handles image processing and display of annotated results
 *
 * @param[in] argc command line argument count
 * @param[in] argv command line argument vector
 * @returnS return status
 * @author Christopher D. McMurrough
 **********************************************************************************************************************/
int main(int argc, char** argv)
{
    // validate and parse the command line arguments
    int cameraIndex = 0;
    bool displayMode = true;
    bool flipDisplay = false;
    if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1)
    {
        std::printf("USAGE: <camera_index> <display_mode>\n");
        std::printf("Running with default parameters... \n");
    }
    else
    {
        cameraIndex = atoi(argv[1]);
        displayMode = atoi(argv[2]) > 0;
        flipDisplay = atoi(argv[2]) == 2;
    }

    // initialize the eye camera video capture
    //cv::VideoCapture occulography(cameraIndex);
   cv::VideoCapture occulography("pupil_test.mp4");
   // cv::VideoCapture occulography("test.mov");
    if(!occulography.isOpened())
    {
        std::printf("Unable to initialize camera %u! \n", cameraIndex);
        return 0;
    }
    occulography.set(CV_CAP_PROP_FRAME_WIDTH, CAMERA_FRAME_WIDTH);
    occulography.set(CV_CAP_PROP_FRAME_HEIGHT, CAMERA_FRAME_HEIGHT);
    occulography.set(CV_CAP_PROP_FORMAT, CAMERA_FORMAT);
    occulography.set(CV_CAP_PROP_FPS, CAMERA_FPS);
    occulography.set(CV_CAP_PROP_BRIGHTNESS, CAMERA_BRIGHTNESS);
    occulography.set(CV_CAP_PROP_CONTRAST, CAMERA_CONTRAST);
    occulography.set(CV_CAP_PROP_SATURATION, CAMERA_SATURATION);
    occulography.set(CV_CAP_PROP_HUE, CAMERA_HUE);
    occulography.set(CV_CAP_PROP_GAIN, CAMERA_GAIN);
    occulography.set(CV_CAP_PROP_EXPOSURE, CAMERA_EXPOSURE);
    occulography.set(CV_CAP_PROP_CONVERT_RGB, CAMERA_CONVERT_RGB);

    // intialize the display window if necessary
    if(displayMode)
    {
        cvNamedWindow("eyeImage", CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_FULLSCREEN, CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_AUTOSIZE, CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_ASPECTRATIO, CV_WINDOW_KEEPRATIO);
    }

    // create the pupil tracking object
    PupilTracker tracker;
    tracker.setDisplay(displayMode);

    // store the frame data
    cv::Mat eyeImage;
    //struct PupilData result;
    bool trackingSuccess = false;

    // store the time between frames
    int frameStartTicks, frameEndTicks, processStartTicks, processEndTicks;
    float processTime, totalTime;

    // process data until program termination
    bool isRunning = true;
    while(isRunning)
    {
        // start the timer
        frameStartTicks = clock();

        // attempt to acquire an image frame
        if(occulography.read(eyeImage))
        {
            // process the image frame
            processStartTicks = clock();
            trackingSuccess = tracker.findPupil(eyeImage);
            processEndTicks = clock();
            processTime = ((float)(processEndTicks - processStartTicks)) / CLOCKS_PER_SEC;

            // warn on tracking failure
            if(!trackingSuccess)
            {
                std::printf("Unable to locate pupil! \n");
            }

            // update the display
            if(displayMode)
            {
                cv::Mat displayImage(eyeImage);

                // annotate the image if tracking was successful
                if(trackingSuccess)
                {
                    // draw the pupil center and boundary
                    //cvx::cross(displayImage, result.pupil_center, 5, COLOR_RED);
                    cv::ellipse(displayImage, tracker.getEllipseRectangle(), COLOR_RED);

                    // shade the pupil area
                    cv::Mat annotation(eyeImage.rows, eyeImage.cols, CV_8UC3, 0.0);
                    cv::ellipse(annotation, tracker.getEllipseRectangle(), COLOR_MAGENTA, -1);
                    const double alpha = 0.7;
                    cv::addWeighted(displayImage, alpha, annotation, 1.0 - alpha, 0.0, displayImage);
                }

                if(flipDisplay)
                {
                    // annotate the image
                    cv::Mat displayFlipped;
                    cv::flip(displayImage, displayFlipped, 1);
                    cv::imshow("eyeImage", displayFlipped);

                    // display the annotated image
                    isRunning = cv::waitKey(1) != 'q';
                    displayFlipped.release();
                }
                else
                {
                    // display the image
                    cv::imshow("eyeImage", displayImage);
                    isRunning = cv::waitKey(1) != 'q';
                }

                // release display image
                displayImage.release();
            }
        }
        else
        {
            std::printf("WARNING: Unable to capture image from source!\n");
            occulography.set(CV_CAP_PROP_POS_FRAMES, 0);
            continue;
        }

        // stop the timer and print the elapsed time
        frameEndTicks = clock();
        totalTime = ((float)(frameEndTicks - frameStartTicks)) / CLOCKS_PER_SEC;
        //std::printf("Processing time (pupil, total) (result x,y): %.4f %.4f - %.2f %.2f\n", processTime, totalTime, tracker.getEllipseCentroid().x, tracker.getEllipseCentroid().y);
    }

    // release the video source before exiting
    occulography.release();
}
folly::Future<int32_t> service_with_special_namesSvIf::future_annotation() {
  return apache::thrift::detail::si::future([&] { return annotation(); });
}
Beispiel #25
0
void JavaUpload::globalInit()
{
	if (!JVM::JVMAvailable())
		return;
	
	// locate Java plugins
	try
	{
		JUploadPlugin::registerNatives();

		JClass helper("info.dolezel.fatrat.plugins.helpers.NativeHelpers");
		JClass annotation("info.dolezel.fatrat.plugins.annotations.UploadPluginInfo");
		JClass annConfigDialog("info.dolezel.fatrat.plugins.annotations.ConfigDialog");
		QList<QVariant> args;

		args << "info.dolezel.fatrat.plugins" << annotation.toVariant();

		JArray arr = helper.callStatic("findAnnotatedClasses",
						  JSignature().addString().add("java.lang.Class").retA("java.lang.Class"),
						  args).value<JArray>();
		qDebug() << "Found" << arr.size() << "annotated classes (UploadPluginInfo)";

		int classes = arr.size();
		for (int i = 0; i < classes; i++)
		{
			try
			{
				JClass obj = (jobject) arr.getObject(i);
				JObject ann = obj.getAnnotation(annotation);
				QString name = ann.call("name", JSignature().retString()).toString();
				QString clsName = obj.getClassName();
				JObject instance(obj, JSignature());

				qDebug() << "Class name:" << clsName;
				qDebug() << "Name:" << name;

				JObject cfgDlg = obj.getAnnotation(annConfigDialog);

				JavaEngine e = { "EXT - " + name.toStdString(), clsName.toStdString() };

				if (!cfgDlg.isNull())
					e.configDialog = cfgDlg.call("value", JSignature().retString()).toString();

				if (instance.instanceOf("info.dolezel.fatrat.plugins.extra.URLAcceptableFilter"))
					e.ownAcceptable = instance;
				if (instance.instanceOf("info.dolezel.fatrat.plugins.listeners.ConfigListener"))
					g_configListeners << instance;
				m_engines[clsName] = e;

				qDebug() << "createInstance of " << clsName;

				EngineEntry entry;
				entry.longName = m_engines[clsName].name.c_str();
				entry.shortName = m_engines[clsName].shortName.c_str();
				entry.lpfnAcceptable2 = JavaUpload::acceptable;
				entry.lpfnCreate2 = JavaUpload::createInstance;
				entry.lpfnInit = 0;
				entry.lpfnExit = 0;
				entry.lpfnMultiOptions = 0;

				addTransferClass(entry, Transfer::Upload);
			}
			catch (const RuntimeException& e)
			{
				qDebug() << e.what();
			}
		}
	}
	catch (const RuntimeException& e)
	{
		qDebug() << e.what();
	}
}
Beispiel #26
0
void LoadARFF(const std::string& filename,
              arma::Mat<eT>& matrix,
              DatasetMapper<PolicyType>& info)
{
  // First, open the file.
  std::ifstream ifs;
  ifs.open(filename, std::ios::in | std::ios::binary);

  // if file is not open throw an error (file not found).
  if (!ifs.is_open())
  {
    Log::Fatal << "Cannot open file '" << filename << "'. " << std::endl;
  }

  std::string line;
  size_t dimensionality = 0;
  std::vector<bool> types;
  size_t headerLines = 0;
  while (ifs.good())
  {
    // Read the next line, then strip whitespace from either side.
    std::getline(ifs, line, '\n');
    boost::trim(line);
    ++headerLines;

    // Is the first character a comment, or is the line empty?
    if (line[0] == '%' || line.empty())
      continue; // Ignore this line.

    // If the first character is @, we are looking at @relation, @attribute, or
    // @data.
    if (line[0] == '@')
    {
      typedef boost::tokenizer<boost::escaped_list_separator<char>> Tokenizer;
      std::string separators = " \t%"; // Split on comments too.
      boost::escaped_list_separator<char> sep("\\", separators, "{\"");
      Tokenizer tok(line, sep);
      Tokenizer::iterator it = tok.begin();

      // Get the annotation we are looking at.
      std::string annotation(*it);
      std::transform(annotation.begin(), annotation.end(), annotation.begin(),
            ::tolower);

      if (annotation == "@relation")
      {
        // We don't actually have anything to do with the name of the dataset.
        continue;
      }
      else if (annotation == "@attribute")
      {
        ++dimensionality;
        // We need to mark this dimension with its according type.
        ++it; // Ignore the dimension name.
        std::string dimType = *(++it);
        std::transform(dimType.begin(), dimType.end(), dimType.begin(),
            ::tolower);

        if (dimType == "numeric" || dimType == "integer" || dimType == "real")
        {
          types.push_back(false); // The feature is numeric.
        }
        else if (dimType == "string")
        {
          types.push_back(true); // The feature is categorical.
        }
        else if (dimType[0] == '{')
        {
          throw std::logic_error("list of ARFF values not yet supported");
        }
      }
      else if (annotation == "@data")
      {
        // We are in the data section.  So we can move out of this loop.
        break;
      }
      else
      {
        throw std::runtime_error("unknown ARFF annotation '" + (*tok.begin()) +
            "'");
      }
    }
  }

  if (ifs.eof())
    throw std::runtime_error("no @data section found");

  // Reset the DatasetInfo object, if needed.
  if (info.Dimensionality() == 0)
  {
    info = DatasetMapper<PolicyType>(dimensionality);
  }
  else if (info.Dimensionality() != dimensionality)
  {
    std::ostringstream oss;
    oss << "data::LoadARFF(): given DatasetInfo has dimensionality "
        << info.Dimensionality() << ", but data has dimensionality "
        << dimensionality;
    throw std::invalid_argument(oss.str());
  }

  for (size_t i = 0; i < types.size(); ++i)
  {
    if (types[i])
      info.Type(i) = Datatype::categorical;
    else
      info.Type(i) = Datatype::numeric;
  }

  // We need to find out how many lines of data are in the file.
  std::streampos pos = ifs.tellg();
  size_t row = 0;
  while (ifs.good())
  {
    std::getline(ifs, line, '\n');
    ++row;
  }
  // Uncount the EOF row.
  --row;

  // Since we've hit the EOF, we have to call clear() so we can seek again.
  ifs.clear();
  ifs.seekg(pos);

  // Now, set the size of the matrix.
  matrix.set_size(dimensionality, row);

  // Now we are looking at the @data section.
  row = 0;
  while (ifs.good())
  {
    std::getline(ifs, line, '\n');
    boost::trim(line);
    // Each line of the @data section must be a CSV (except sparse data, which
    // we will handle later).  So now we can tokenize the
    // CSV and parse it.  The '?' representing a missing value is not allowed,
    // so if that occurs we throw an exception.  We also throw an exception if
    // any piece of data does not match its type (categorical or numeric).

    // If the first character is {, it is sparse data, and we can just say this
    // is not handled for now...
    if (line[0] == '{')
      throw std::runtime_error("cannot yet parse sparse ARFF data");

    // Tokenize the line.
    typedef boost::tokenizer<boost::escaped_list_separator<char>> Tokenizer;
    boost::escaped_list_separator<char> sep("\\", ",", "\"");
    Tokenizer tok(line, sep);

    size_t col = 0;
    std::stringstream token;
    for (Tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
    {
      // Check that we are not too many columns in.
      if (col >= matrix.n_rows)
      {
        std::stringstream error;
        error << "Too many columns in line " << (headerLines + row) << ".";
        throw std::runtime_error(error.str());
      }

      // What should this token be?
      if (info.Type(col) == Datatype::categorical)
      {
        // Strip spaces before mapping.
        std::string token = *it;
        boost::trim(token);
        // We load transposed.
        matrix(col, row) = info.template MapString<eT>(token, col);
      }
      else if (info.Type(col) == Datatype::numeric)
      {
        // Attempt to read as numeric.
        token.clear();
        token.str(*it);

        eT val = eT(0);
        token >> val;

        if (token.fail())
        {
          // Check for NaN or inf.
          if (!IsNaNInf(val, token.str()))
          {
            // Okay, it's not NaN or inf.  If it's '?', we issue a specific
            // error, otherwise we issue a general error.
            std::stringstream error;
            std::string tokenStr = token.str();
            boost::trim(tokenStr);
            if (tokenStr == "?")
              error << "Missing values ('?') not supported, ";
            else
              error << "Parse error ";
            error << "at line " << (headerLines + row) << " token " << col
                << ": \"" << tokenStr << "\".";
            throw std::runtime_error(error.str());
          }
        }

        // If we made it to here, we have a value.
        matrix(col, row) = val; // We load transposed.
      }

      ++col;
    }
    ++row;
  }
Beispiel #27
0
void JavaExtractor::globalInit()
{
	try {
		JClass helper("info.dolezel.fatrat.plugins.helpers.NativeHelpers");
		JClass annotation("info.dolezel.fatrat.plugins.annotations.ExtractorPluginInfo");

		JExtractorPlugin::registerNatives();

		JArgs args;

		args << "info.dolezel.fatrat.plugins" << annotation.toVariant();

		JArray arr = helper.callStatic("findAnnotatedClasses",
						  JSignature().addString().add("java.lang.Class").retA("java.lang.Class"),
						  args).value<JArray>();
		qDebug() << "Found" << arr.size() << "annotated classes (ExtractorPluginInfo)";

		int classes = arr.size();
		for (int i = 0; i < classes; i++)
		{
			try
			{
				JClass obj = (jobject) arr.getObject(i);
				JObject ann = obj.getAnnotation(annotation);
				QString regexp = ann.call("regexp", JSignature().retString()).toString();
				QString name = ann.call("name", JSignature().retString()).toString();
				QString targetClassName = ann.call("transferClassName", JSignature().retString()).toString();
				QString clsName = obj.getClassName();
				JObject instance(obj, JSignature());

				if (targetClassName.isEmpty())
				{
					JClass cls = JClass(ann.call("transferClass", JSignature().ret("java.lang.Class")).value<JObject>());
					if (!cls.isNull() && cls.getClassName() != "java.lang.Object")
						targetClassName = cls.getClassName();
				}

				qDebug() << "Class name:" << clsName;
				qDebug() << "Name:" << name;
				qDebug() << "Regexp:" << regexp;

				JavaEngine e = { "EXT - " + name.toStdString(), clsName.toStdString(), QRegExp(regexp) };

				if (instance.instanceOf("info.dolezel.fatrat.plugins.extra.URLAcceptableFilter"))
					e.ownAcceptable = instance;
				if (instance.instanceOf("info.dolezel.fatrat.plugins.listeners.ConfigListener"))
					g_configListeners << instance;
				e.targetClass = targetClassName;

				m_engines[clsName] = e;

				EngineEntry entry;
				entry.longName = m_engines[clsName].name.c_str();
				entry.shortName = m_engines[clsName].shortName.c_str();
				entry.lpfnAcceptable2 = JavaExtractor::acceptable;
				entry.lpfnCreate2 = JavaExtractor::createInstance;
				entry.lpfnInit = 0;
				entry.lpfnExit = 0;
				entry.lpfnMultiOptions = 0;

				addTransferClass(entry, Transfer::Download);
			}
			catch (const RuntimeException& e)
			{
				qDebug() << e.what();
			}
		}
	}
	catch (const RuntimeException& e)
	{
		qDebug() << e.what();
	}
}
void XSPFParser::readTrack(QXmlStreamReader & xml, MediaInfo & mediaInfo) const {
	while (!xml.atEnd() && !_stop) {
		xml.readNext();

		QString element(xml.name().toString());

		if (xml.isStartElement()) {

			//Filename
			if (element == XSPF_LOCATION) {
				QUrl url = QUrl::fromEncoded(xml.readElementText().toUtf8());
				QString location(url.toString());
				bool isUrl = MediaInfo::isUrl(location);
				mediaInfo.setUrl(isUrl);
				if (isUrl) {
					mediaInfo.setFileName(location);
				} else {
					QString path(QFileInfo(_filename).path());
					mediaInfo.setFileName(Util::canonicalFilePath(path, location));
				}
			}

			//Unique ID
			else if (element == XSPF_IDENTIFIER) {
				QString identifier(xml.readElementText());
				//FIXME not implemented yet
			}

			//Artist
			else if (element == XSPF_CREATOR) {
				QString creator(xml.readElementText());
				mediaInfo.insertMetadata(MediaInfo::Artist, creator);
			}

			//Album
			else if (element == XSPF_ALBUM) {
				QString album(xml.readElementText());
				mediaInfo.insertMetadata(MediaInfo::Album, album);
			}

			//Track number
			else if (element == XSPF_TRACKNUM) {
				QString trackNum(xml.readElementText());
				mediaInfo.insertMetadata(MediaInfo::TrackNumber, trackNum);
			}

			//Title
			else if (element == XSPF_TITLE) {
				QString title(xml.readElementText());
				mediaInfo.insertMetadata(MediaInfo::Title, title);
			}

			//Comment
			else if (element == XSPF_ANNOTATION) {
				QString annotation(xml.readElementText());
				if (mediaInfo.metadataValue(MediaInfo::Title).isEmpty()) {
					//Some people didn't understand how XSPF works
					//and confused annotation with title
					mediaInfo.insertMetadata(MediaInfo::Title, annotation);
				}
				mediaInfo.insertMetadata(MediaInfo::Comment, annotation);
			}

			//Length
			else if (element == XSPF_DURATION) {
				int duration = xml.readElementText().toInt();
				//XSPF gives us the duration in milliseconds
				//Let's convert it to seconds
				mediaInfo.setLength(duration / 1000);
			}

			//Album art URL
			else if (element == XSPF_IMAGE) {
				QString image(xml.readElementText());
				//FIXME not implemented yet
				//mediaInfo.insertMetadata(MediaInfo::AlbumArt, image);
			}

			//URL of the original web page
			else if (element == XSPF_INFO) {
				QString info(xml.readElementText());
				mediaInfo.insertMetadata(MediaInfo::URL, info);
			}

			//Meta
			else if (element == XSPF_META) {

				//These tags are specific to foobar2000 XSPF plugin

				QXmlStreamAttributes attributes = xml.attributes();

				//Date
				if (attributes.hasAttribute(XSPF_FOOBAR2000_DATE)) {
					QString date(attributes.value(XSPF_FOOBAR2000_DATE).toString());
					mediaInfo.insertMetadata(MediaInfo::Year, date);
				}

				//Genre
				else if (attributes.hasAttribute(XSPF_FOOBAR2000_GENRE)) {
					QString genre(attributes.value(XSPF_FOOBAR2000_GENRE).toString());
					mediaInfo.insertMetadata(MediaInfo::Genre, genre);
				}
			}

			else if (element == XSPF_EXTENSION) {
				QString xspfNamespace(xml.attributes().value(XSPF_APPLICATION).toString());

				if (xspfNamespace == XSPF_QUARKPLAYER_NAMESPACE) {
					while (!xml.atEnd() && !_stop) {
						xml.readNext();

						QString extensionElement(xml.name().toString());
						if (xml.isStartElement()) {

							if (extensionElement == XSPF_QUARKPLAYER_CUE_START_INDEX) {
								QString cueStartIndex(xml.readElementText());
								mediaInfo.setCueStartIndex(cueStartIndex);
							}

							else if (extensionElement == XSPF_QUARKPLAYER_CUE_END_INDEX) {
								QString cueEndIndex(xml.readElementText());
								mediaInfo.setCueEndIndex(cueEndIndex);
							}

							else if (extensionElement == XSPF_QUARKPLAYER_YEAR) {
								QString year(xml.readElementText());
								mediaInfo.insertMetadata(MediaInfo::Year, year);
							}

							else if (extensionElement == XSPF_QUARKPLAYER_GENRE) {
								QString genre(xml.readElementText());
								mediaInfo.insertMetadata(MediaInfo::Genre, genre);
							}
						}

						if (xml.isEndElement()) {
							if (extensionElement == XSPF_EXTENSION) {
								break;
							}
						}
					}
				}
			}
		}

		if (xml.isEndElement()) {
			if (element == XSPF_TRACK) {
				return;
			}
		}
	}
}
/*******************************************************************************************************************//**
 * @brief Program entry point
 *
 * Handles image processing and display of annotated results
 *
 * @param[in] argc command line argument count
 * @param[in] argv command line argument vector
 * @returnS return status
 * @author Christopher D. McMurrough
 **********************************************************************************************************************/
int main(int argc, char** argv)
{
    // validate and parse the command line arguments
    int cameraIndex = 0;
    bool displayMode = true;
    bool flipDisplay = false;
    if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1)
    {
        std::printf("USAGE: <camera_index> <display_mode>\n");
        std::printf("Running with default parameters... \n");
    }
    else
    {
        cameraIndex = atoi(argv[1]);
        displayMode = atoi(argv[2]) > 0;
        flipDisplay = atoi(argv[2]) == 2;
    }

    // initialize the eye camera video capture
//    cv::VideoCapture occulography(cameraIndex);
    cv::VideoCapture occulography("pupil_test.mp4");

    if(!occulography.isOpened())
    {
        std::printf("Unable to initialize camera %u! \n", cameraIndex);
        return 0;
    }
    // THESE ARE FOR GETTING THE PROPERTIES OF THE CAMERA IF APPLICABLE

    std::cout<<"width "<< occulography.get(CV_CAP_PROP_FRAME_WIDTH)  << std::endl;
    std::cout<<"height "<< occulography.get(CV_CAP_PROP_FRAME_WIDTH)  << std::endl;

    

    // std::cout<<"format "<< occulography.get(CV_CAP_PROP_FORMAT)  << std::endl;
    // std::cout<<"fps "<< occulography.get(CV_CAP_PROP_FPS)  << std::endl;
    // std::cout<<"brightness "<< occulography.get(CV_CAP_PROP_BRIGHTNESS)  << std::endl;
    // std::cout<<"contrast "<< occulography.get(CV_CAP_PROP_CONTRAST)  << std::endl;
    // std::cout<<"saturation "<< occulography.get(CV_CAP_PROP_SATURATION)  << std::endl;
    // std::cout<<"hue "<< occulography.get(CV_CAP_PROP_HUE)  << std::endl;
    // std::cout<<"gain "<< occulography.get(CV_CAP_PROP_GAIN)  << std::endl;
    // std::cout<<"exposure "<< occulography.get(CV_CAP_PROP_EXPOSURE)  << std::endl;
    // std::cout<<"convert rgb "<< occulography.get(CV_CAP_PROP_CONVERT_RGB)  << std::endl;

    // THESE ARE FOR SETTING THE PROPERTIES OF THE CAMERA IF APPLICABLE
    occulography.set(CV_CAP_PROP_FRAME_WIDTH, CAMERA_FRAME_WIDTH);
    occulography.set(CV_CAP_PROP_FRAME_HEIGHT, CAMERA_FRAME_HEIGHT);
    // occulography.set(CV_CAP_PROP_FORMAT, CAMERA_FORMAT);
    // occulography.set(CV_CAP_PROP_FPS, CAMERA_FPS);
    occulography.set(CV_CAP_PROP_BRIGHTNESS, CAMERA_BRIGHTNESS);
    occulography.set(CV_CAP_PROP_CONTRAST, CAMERA_CONTRAST);
    occulography.set(CV_CAP_PROP_SATURATION, CAMERA_SATURATION);
    // occulography.set(CV_CAP_PROP_HUE, CAMERA_HUE);
    // occulography.set(CV_CAP_PROP_GAIN, CAMERA_GAIN);
    // occulography.set(CV_CAP_PROP_EXPOSURE, CAMERA_EXPOSURE);
    // occulography.set(CV_CAP_PROP_CONVERT_RGB, CAMERA_CONVERT_RGB);

    // intialize the display window if necessary
    if(displayMode)
    {
        cvNamedWindow("eyeImage", CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_FULLSCREEN, CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_AUTOSIZE, CV_WINDOW_NORMAL);
        cvSetWindowProperty("eyeImage", CV_WND_PROP_ASPECTRATIO, CV_WINDOW_KEEPRATIO);
    }

    // create the pupil tracking object
    PupilTracker tracker;
    tracker.setDisplay(displayMode);

    // store the frame data
    cv::Mat eyeImage;
    //struct PupilData result;
    bool trackingSuccess = false;

    // store the time between frames
    int frameStartTicks, frameEndTicks, processStartTicks, processEndTicks;
    float processTime, totalTime;

    // process data until program termination
    bool isRunning = true;
    while(isRunning)
    {
        // start the timer
        frameStartTicks = clock();

        // attempt to acquire an image frame
        if(occulography.read(eyeImage))
        {
            // process the image frame
            processStartTicks = clock();
            trackingSuccess = tracker.findPupil(eyeImage);
            processEndTicks = clock();
            processTime = ((float)(processEndTicks - processStartTicks)) / CLOCKS_PER_SEC;

            // warn on tracking failure
            if(!trackingSuccess)
            {
                std::cout<< "Unable to locate pupil!" << std::endl;
            }

            // update the display
            if(displayMode)
            {
                cv::Mat displayImage(eyeImage);

                // annotate the image if tracking was successful
                if(trackingSuccess)
                {
                    // draw the pupil center and boundary
                    //cvx::cross(displayImage, result.pupil_center, 5, COLOR_RED);
                    cv::ellipse(displayImage, tracker.getEllipseRectangle(), COLOR_BLUE, 2);

                    // shade the pupil area
                    cv::Mat annotation(eyeImage.rows, eyeImage.cols, CV_8UC3, 0.0);
                    cv::RotatedRect my_rotated_rect_property;
                    my_rotated_rect_property = tracker.getEllipseRectangle();
                    cv::Point2f Center;
                    Center = my_rotated_rect_property.center;

                    double x1, y1, x2, y2;
                    
                    x1 = Center.x - 40; y1 = Center.y - 40; x2 = Center.x + 40; y2 = Center.y + 40;

                    // Draw a square/rectangle around the ellipse based off of the center 
                    // This is for the rectangle
                    cv::Point x1y1 = cv::Point(x1, y1);
                    cv::Point x2y2 = cv::Point(x2, y2);
                    // This is for the lines around the rectangle 
                    cv::Point x1y2 = cv::Point(x1, y2);
                    cv::Point x2y1 = cv::Point(x2, y1);

                    // here is the math to draw the lines 
                    // for the horizontal line
                    cv::Point horizontal_start = cv::Point(x1-20, (y1+y2)/2);
                    cv::Point horizontal_end = cv::Point(x1+100, (y1+y2)/2);
                    
                    // for the vertical line
                    cv::Point vertical_start = cv::Point((x1+x2)/2, y1-20);
                    cv::Point vertical_end = cv::Point((x1+x2)/2, y1+100);
                    
                    // done with the lines

                    cv::ellipse(annotation, tracker.getEllipseRectangle(), COLOR_PURPLE, -1);
                    const double alpha = 0.7;
                    cv::addWeighted(displayImage, alpha, annotation, 1.0 - alpha, 0.0, displayImage);
                    // The centre is actually a tiny circle (neat trick)
                    cv::circle(displayImage, Center, 2.5, COLOR_RED, 2, 4);
                    // The bounding rectangle based off of the centre
                    cv::rectangle(displayImage, x1y1, x2y2, COLOR_GREEN, 1);
                    // The lines across the rectangle
                    cv::line(displayImage, horizontal_start, horizontal_end, COLOR_GREEN, 1);
                    cv::line(displayImage, vertical_start, vertical_end, COLOR_GREEN, 1);
                    int fontFace = cv::FONT_HERSHEY_PLAIN;
                    double scale = 1.5;
                    int thickness = 1;

                    int baseline = 0;
                    char pupil_center[25];
                    char ellipse_size[25];
                    char pupil_angle[25];
                    sprintf(pupil_center, "Pupil Center: (%.2lf, %.2lf)",  Center.x, Center.y);
                    sprintf(ellipse_size, "Pupil Size: (%.2lf, %.2lf)",  my_rotated_rect_property.size.width,my_rotated_rect_property.size.height);
 					sprintf(pupil_angle, "Pupil Angle: (%.2lf)",  my_rotated_rect_property.angle);
                    cv::putText(displayImage, "OptiFind :: Real Time Eye Tracker", cv::Point(40, 40), fontFace, 1, COLOR_WHITE, thickness, 8);
                    cv::putText(displayImage, pupil_center, cv::Point(350, 315), fontFace, 1, COLOR_WHITE, thickness, 8);
                    cv::putText(displayImage, ellipse_size, cv::Point(350, 330), fontFace, 1, COLOR_WHITE, thickness, 8);
                    cv::putText(displayImage, pupil_angle, cv::Point(350, 345), fontFace, 1, COLOR_WHITE, thickness, 8);
                 }

                if(flipDisplay)
                {
                    // annotate the image
                    cv::Mat displayFlipped;
                    cv::flip(displayImage, displayFlipped, 1);
                    cv::imshow("eyeImage", displayFlipped);

                    // display the annotated image
                    isRunning = cv::waitKey(1) != 'q';
                    char key = cvWaitKey(10);
                    // If the user pressed 'ESC' Key then break the loop and exit the program
                    if (key == 27)
                        break;
                    displayFlipped.release();
                }
                else
                {
                    // display the image
                    cv::imshow("eyeImage", displayImage);
                    //char key1 = cvWaitKey(0);
                    isRunning = cv::waitKey(1) != 'q';
                    char key = cvWaitKey(10);
                    // If the user pressed 'ESC' Key then break the loop and exit the program
                    if (key == 27)
                        break;
                }
                // release display image
                displayImage.release();
            }
        }
        else
        {
            std::cout<<"WARNING: Unable to capture image from source!\n"<<std::endl;
            std::cout<< "Reading the video from frame 0 again!" << std::endl;
            occulography.set(CV_CAP_PROP_POS_FRAMES, 0);
            continue;
        }

        // stop the timer and print the elapsed time
        // frameEndTicks = clock();
        // totalTime = ((float)(frameEndTicks - frameStartTicks)) / CLOCKS_PER_SEC;
        // std::printf("Processing time (pupil, total) (result x,y): %.4f %.4f - %.2f %.2f\n", processTime, totalTime, tracker.getEllipseRectangle().center.x, tracker.getEllipseRectangle().center.y);
        //std::cout<< "Processing time (pupil)"<< processTime << "total time" <<  totalTime << "pupil center" << tracker.getEllipseRectangle().center << std::endl;
       
    }

    // release the video source before exiting
    occulography.release();
}
Beispiel #30
0
void MoveViewController::showContextMenu(const QPoint &pos) {
    QMenu *menu = new QMenu(this);

    this->pos_rightclick->setX(pos.x());
    this->pos_rightclick->setY(pos.y());

    QMenu *subMoveAnnotation = new QMenu(menu);
    subMoveAnnotation->setTitle(this->tr("Move Annotation"));

    QAction *annBlunder = subMoveAnnotation->addAction(this->tr("?? Blunder"));
    QAction *annMistake = subMoveAnnotation->addAction(this->tr("? Mistake"));
    QAction *annDubious = subMoveAnnotation->addAction(this->tr("?! Dubious Move"));
    QAction *annInteresting = subMoveAnnotation->addAction(this->tr("!? Interesting Move"));
    QAction *annGood = subMoveAnnotation->addAction(this->tr("! Good Move"));
    QAction *annBrilliant = subMoveAnnotation->addAction(this->tr("!! Brilliant Move"));
    QAction *annEmpty = subMoveAnnotation->addAction(this->tr("No Annotation"));

    connect(annBlunder, &QAction::triggered, this, [this] { annotation(chess::NAG_BLUNDER, 0, 9); });
    connect(annMistake, &QAction::triggered, this, [this] { annotation(chess::NAG_MISTAKE, 0, 9); });
    connect(annDubious, &QAction::triggered, this, [this] { annotation(chess::NAG_DUBIOUS_MOVE, 0, 9); });
    connect(annInteresting, &QAction::triggered, this, [this] { annotation(chess::NAG_SPECULATIVE_MOVE, 0, 9); });
    connect(annGood, &QAction::triggered, this, [this] { annotation(chess::NAG_GOOD_MOVE, 0, 9); });
    connect(annBrilliant, &QAction::triggered, this, [this] { annotation(chess::NAG_BRILLIANT_MOVE, 0, 9); });
    connect(annEmpty, &QAction::triggered, this, [this] { annotation(0, 0, 9); });

    QMenu *subPosAnnotation = new QMenu(menu);
    subPosAnnotation->setTitle(this->tr("Position Annotation"));

    QAction *posUnclear = subPosAnnotation->addAction(this->tr("∞ Unclear"));
    QAction *posDrawish = subPosAnnotation->addAction(this->tr("= Drawish"));
    QAction *posWhiteModBetter = subPosAnnotation->addAction(this->tr("+/= Slight Advantage White"));
    QAction *posBlackModBetter = subPosAnnotation->addAction(this->tr("=/+ Slight Advantage Black"));
    QAction *posWhiteMuchBetter = subPosAnnotation->addAction(this->tr("+- White Better"));
    QAction *posBlackMuchBetter = subPosAnnotation->addAction(this->tr("-+ Black Better"));
    QAction *posNoAnnotation = subPosAnnotation->addAction(this->tr("No Annotation"));

    connect(posUnclear, &QAction::triggered, this, [this] { annotation(chess::NAG_UNCLEAR_POSITION, 9, 23); });
    connect(posDrawish, &QAction::triggered, this, [this] { annotation(chess::NAG_DRAWISH_POSITION, 9, 23); });
    connect(posWhiteModBetter, &QAction::triggered, this, [this] { annotation(chess::NAG_WHITE_MODERATE_ADVANTAGE, 9, 23); });
    connect(posBlackModBetter, &QAction::triggered, this, [this] { annotation(chess::NAG_BLACK_MODERATE_ADVANTAGE, 9, 23); });
    connect(posWhiteMuchBetter, &QAction::triggered, this, [this] { annotation(chess::NAG_WHITE_DECISIVE_ADVANTAGE, 9, 23); });
    connect(posBlackMuchBetter, &QAction::triggered, this, [this] { annotation(chess::NAG_BLACK_DECISIVE_ADVANTAGE, 9, 23); });
    connect(posNoAnnotation, &QAction::triggered, this, [this] { annotation(0, 9, 23); });

    posUnclear->setData(chess::NAG_UNCLEAR_POSITION);
    posDrawish->setData(chess::NAG_DRAWISH_POSITION);
    posWhiteModBetter->setData(chess::NAG_WHITE_MODERATE_ADVANTAGE);
    posBlackModBetter->setData(chess::NAG_BLACK_MODERATE_ADVANTAGE);
    posWhiteMuchBetter->setData(chess::NAG_WHITE_DECISIVE_ADVANTAGE);
    posBlackMuchBetter->setData(chess::NAG_BLACK_DECISIVE_ADVANTAGE);
    posNoAnnotation->setData(0);

    QAction *addComment = menu->addAction(this->tr("Add/Edit Comment"));
    QAction *delComment = menu->addAction(this->tr("Delete Comment"));

    menu->addMenu(subMoveAnnotation);
    menu->addMenu(subPosAnnotation);

    connect(addComment, &QAction::triggered, this, &MoveViewController::addComment);
    connect(delComment, &QAction::triggered, this, &MoveViewController::deleteComment);

    QAction *remAnnotation = menu->addAction(this->tr("Remove Annotations"));
    connect(remAnnotation, &QAction::triggered, this, &MoveViewController::removeAnnotations);

    menu->addSeparator();

    QAction *varUp = menu->addAction(this->tr("Move Variant Up"));
    QAction *varDown = menu->addAction(this->tr("Move Variant Down"));
    QAction *delVar = menu->addAction(this->tr("Delete Variant"));
    QAction *delHere = menu->addAction(this->tr("Delete From Here"));

    connect(varUp, &QAction::triggered, this, &MoveViewController::variantUp);
    connect(varDown, &QAction::triggered, this, &MoveViewController::variantDown);
    connect(delVar, &QAction::triggered, this, &MoveViewController::deleteVariant);
    connect(delHere, &QAction::triggered, this, &MoveViewController::deleteFromHere);


    menu->addSeparator();

    QAction *delAllComments = menu->addAction(this->tr("Delete All Comments"));
    QAction *delAllVariants = menu->addAction(this->tr("Delete All Variants"));

    connect(delAllComments, &QAction::triggered, this, &MoveViewController::removeAllComments);
    connect(delAllVariants, &QAction::triggered, this, &MoveViewController::removeAllVariants);

    menu->exec(QCursor::pos());
}