Exemplo n.º 1
0
Object3D* SceneParser::parseObject(char token[MAX_PARSER_TOKEN_LENGTH]) {
	Object3D *answer = NULL;
	if (!strcmp(token, "Group")) {
		answer = (Object3D*)parseGroup();
	}
	else if (!strcmp(token, "Sphere")) {
		answer = (Object3D*)parseSphere();
	}
	else if (!strcmp(token, "Plane")) {
		answer = (Object3D*)parsePlane();
	}
	else if (!strcmp(token, "Triangle")) {
		answer = (Object3D*)parseTriangle();
	}
	else if (!strcmp(token, "TriangleMesh")) {
		answer = (Object3D*)parseTriangleMesh();
	}
	else if (!strcmp(token, "Transform")) {
		answer = (Object3D*)parseTransform();
	}
	else {
		printf("Unknown token in parseObject: '%s'\n", token);
		exit(0);
	}
	return answer;
}
Exemplo n.º 2
0
void SceneParser::parseFile() {
	//
	// at the top level, the scene can have a camera, 
	// background color and a group of objects
	// (we add lights and other things in future assignments)
	//
	char token[MAX_PARSER_TOKEN_LENGTH];
	while (getToken(token)) {
		if (!strcmp(token, "OrthographicCamera")) {
			parseOrthographicCamera();
		}
		else if (!strcmp(token, "PerspectiveCamera")) {
			parsePerspectiveCamera();
		}
		else if (!strcmp(token, "Background")) {
			parseBackground();
		}
		else if (!strcmp(token, "Lights")) {
			parseLights();
		}
		else if (!strcmp(token, "Materials")) {
			parseMaterials();
		}
		else if (!strcmp(token, "Group")) {
			group = parseGroup();
		}
		else {
			printf("Unknown token in parseFile: '%s'\n", token);
			exit(0);
		}
	}
}
Exemplo n.º 3
0
int DrawTool::processInputFile(const char * inputFile)
{
    try {
        crispr::xml::parser xml_parser;
        xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile);
        xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement();
        
        if( !root_elem ) throw(crispr::xml_exception(__FILE__, 
                                                     __LINE__, 
                                                     __PRETTY_FUNCTION__, 
                                                     "empty XML document" ));

        // get the children
        for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); 
             currentElement != NULL; 
             currentElement = currentElement->getNextElementSibling()) {
                
            // is this a group element
            if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) {
                char * c_group_id = tc(currentElement->getAttribute(xml_parser.attr_Gid()));
                std::string group_id = c_group_id;
                if (DT_Subset) {
                    
                    // we only want some of the groups look at DT_Groups
                    if (DT_Groups.find(group_id.substr(1)) != DT_Groups.end() ) {
                        parseGroup(currentElement, xml_parser);
                        
                    }
                } else {
                    parseGroup(currentElement, xml_parser);   
                }
                xr(&c_group_id);
            }
            
        }
    } catch (crispr::xml_exception& e) {
        std::cerr<<e.what()<<std::endl;
        return 1;
    } catch (crispr::runtime_exception& e) {
        std::cerr<<e.what()<<std::endl;
    }
    
    return 0;
}
Exemplo n.º 4
0
	void ImageExportSerializer::parseImage(pugi::xml_node _node)
	{
		DataPtr data = Data::CreateInstance();
		data->setType(DataTypeManager::getInstance().getType("Image"));
		data->setPropertyValue("Name", _node.attribute("name").value());

		DataManager::getInstance().getRoot()->addChild(data);

		pugi::xpath_node_set nodes = _node.select_nodes("Group");
		for (pugi::xpath_node_set::const_iterator node = nodes.begin(); node != nodes.end(); node ++)
			parseGroup((*node).node(), data);
	}
/*
 * Begin: Parse KeePassX XML Files.
 */
void KeePassXmlStreamReader::parseDatabase(){
    resetMembers();
    while(xmlReader.readNextStartElement()){
        if(xmlReader.name() == "group"){
            qDebug("Found group in database.");
            parseGroup();
        }else{
            qDebug("Skipping database child element: %s", xmlReader.name().toString().toUtf8().constData());
            xmlReader.skipCurrentElement();
        }
    }
    qDebug("Leaving parseDatabase...");
}
Exemplo n.º 6
0
static Node* parseQuantifier(const char*& nextChar,Uptr groupDepth)
{
	Node* result = parseGroup(nextChar,groupDepth);

	switch(*nextChar)
	{
	case '+': ++nextChar; result = new OneOrMore(result); break;
	case '*': ++nextChar; result = new ZeroOrMore(result); break;
	case '?': ++nextChar; result = new Optional(result); break;
	};

	return result;
}
Exemplo n.º 7
0
bool Preprocessor::parseElseGroup(IfSection *ifSection)
{
    //cout << "parse else group" << endl;
    TokenSection tokenSection = readLine();
    if(tokenSection.count() == 0)
        return false;

    ElseDirective *elseDirective = createNode<ElseDirective>(m_memoryPool, ifSection);
    ifSection->setElseGroup(elseDirective);
    elseDirective->setTokenSection(tokenSection);
    parseGroup(elseDirective);
    return true;
}
Exemplo n.º 8
0
bool MorkParser::parse()
{
	bool Result = true;
	char cur = 0;

	// Run over mork chars and parse each term
	cur = nextChar();

	int i = 0;

	while ( Result && cur )
	{
		if ( !isWhiteSpace( cur ) )
		{
			i++;
			// Figure out what a term
			switch ( cur )
			{
			case '<':
				// Dict
				Result = parseDict();
				break;
			case '/':
				// Comment
				Result = parseComment();
				break;
			case '{':
				Result = parseTable();
				// Table
				break;
			case '[':
				Result = parseRow( 0, 0 );
				// Row
				break;
			case '@':
				Result = parseGroup();
				// Group
				break;
			default:
				error_ = DefectedFormat;
				Result = false;
				break;
			}
		}

		// Get next char
		cur = nextChar();
	}

	return Result;
}
Exemplo n.º 9
0
//parses an "ifdef-like" directive, like #ifdef and #ifndef :)
//# ifdef identifier newline group[opt]
bool Preprocessor::parseIfdefLikeDirective(IfdefLikeDirective *node)
{
    Q_ASSERT(node->toItemComposite());
    const TokenSection tokenSection = readLine();
    const QVector<int> cleanedLine = cleanTokenRange(tokenSection);

    if(cleanedLine.count() < 3)
        return false;

    node->setTokenSection(tokenSection);
    node->setIdentifier(TokenList(m_tokenContainer, QVector<int>() << cleanedLine.at(2)));
    parseGroup(node);

    return true;
}
Exemplo n.º 10
0
int SanitiseTool::processInputFile(const char * inputFile)
{
    try {
        crispr::xml::parser xml_parser;
        xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile);
        xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement();
        if (!root_elem) {
            throw crispr::xml_exception(__FILE__, 
                                        __LINE__, 
                                        __PRETTY_FUNCTION__, 
                                        "problem when parsing xml file");
        }
        if (ST_OutputFile.empty()) {
            ST_OutputFile = inputFile;
        }

        for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); 
             currentElement != NULL; 
             currentElement = currentElement->getNextElementSibling()) {

                
                // is this a group element
                if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) {
                    
                    XMLCh * x_next_group_num = tc( getNextGroupS().c_str());
                    currentElement->setAttribute(xml_parser.attr_Gid(), x_next_group_num);
                    incrementGroup();
                    xr(&x_next_group_num);
                    // the user wants to change any of these 
                    if (ST_Spacers || ST_Repeats || ST_Flank || ST_contigs) {
                        parseGroup(currentElement, xml_parser);
                    }
                }
            
            setNextRepeat(1);
            setNextContig(1);
            setNextRepeat(1);
            setNextSpacer(1);
        }
        xml_parser.printDOMToFile(ST_OutputFile, input_doc_obj);
    } catch (crispr::xml_exception& e) {
        std::cerr<<e.what()<<std::endl;
        return 1;
    }
    
    return 0;
}
Exemplo n.º 11
0
void scene::parse(const char *filename)
{
    //some default values in case parsing fails
    myObjGroup = NULL;
    bgColor = Vec3f(0.5,0.5,0.5);
    ambLight = Vec3f(0.5,0.5,0.5);
    eye = Vec3f(0,0,0);
    lookAt = Vec3f(0,0,-1);
    up = Vec3f(0,1,0);
    fovy = 45;
    file = NULL;
    curline = 1;

    //the file-extension needs to be "ray"
    assert(filename != NULL);
    const char *ext = &filename[strlen(filename)-4];
    assert(!strcmp(ext,".ray"));
    fopen_s(&file, filename, "r");
    assert(file != NULL);

    char token[MAX_PARSER_TOKEN_LENGTH];

    //prime the parser pipe
    parse_char = fgetc(file);

    while (getToken(token))
    {
        if(!strcmp(token, "Background"))
            parseBackground();
        else if(!strcmp(token, "Camera"))
            parseCamera();
        else if(!strcmp(token, "Materials"))
            parseMaterials();
        else if(!strcmp(token, "Group"))
            myObjGroup = parseGroup();
        else if(!strcmp(token, "Lights"))
            parseLights();
        else
        {
            cout<<"Unknown token in parseFile: '"<<token<<
                "' at input line "<<curline<<"\n";
            exit(-1);
        }
    }
}
Exemplo n.º 12
0
void KeePassXmlStreamReader::parseGroup(){
    while(xmlReader.readNextStartElement()){
        if(xmlReader.name() == "title"){
            if(! groupTitle.isEmpty()) groupTitleStack.append(groupTitle);
            groupTitle = xmlReader.readElementText();
        }else if(xmlReader.name() == "entry"){
            qDebug("Found entry in group.");
            parseEntry();
        }else if(xmlReader.name() == "group"){
            qDebug("Found group in group.");
            parseGroup();
        }else{
            qDebug("Skipping group child element: %s", xmlReader.name().toString().toUtf8().constData());
            xmlReader.skipCurrentElement();
        }
    }
    resetMembers();
    qDebug("Leaving parseGroup...");
}
Exemplo n.º 13
0
void SUROpener::Parser::dispatch(QString line)
{
    switch (state)
    {
    case GROUPS:
        parseGroup(line);
        break;
    case INCIDENCE:
        parseIncidence(line);
        break;
    case COORDINATES:
        parseCoordinate(line);
        break;
    case VOLUME:
        ignoreLine(line);
        break;
    default:
        ignoreLine(line);
    }
}
Exemplo n.º 14
0
bool ShapePlug::convert(QString fn)
{
    importedColors.clear();
    QList<PageItem*> gElements;
    groupStack.push(gElements);
    if(progressDialog)
    {
        progressDialog->setOverallProgress(2);
        progressDialog->setLabel("GI", tr("Generating Items"));
        qApp->processEvents();
    }
    QFile f(fn);
    if (f.open(QIODevice::ReadOnly))
    {
        QDomDocument docu("scridoc");
        docu.setContent(&f);
        QDomElement elem = docu.documentElement();
        if (elem.tagName() != "shape")
            return false;
        QDomNodeList list = elem.elementsByTagName("svg:svg");
        if (list.count() == 0)
            return false;
        QDomElement svg = list.item(0).toElement();
        QDomNode DOC = svg.firstChild();
        parseGroup(DOC);
        if (Elements.count() == 0)
        {
            if (importedColors.count() != 0)
            {
                for (int cd = 0; cd < importedColors.count(); cd++)
                {
                    m_Doc->PageColors.remove(importedColors[cd]);
                }
            }
        }
        f.close();
    }
    if (progressDialog)
        progressDialog->close();
    return true;
}
Exemplo n.º 15
0
//# if constant-expression newline group[opt]
bool Preprocessor::parseIfLikeDirective(IfLikeDirective *node)
{
    //cout << "parse if-like directive" << endl;
    Q_ASSERT(node->toItemComposite());
    TokenSection tokenSection = readLine();
    QVector<int> cleanedSection = cleanTokenRange(tokenSection);
    if(cleanedSection.count() < 3)
        return false;

    cleanedSection.erase(cleanedSection.begin(), cleanedSection.begin() + 2); //remove # and if
    cleanedSection.pop_back(); //remove endl;

    const TokenList sectionList(m_tokenContainer, cleanedSection);
    ExpressionBuilder expressionBuilder(sectionList, m_tokenTypeList, m_memoryPool);
    Expression *expr = expressionBuilder.parse();
    node->setTokenSection(tokenSection);
    node->setExpression(expr);

    parseGroup(node);
    return true;
}
Exemplo n.º 16
0
Source *Preprocessor::parse(const TokenEngine::TokenContainer &tokenContainer,
                            const QVector<Type> &tokenTypeList, TypedPool<Item> *memoryPool)
{
    m_memoryPool = memoryPool;
    Source *m_source = createNode<Source>(m_memoryPool); //node with no parent
    m_tokenContainer = tokenContainer;
    m_tokenTypeList = tokenTypeList;
    lexerTokenIndex = 0;
    numTokens = m_tokenContainer.count();

    if(m_tokenContainer.count() != tokenTypeList.count()) {
        emit error(QLatin1String("Error"), QLatin1String("Internal error in preprocessor: Number of tokens is not equal to number of types in type list"));
        return m_source;
    }

    if(tokenTypeList.isEmpty()) {
    //    emit error("Warning:", "Trying to parse empty source file");
        return m_source;
    }
    Q_ASSERT(m_source->toItemComposite());
    parseGroup(m_source);

    return m_source;
}
Exemplo n.º 17
0
int StatTool::processInputFile(const char * inputFile)
{
    try {
        crispr::xml::reader xml_parser;
        std::ifstream in_file_stream(inputFile);
        if (in_file_stream.good()) {
            in_file_stream.close();
        } else {
            throw crispr::input_exception("cannot open input file");
        }
        xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile);
        xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement();
        if (!root_elem) {
            throw crispr::xml_exception(__FILE__, 
                                        __LINE__, 
                                        __PRETTY_FUNCTION__, 
                                        "problem when parsing xml file");
        }
        int num_groups_to_process = static_cast<int>(ST_Groups.size());
        //std::cout<<num_groups_to_process<<std::endl;
        for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild();
             currentElement != NULL; 
             currentElement = currentElement->getNextElementSibling()) {

            if (ST_Subset && num_groups_to_process == 0) {
                break;
            }
            // is this a group element
            if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) {
                char * c_gid = tc(currentElement->getAttribute(xml_parser.attr_Gid()));
                std::string group_id = c_gid;
                if (ST_Subset) {
                    // we only want some of the groups look at DT_Groups
                    if (ST_Groups.find(group_id.substr(1)) != ST_Groups.end() ) {
                        parseGroup(currentElement, xml_parser);

                        // decrease the number of groups left
                        // if we are only using a subset
                        if(ST_Subset) num_groups_to_process--;
                    }
                } else {
                    parseGroup(currentElement, xml_parser);   
                }
                xr(&c_gid);
            }
        }
        AStats agregate_stats;
        agregate_stats.total_groups = 0;
        agregate_stats.total_spacers = 0;
        agregate_stats.total_dr = 0;
        agregate_stats.total_flanker = 0;
        agregate_stats.total_spacer_length = 0;
        agregate_stats.total_spacer_cov = 0;
        agregate_stats.total_dr_length = 0;
        agregate_stats.total_flanker_length = 0;
        agregate_stats.total_reads = 0;
        // go through each of the groups and print out a pretty picture
        std::vector<StatManager *>::iterator iter = this->begin();
        int longest_consensus = 0;
        int longest_gid = 0;
        if (ST_OutputStyle == veryPretty) {
            while (iter != this->end()) {
                if(static_cast<int>((*iter)->getConcensus().length()) > longest_consensus) {
                    longest_consensus = static_cast<int>((*iter)->getConcensus().length());
                }
                if (static_cast<int>((*iter)->getGid().length()) > longest_gid) {
                    longest_gid = static_cast<int>((*iter)->getGid().length());
                }
            }
            iter = this->begin();
        }
        
        while (iter != this->end()) {
            switch (ST_OutputStyle) {
                case tabular:
                    printTabular(*iter);
                    break;
                case pretty:
                    prettyPrint(*iter);
                    break;
                case veryPretty:
                    veryPrettyPrint(*iter, longest_consensus, longest_gid);
                    break;
                case coverage:
                    printCoverage(*iter);
                    break;
                default:
                    break;
            }
            iter++;
        }
        if (ST_AggregateStats) {
            calculateAgregateSTats(&agregate_stats);
            printAggregate(&agregate_stats);
        }
    } catch (xercesc::DOMException& e ) {
        char * c_msg = tc(e.getMessage());
        std::cerr<<c_msg<<std::endl;
        xr(&c_msg);
        return 1;
    }  catch (crispr::exception& e) {
        std::cerr<<e.what()<<std::endl;
        return 1;
    }
    return 0;
}
Exemplo n.º 18
0
static policyPtr parsePermission(xmlNode *node, int allow) {
    xmlNode *cur_node = node;
    int accessParsed = 0;
    ulong noOfGroups = 0;
    ulong noOfUsers = 0;
    int fileParsed = 0;
    ulong userIndex = 0;
    ulong groupIndex = 0;
    long tempaccessMode = 0;
    policyPtr newAccessNode = null;
    char *temp = null;
    if (cur_node && cur_node->type == XML_ELEMENT_NODE && (!strcmp(cur_node->name, allowTagName) || !strcmp(cur_node->name, denyTagName))) {
        fileParsed = 0;
        accessParsed = 0;
        noOfGroups = getNoOfGroups(cur_node);
        noOfUsers = getNoOfUsers(cur_node);
        newAccessNode = getNewPolicyElement();
        if (noOfGroups) {
            newAccessNode->groups = (char**) malloc(sizeof (char*) * noOfGroups);
        }
        if (noOfUsers) {
            newAccessNode->users = (char**) malloc(sizeof (char*) * noOfUsers);
        }
        newAccessNode->allow = allow;
        userIndex = 0;
        groupIndex = 0;
        tempaccessMode = -1;
        for (cur_node = node->children; cur_node; cur_node = cur_node->next) {
            if (cur_node->type == XML_ELEMENT_NODE) {
                if (!strcmp(cur_node->name, fileTagName) && !(fileParsed)) {
                    temp = parseFile(cur_node);
                    fileParsed = 1;
                    if (temp) {
                        newAccessNode->fileName = temp;
                    } else {
                        goto cleanup;
                    }
                } else if (!strcmp(cur_node->name, userTagName)) {
                    temp = parseUser(cur_node);
                    if (temp) {
                        newAccessNode->users[userIndex++] = temp;
                        newAccessNode->noOfUsers++;
                    } else {
                        goto cleanup;
                    }
                } else if (!strcmp(cur_node->name, groupTagName)) {
                    temp = parseGroup(cur_node);
                    if (temp) {
                        newAccessNode->groups[groupIndex++] = temp;
                        newAccessNode->noOfGroups++;
                    } else {
                        goto cleanup;
                    }
                } else if (!strcmp(cur_node->name, accessTagName) && !(accessParsed)) {
                    tempaccessMode = parseAccess(cur_node);
                    accessParsed = 1;
                    if (tempaccessMode < 0) {
                        goto cleanup;
                    } else {
                        newAccessNode->mode = (ulong) tempaccessMode;
                    }
                } else {
                    fprintf(stderr, "\nInvalid Element:%s\n", cur_node->name);
                    goto cleanup;
                }

            }
        }
    } else {
        fprintf(stderr, "Expected element : %s, as root node but found:%s", allowTagName, cur_node->name);
    }
ret:
    return newAccessNode;
cleanup:
    freePolicyElement(newAccessNode);
    newAccessNode = null;
    goto ret;

}
Exemplo n.º 19
0
void ShapePlug::parseGroup(QDomNode &DOC)
{
    QString tmp = "";
    QString FillCol = "White";
    QString StrokeCol = "Black";
    QString defFillCol = "White";
    QString defStrokeCol = "Black";
    QColor stroke = Qt::black;
    QColor fill = Qt::white;
//	Qt::PenStyle Dash = Qt::SolidLine;
    Qt::PenCapStyle LineEnd = Qt::FlatCap;
    Qt::PenJoinStyle LineJoin = Qt::MiterJoin;
//	int fillStyle = 1;
    double strokewidth = 0.1;
//	bool poly = false;
    while(!DOC.isNull())
    {
        double x1, y1, x2, y2;
        StrokeCol = defStrokeCol;
        FillCol = defFillCol;
        stroke = Qt::black;
        fill = Qt::white;
        //	fillStyle = 1;
        strokewidth = 1.0;
        //	Dash = Qt::SolidLine;
        LineEnd = Qt::FlatCap;
        LineJoin = Qt::MiterJoin;
        FPointArray PoLine;
        PoLine.resize(0);
        QDomElement pg = DOC.toElement();
        QString STag = pg.tagName();
        QString style = pg.attribute( "style", "" ).simplified();
        if (style.isEmpty())
            style = pg.attribute( "svg:style", "" ).simplified();
        QStringList substyles = style.split(';', QString::SkipEmptyParts);
        for( QStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it )
        {
            QStringList substyle = (*it).split(':', QString::SkipEmptyParts);
            QString command(substyle[0].trimmed());
            QString params(substyle[1].trimmed());
            if (command == "fill")
            {
                if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default") || (params == "inverse")))
                {
                    if (params == "nofill")
                        FillCol = CommonStrings::None;
                    else
                    {
                        fill.setNamedColor( params );
                        FillCol = "FromDia"+fill.name();
                        ScColor tmp;
                        tmp.fromQColor(fill);
                        tmp.setSpotColor(false);
                        tmp.setRegistrationColor(false);
                        QString fNam = m_Doc->PageColors.tryAddColor(FillCol, tmp);
                        if (fNam == FillCol)
                            importedColors.append(FillCol);
                        FillCol = fNam;
                    }
                }
            }
            else if (command == "stroke")
            {
                if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default")) || (params == "inverse"))
                {
                    stroke.setNamedColor( params );
                    StrokeCol = "FromDia"+stroke.name();
                    ScColor tmp;
                    tmp.fromQColor(stroke);
                    tmp.setSpotColor(false);
                    tmp.setRegistrationColor(false);
                    QString fNam = m_Doc->PageColors.tryAddColor(StrokeCol, tmp);
                    if (fNam == StrokeCol)
                        importedColors.append(StrokeCol);
                    StrokeCol = fNam;
                }
            }
            else if (command == "stroke-width")
                strokewidth = ScCLocale::toDoubleC(params);
            else if( command == "stroke-linejoin" )
            {
                if( params == "miter" )
                    LineJoin = Qt::MiterJoin;
                else if( params == "round" )
                    LineJoin = Qt::RoundJoin;
                else if( params == "bevel" )
                    LineJoin = Qt::BevelJoin;
            }
            else if( command == "stroke-linecap" )
            {
                if( params == "butt" )
                    LineEnd = Qt::FlatCap;
                else if( params == "round" )
                    LineEnd = Qt::RoundCap;
                else if( params == "square" )
                    LineEnd = Qt::SquareCap;
            }
        }
        if (STag == "svg:line")
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
            y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
            PoLine.addPoint(x1, y1);
            PoLine.addPoint(x1, y1);
            PoLine.addPoint(x2, y2);
            PoLine.addPoint(x2, y2);
            int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:rect")
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
            y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->setLineJoin(LineJoin);
            m_Doc->Items->at(z)->setLineEnd(LineEnd);
            finishItem(m_Doc->Items->at(z));
        }
        else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
        {
            bool bFirst = true;
            double x = 0.0;
            double y = 0.0;
            QString points = pg.attribute( "points" ).simplified().replace(',', " ");
            QStringList pointList = points.split(' ', QString::SkipEmptyParts);
            FirstM = true;
            for( QStringList::Iterator it = pointList.begin(); it != pointList.end(); it++ )
            {
                x = ScCLocale::toDoubleC(*(it++));
                y = ScCLocale::toDoubleC(*it);
                if( bFirst )
                {
                    svgMoveTo(x * Conversion, y * Conversion);
                    bFirst = false;
                    WasM = true;
                }
                else
                {
                    svgLineTo(&PoLine, x * Conversion, y * Conversion);
                }
            }
            if (STag == "svg:polygon")
                svgClosePath(&PoLine);
            if (PoLine.size() < 4)
            {
                DOC = DOC.nextSibling();
                continue;
            }
            int z;
            if (STag == "svg:polygon")
                z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol);
            else
                z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if ((STag == "svg:circle") || (STag == "svg:ellipse"))
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
            y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
            x1 *= 2.0;
            y1 *= 2.0;
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->setLineJoin(LineJoin);
            m_Doc->Items->at(z)->setLineEnd(LineEnd);
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:path")
        {
            //	poly =
            parseSVG( pg.attribute( "d" ), &PoLine );
            if (PoLine.size() < 4)
            {
                DOC = DOC.nextSibling();
                continue;
            }
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:g")
        {
            int z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseX, 1, 1, 0, CommonStrings::None, CommonStrings::None);
            PageItem *neu = m_Doc->Items->at(z);
            Elements.append(neu);
            if (groupStack.count() > 0)
                groupStack.top().append(neu);
            QList<PageItem*> gElements;
            groupStack.push(gElements);
            QDomNode child = DOC.firstChild();
            parseGroup(child);
            if (gElements.count() == 0)
            {
                groupStack.pop();
                Elements.removeAll(neu);
                groupStack.top().removeAll(neu);
                Selection tmpSelection(m_Doc, false);
                tmpSelection.addItem(neu);
                m_Doc->itemSelection_DeleteItem(&tmpSelection);
            }
            else
            {
                QList<PageItem*> gElem = groupStack.pop();
                double minx =  std::numeric_limits<double>::max();
                double miny =  std::numeric_limits<double>::max();
                double maxx = -std::numeric_limits<double>::max();
                double maxy = -std::numeric_limits<double>::max();
                for (int gr = 0; gr < gElements.count(); ++gr)
                {
                    PageItem* currItem = gElem.at(gr);
                    double x1, x2, y1, y2;
                    currItem->getVisualBoundingRect(&x1, &y1, &x2, &y2);
                    minx = qMin(minx, x1);
                    miny = qMin(miny, y1);
                    maxx = qMax(maxx, x2);
                    maxy = qMax(maxy, y2);
                }
                double gx = minx;
                double gy = miny;
                double gw = maxx - minx;
                double gh = maxy - miny;
                neu->setXYPos(gx, gy, true);
                neu->setWidthHeight(gw, gh, true);
                neu->SetRectFrame();
                neu->Clip = FlattenPath(neu->PoLine, neu->Segments);
                neu->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
                neu->AutoName = false;
                neu->gXpos = neu->xPos() - gx;
                neu->gYpos = neu->yPos() - gy;
                neu->groupWidth = gw;
                neu->groupHeight = gh;
                for (int gr = 0; gr < gElem.count(); ++gr)
                {
                    PageItem* currItem = gElem.at(gr);
                    currItem->gXpos = currItem->xPos() - gx;
                    currItem->gYpos = currItem->yPos() - gy;
                    currItem->gWidth = gw;
                    currItem->gHeight = gh;
                    currItem->Parent = neu;
                    neu->groupItemList.append(currItem);
                    m_Doc->Items->removeAll(currItem);
                    Elements.removeAll(currItem);
                }
                neu->setRedrawBounding();
                neu->setTextFlowMode(PageItem::TextFlowDisabled);
                m_Doc->GroupCounter++;
            }
        }
        DOC = DOC.nextSibling();
    }
}
Exemplo n.º 20
0
int hdfsGetConf(const char *&host, unsigned short &port, const char *&user, char *group[], int &group_size)
{
  jobject jConfiguration = NULL;
  JNIEnv *env = 0;
  jthrowable jExc = NULL;
  int ret = 0;

  env = getJNIEnv();
  if (env == NULL) {
    fprintf(stderr, "can't JNI Env\n");
    return -1;
  }

  jConfiguration =
    constructNewObjectOfClass(env, &jExc, HADOOP_CONF, "()V");
  if (jConfiguration == NULL) {
    fprintf(stderr, "Can't construct instance of class "
            "org.apache.hadoop.conf.Configuration\n");
    if (jExc != NULL) {
      env->ExceptionDescribe();
    }

    return -1;
  }

  jvalue jVal;
  jstring ugiStr = (env)->NewStringUTF(UGI_INFO);
  jstring fsStr = env->NewStringUTF(DEFAULT_FS);

  if (invokeMethod(env, &jVal, NULL, jConfiguration, HADOOP_CONF, "get", JMETHOD1(JPARAM(JAVA_STRING), JPARAM(JAVA_STRING)), ugiStr) != 0) {
    //set err return
    ret = -1;

    fprintf(stderr, "can't invoke method get ugi\n");
    if (env->ExceptionOccurred()) {
      env->ExceptionDescribe();
    }
  }

  //parse group and user info
  if (ret == 0) {
    if (jVal.l != NULL) {
      const char *ugi = (env)->GetStringUTFChars((jstring)jVal.l, NULL);

      if (ugi != NULL) {
        fprintf(stdout, "ugi string is %s\n", ugi);

        if (parseGroup(user, group, group_size, ugi)) {
          fprintf(stderr, "can't parse group info\n");
          ret = -1;
        }

        env->ReleaseStringUTFChars((jstring)jVal.l, ugi);
      }
    } else {
      fprintf(stdout, "can't find gui=%s\n", UGI_INFO);
    }
  }

  if (ret == 0) {                               /* get host and port info */
    if (invokeMethod(env, &jVal, NULL, jConfiguration, HADOOP_CONF, "get", JMETHOD1(JPARAM(JAVA_STRING), JPARAM(JAVA_STRING)), fsStr) != 0) {
      ret = -1;

      fprintf(stderr, "can't invoke method get default fs\n");
      if (env->ExceptionOccurred()) {
        env->ExceptionDescribe();
      }
    } else {
      if (jVal.l != NULL) {
        const char *str = (env)->GetStringUTFChars((jstring)jVal.l, NULL);

        if (str != NULL) {
          fprintf(stdout, "fs string is %s\n", str);
          if (parseHostAndPort(host, port, str)) {
            fprintf(stderr, "can't parse host and port info\n");
            ret = -1;
          }

          env->ReleaseStringUTFChars((jstring)jVal.l, str);
        }
      } else {
        fprintf(stdout, "can't find gui=%s\n", UGI_INFO);
      }
    }
  }

  destroyLocalReference(env, ugiStr);
  destroyLocalReference(env, jConfiguration);

  return ret;
}
Exemplo n.º 21
0
bool Parser::parseSchemaTag( ParserContext *context, const QDomElement &root )
{
  QName name(root.tagName());
  if ( name.localName() != QLatin1String("schema") ) {
    qDebug() << "ERROR localName=" << name.localName();
    return false;
  }

  // Already done by caller when coming from type.cpp, but doesn't hurt to do twice
  context->namespaceManager()->enterChild(root);

  // This method can call itself recursively, so save/restore the member attribute.
  QString oldNamespace = d->mNameSpace;
  if ( root.hasAttribute( QLatin1String("targetNamespace") ) )
    d->mNameSpace = root.attribute( QLatin1String("targetNamespace") );

  if (root.attribute( QLatin1String("elementFormDefault") ) == QLatin1String("qualified"))
      d->mDefaultQualifiedElements = true;

  if (root.attribute( QLatin1String("attributeFormDefault") ) == QLatin1String("qualified"))
      d->mDefaultQualifiedAttributes = true;

 // mTypesTable.setTargetNamespace( mNameSpace );

  QDomElement element = root.firstChildElement();
  while ( !element.isNull() ) {
    NSManager namespaceManager( context, element );
    const QName name( element.tagName() );
    if (debugParsing())
        qDebug() << "Schema: parsing" << name.localName();
    if ( name.localName() == QLatin1String("import") ) {
      parseImport( context, element );
    } else if ( name.localName() == QLatin1String("element") ) {
      addGlobalElement( parseElement( context, element, d->mNameSpace, element ) );
    } else if ( name.localName() == QLatin1String("complexType") ) {
      ComplexType ct = parseComplexType( context, element );
      d->mComplexTypes.append( ct );
    } else if ( name.localName() == QLatin1String("simpleType") ) {
      SimpleType st = parseSimpleType( context, element );
      d->mSimpleTypes.append( st );
    } else if ( name.localName() == QLatin1String("attribute") ) {
      addGlobalAttribute( parseAttribute( context, element, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("attributeGroup") ) {
      d->mAttributeGroups.append( parseAttributeGroup( context, element, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("group") ) {
      d->mGroups.append( parseGroup( context, element, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("annotation") ) {
      d->mAnnotations = parseAnnotation( context, element );
    } else if ( name.localName() == QLatin1String("include") ) {
      parseInclude( context, element );
    } else {
        qWarning() << "Unsupported schema element" << name.localName();
    }

    element = element.nextSiblingElement();
  }

  if (!resolveForwardDeclarations())
      return false;

  d->mNameSpace = oldNamespace;

  return true;
}