Ejemplo n.º 1
0
// we basically want to update the doc and start text of this method
void RubyCodeOperation::updateMethodDeclaration()
{

    CodeDocument * doc = getParentDocument();
    RubyClassifierCodeDocument * rubydoc = dynamic_cast<RubyClassifierCodeDocument*>(doc);
    UMLClassifier *c = rubydoc->getParentClassifier();
    UMLOperation * o = getParentOperation();
    bool isInterface = rubydoc->getParentClassifier()->isInterface();
    QString endLine = getNewLineEndingChars();

    // now, the starting text.
    QString strVis = rubydoc->scopeToRubyDecl(o->getVisibility());
    // no return type for constructors
    QString fixedReturn = RubyCodeGenerator::cppToRubyType(o->getTypeName());
    QString returnType = o->isConstructorOperation() ? QString("") : (fixedReturn + QString(" "));
    QString methodName = o->getName();

    QString RubyClassName = rubydoc->getRubyClassName(c->getName());

    // Skip destructors, and operator methods which
    // can't be defined in ruby
    if (    methodName.startsWith("~")
            || QRegExp("operator\\s*(=|--|\\+\\+|!=)$").exactMatch(methodName) )
    {
        getComment()->setText("");
        return;
    }

    if (RubyClassName == methodName) {
        methodName = "initialize";
    }

    methodName.replace(QRegExp("operator\\s*"), "");
    methodName = methodName.mid(0, 1).lower() + methodName.mid(1);

    QString paramStr = QString("");
    QStringList commentedParams;

    // assemble parameters
    UMLAttributeList list = getParentOperation()->getParmList();
    int nrofParam = list.count();
    int paramNum = 0;
    for(UMLAttribute* parm = list.first(); parm; parm = list.next())
    {
        QString paramName = RubyCodeGenerator::cppToRubyName(parm->getName());
        paramStr += paramName;
        if (! parm->getInitialValue().isEmpty()) {
            paramStr += QString(" = ") + RubyCodeGenerator::cppToRubyType(parm->getInitialValue());
        }
        paramNum++;

        if (paramNum != nrofParam )
            paramStr  += ", ";
    }

    QString startText;
    if (isInterface) {
        // Assume 'isInterface' means a module in Ruby, so
        // generate module methods
        startText = "def "+ RubyClassName + '.' + methodName + '(' + paramStr +')';
    } else {
        startText = "def "+ methodName + '(' + paramStr +')';
    }

    startText += "";
    setEndMethodText("end");

    setStartMethodText(startText);

    // Lastly, for text content generation, we fix the comment on the
    // operation, IF the codeop is autogenerated & currently empty
    QString comment = o->getDoc();

    if (comment.isEmpty()) {
        if (getContentType() == CodeBlock::AutoGenerated) {
            UMLAttributeList parameters = o->getParmList();
            for(UMLAttributeListIt iterator(parameters); iterator.current(); ++iterator) {
                comment += endLine + "* _" + iterator.current()->getName() + "_ ";
                comment += (' ' + iterator.current()->getDoc().replace( QRegExp("[\\n\\r]+[\\t ]*"),
                                                                        endLine + "  " ) );
            }
            // add a returns statement too
            if(!returnType.isEmpty() && !QRegExp("^void\\s*$").exactMatch(returnType))
                comment += endLine + "* _returns_ " + returnType + ' ';
            getComment()->setText(comment);
        }
    } else {
        comment.replace(QRegExp("[\\n\\r]+ *"), endLine);
        comment.replace(QRegExp("[\\n\\r]+\\t*"), endLine);

        comment.replace(" m_", " ");
        comment.replace(QRegExp("\\s[npb](?=[A-Z])"), " ");
        QRegExp re_params("@param (\\w)(\\w*)");
        int pos = re_params.search(comment);
        while (pos != -1) {
            comment.replace( re_params.cap(0),
                            QString("@param _") + re_params.cap(1).lower() + re_params.cap(2) + '_' );
            commentedParams.append(re_params.cap(1).lower() + re_params.cap(2));

            pos += re_params.matchedLength() + 3;
            pos = re_params.search(comment, pos);
        }

        UMLAttributeList parameters = o->getParmList();
        for (UMLAttributeListIt iterator(parameters); iterator.current(); ++iterator) {
            // Only write an individual @param entry if one hasn't been found already
            // in the main doc comment
            if (commentedParams.contains(RubyCodeGenerator::cppToRubyName(iterator.current()->getName())) == 0) {
                comment += (endLine + "@param _" + RubyCodeGenerator::cppToRubyName(iterator.current()->getName()) + '_');
                if (iterator.current()->getDoc().isEmpty()) {
                    comment += (' ' + RubyCodeGenerator::cppToRubyType(iterator.current()->getTypeName()));
                } else {
                    comment += (' ' + iterator.current()->getDoc().replace(QRegExp("[\\n\\r]+[\\t ]*"), endLine + "  "));
                }
            }
        }

        comment.replace("@ref ", "");
        comment.replace("@param", "*");
        comment.replace("@return", "* _returns_");

        // All lines after the first one starting with '*' in the doc comment
        // must be indented correctly. If they aren't a list
        // item starting with '*', then indent the text with
        // two spaces, '  ', to line up with the list item.
        pos = comment.find(endLine + '*');
        if (pos != -1) {
            pos += endLine.length() + 1;
            pos = comment.find(endLine, pos);
        }

        while (pos > 0) {
            pos += endLine.length();
            if (comment[pos] != '*') {
                comment.insert(pos, "  ");
                pos += 2;
            }

            pos = comment.find(endLine, pos);
        }

        QString typeStr = RubyCodeGenerator::cppToRubyType(o->getTypeName());
        if ( !typeStr.isEmpty()
                && !QRegExp("^void\\s*$").exactMatch(typeStr)
                && comment.contains("_returns_") == 0 )
        {
            comment += endLine + "* _returns_ " + typeStr;
        }

        getComment()->setText(comment);
    }

    // In Java, for interfaces..we DONT write out non-public
    // method declarations. And for Ruby modules?
    if (isInterface) {
        UMLOperation * o = getParentOperation();
        if(o->getVisibility() != Uml::Visibility::Public)
            setWriteOutText(false);
    }

}
Ejemplo n.º 2
0
int ecGetToken(EcInput *input)
{
    EcToken     *token, *tp;
    EcStream    *stream;
    int         c;

    //  TODO - functionalize this section

    token = input->token;

    if ((tp = input->putBack) != 0) {
        input->putBack = tp->next;
        input->token = tp;

        /*
         *  Move any old token to free list
         */
        if (token) {
            token->next = input->freeTokens;
            input->freeTokens = token;
        }
        return tp->tokenId;
    }

    if (token == 0) {
        //  TBD -- need an API for this
        input->token = mprAllocObjZeroed(input, EcToken);
        if (input->token == 0) {
            //  TBD -- err code
            return -1;
        }
        input->token->lineNumber = 1;
    }

    stream = input->stream;
    tp = input->token;
    mprAssert(tp);

    initializeToken(tp, stream);

    while (1) {

        c = getNextChar(stream);

        /*
         *  Overloadable operators
         *
         *  + - ~ * / % < > <= >= == << >> >>> & | === != !==
         *
         *  TODO FUTURE, we could allow also:  ".", "[", "("
         *
         *  TODO: what about unary !, ^
         */
        switch (c) {
        default:
        number:
            if (isdigit(c)) {
                return getNumberToken(input, tp, c);

            } else if (c == '\\') {
                c = getNextChar(stream);
                if (c == '\n') {
                    break;
                }
                putBackChar(stream, c);
                c = '\n';
            }
            if (isalpha(c) || c == '_' || c == '\\' || c == '$') {
                return getAlphaToken(input, tp, c);
            }
            return makeToken(tp, 0, T_ERR, 0);

        case -1:
            return makeToken(tp, 0, T_ERR, 0);

        case 0:
            if (stream->flags & EC_STREAM_EOL) {
                return makeToken(tp, 0, T_NOP, 0);
            } else {
                return makeToken(tp, 0, T_EOF, 0);
            }

        case ' ':
        case '\t':
            break;

        case '\r':
        case '\n':
            if (tp->textLen == 0 && tp->lineNumber != stream->lineNumber) {
                tp->currentLine = 0;
            }
            break;

        case '"':
        case '\'':
            return getQuotedToken(input, tp, c);

        case '#':
            return makeToken(tp, c, T_HASH, 0);

        case '[':
            //  EJS extension to consider this an operator
            return makeToken(tp, c, T_LBRACKET, G_OPERATOR);

        case ']':
            return makeToken(tp, c, T_RBRACKET, 0);

        case '(':
            //  EJS extension to consider this an operator
            return makeToken(tp, c, T_LPAREN, G_OPERATOR);

        case ')':
            return makeToken(tp, c, T_RPAREN, 0);

        case '{':
            return makeToken(tp, c, T_LBRACE, 0);

        case '}':
            return makeToken(tp, c, T_RBRACE, 0);

        case '@':
            return makeToken(tp, c, T_AT, 0);

        case ';':
            return makeToken(tp, c, T_SEMICOLON, 0);

        case ',':
            return makeToken(tp, c, T_COMMA, 0);

        case '?':
            return makeToken(tp, c, T_QUERY, 0);

        case '~':
            return makeToken(tp, c, T_TILDE, G_OPERATOR);

        case '+':
            c = getNextChar(stream);
            if (c == '+') {
                addCharToToken(tp, '+');
                return makeToken(tp, c, T_PLUS_PLUS, G_OPERATOR);
            } else if (c == '=') {
                addCharToToken(tp, '+');
                return makeSubToken(tp, c, T_ASSIGN, T_PLUS_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '+', T_PLUS, G_OPERATOR);

        case '-':
            c = getNextChar(stream);
            if (isdigit(c)) {
                putBackChar(stream, c);
                return makeToken(tp, '-', T_MINUS, G_OPERATOR);

            } else if (c == '-') {
                addCharToToken(tp, '-');
                return makeToken(tp, c, T_MINUS_MINUS, G_OPERATOR);

            } else if (c == '=') {
                addCharToToken(tp, '-');
                return makeSubToken(tp, c, T_ASSIGN, T_MINUS_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '-', T_MINUS, G_OPERATOR);

        case '*':
            c = getNextChar(stream);
            if (c == '=') {
                addCharToToken(tp, '*');
                return makeSubToken(tp, c, T_ASSIGN, T_MUL_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '*', T_MUL, G_OPERATOR);

        case '/':
            c = getNextChar(stream);
            if (c == '=') {
                addCharToToken(tp, '/');
                return makeSubToken(tp, c, T_ASSIGN, T_DIV_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);

            } else if (c == '>') {
                addCharToToken(tp, '/');
                return makeToken(tp, c, T_SLASH_GT, G_OPERATOR);

            } else if (c == '*' || c == '/') {
                /*
                 *  C and C++ comments
                 */
                if (getComment(input, tp, c) < 0) {
                    return tp->tokenId;
                }
#if BLD_FEATURE_EJS_DOC
                if (tp->text && tp->text[0] == '*') {
                    mprFree(input->doc);
                    input->doc = mprStrdup(input, (char*) tp->text);
                }
#endif
                initializeToken(tp, stream);
                break;
            }
            putBackChar(stream, c);
            return makeToken(tp, '/', T_DIV, G_OPERATOR);

        case '%':
            c = getNextChar(stream);
            if (c == '=') {
                addCharToToken(tp, '%');
                return makeSubToken(tp, c, T_ASSIGN, T_MOD_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '%', T_MOD, G_OPERATOR);

        case '.':
            c = getNextChar(stream);
            if (c == '.') {
                c = getNextChar(stream);
                if (c == '.') {
                    addStringToToken(tp, "..");
                    return makeToken(tp, c, T_ELIPSIS, 0);
                }
                putBackChar(stream, c);
                addCharToToken(tp, '.');
                return makeToken(tp, '.', T_DOT_DOT, 0);

            } else if (c == '<') {
                addCharToToken(tp, '.');
                return makeToken(tp, c, T_DOT_LESS, 0);

            } else if (isdigit(c)) {
                putBackChar(stream, c);
                goto number;
            }
            putBackChar(stream, c);
            //  EJS extension to consider this an operator
            return makeToken(tp, '.', T_DOT, G_OPERATOR);

        case ':':
            c = getNextChar(stream);
            if (c == ':') {
                addCharToToken(tp, ':');
                return makeToken(tp, c, T_COLON_COLON, 0);
            }
            putBackChar(stream, c);
            return makeToken(tp, ':', T_COLON, 0);

        case '!':
            c = getNextChar(stream);
            if (c == '=') {
                c = getNextChar(stream);
                if (c == '=') {
                    addStringToToken(tp, "!=");
                    return makeToken(tp, c, T_STRICT_NE, G_OPERATOR);
                }
                putBackChar(stream, c);
                addCharToToken(tp, '!');
                return makeToken(tp, '=', T_NE, G_OPERATOR);
            }
            putBackChar(stream, c);
            return makeToken(tp, '!', T_LOGICAL_NOT, G_OPERATOR);

#if UNUSED
        case '~':
            c = getNextChar(stream);
            if (c == '=') {
                addStringToToken(tp, "~=");
                return makeSubToken(tp, c, T_ASSIGN, T_BIT_NEG_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '~', T_BIT_NEG, G_OPERATOR);
#endif

        case '&':
            c = getNextChar(stream);
            if (c == '&') {
                addCharToToken(tp, '&');
                c = getNextChar(stream);
                if (c == '=') {
                    addCharToToken(tp, '&');
                    return makeSubToken(tp, '=', T_ASSIGN, T_LOGICAL_AND_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                }
                putBackChar(stream, c);
                return makeToken(tp, '&', T_LOGICAL_AND, G_OPERATOR);

            } else if (c == '=') {
                addCharToToken(tp, '&');
                return makeSubToken(tp, c, T_ASSIGN, T_BIT_AND_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '&', T_BIT_AND, G_OPERATOR);

        case '<':
            c = getNextChar(stream);
            if (c == '=') {
                addCharToToken(tp, '<');
                return makeToken(tp, c, T_LE, G_OPERATOR);
            } else if (c == '<') {
                c = getNextChar(stream);
                if (c == '=') {
                    addStringToToken(tp, "<<");
                    return makeSubToken(tp, c, T_ASSIGN, T_LSH_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                }
                putBackChar(stream, c);
                addCharToToken(tp, '<');
                return makeToken(tp, c, T_LSH, G_OPERATOR);

            } else if (c == '/') {
                addCharToToken(tp, '<');
                return makeToken(tp, c, T_LT_SLASH, 0);
            }
            putBackChar(stream, c);
            return makeToken(tp, '<', T_LT, G_OPERATOR);

        case '=':
            c = getNextChar(stream);
            if (c == '=') {
                c = getNextChar(stream);
                if (c == '=') {
                    addStringToToken(tp, "==");
                    return makeToken(tp, c, T_STRICT_EQ, G_OPERATOR);
                }
                putBackChar(stream, c);
                addCharToToken(tp, '=');
                return makeToken(tp, c, T_EQ, G_OPERATOR);
            }
            putBackChar(stream, c);
            return makeToken(tp, '=', T_ASSIGN, G_OPERATOR);

        case '>':
            c = getNextChar(stream);
            if (c == '=') {
                addCharToToken(tp, '<');
                return makeToken(tp, c, T_GE, G_OPERATOR);
            } else if (c == '>') {
                c = getNextChar(stream);
                if (c == '=') {
                    addStringToToken(tp, ">>");
                    return makeSubToken(tp, c, T_ASSIGN, T_RSH_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                } else if (c == '>') {
                    c = getNextChar(stream);
                    if (c == '=') {
                        addStringToToken(tp, ">>>");
                        return makeSubToken(tp, c, T_ASSIGN, T_RSH_ZERO_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                    }
                    putBackChar(stream, c);
                    addStringToToken(tp, ">>");
                    return makeToken(tp, '>', T_RSH_ZERO, G_OPERATOR);
                }
                putBackChar(stream, c);
                addCharToToken(tp, '>');
                return makeToken(tp, '>', T_RSH, G_OPERATOR);
            }
            putBackChar(stream, c);
            return makeToken(tp, '>', T_GT, G_OPERATOR);

        case '^':
            c = getNextChar(stream);
            if (c == '^') {
                addCharToToken(tp, '^');
                c = getNextChar(stream);
                if (c == '=') {
                    addCharToToken(tp, '^');
                    return makeSubToken(tp, '=', T_ASSIGN, T_LOGICAL_XOR_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                }
                putBackChar(stream, c);
                return makeToken(tp, '^', T_LOGICAL_XOR, G_OPERATOR);

            } else if (c == '=') {
                addCharToToken(tp, '^');
                return makeSubToken(tp, '=', T_ASSIGN, T_BIT_XOR_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
            }
            putBackChar(stream, c);
            return makeToken(tp, '^', T_BIT_XOR, G_OPERATOR);

        case '|':
            c = getNextChar(stream);
            if (c == '|') {
                addCharToToken(tp, '|');
                c = getNextChar(stream);
                if (c == '=') {
                    addCharToToken(tp, '|');
                    return makeSubToken(tp, '=', T_ASSIGN, T_LOGICAL_OR_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);
                }
                putBackChar(stream, c);
                return makeToken(tp, '|', T_LOGICAL_OR, G_OPERATOR);

            } else if (c == '=') {
                addCharToToken(tp, '|');
                return makeSubToken(tp, '=', T_ASSIGN, T_BIT_OR_ASSIGN, G_OPERATOR | G_COMPOUND_ASSIGN);

            }
            putBackChar(stream, c);
            return makeToken(tp, '|', T_BIT_OR, G_OPERATOR);
        }
    }
}
Ejemplo n.º 3
0
void GetFORTRANBlock( ss_block *ss_new, char *start, int text_col )
{
    int length = 0;
    if( start[0] == '\0' ) {
        if( text_col == 0 ) {
            // line is empty -
            // do not flag following line as having anything to do
            // with an unterminated string from previous line
            flags.inString = FALSE;
        }
        getBeyondText( ss_new );
        return;
    }

    if( iscomment( firstChar ) ) {
        getComment( ss_new, start );
        return;
    }

    if( text_col <= 4 ) {
        getLabelOrWS( ss_new, start, text_col );
        return;
    }

    if( text_col == 5 ) {
        getContinuationOrWS( ss_new, start );
        return;
    }

    if( flags.inString ) {
        getLiteral( ss_new, start, 0 );
        return;
    }

    if( isspace( start[0] ) ) {
        getWhiteSpace( ss_new, start );
        return;
    }

    switch( start[0] ) {

    case '!':
        getComment( ss_new, start );
        return;
    case '\'':
        getLiteral( ss_new, start, 1 );
        return;
    case '.':
        if( isdigit( start[1] ) ) {
            getFloat( ss_new, start, 1, AFTER_DOT );
            return;
        }
        length = islogical( start );
        if( length > 0 ) {
            getSymbol( ss_new, length );
            return;
        }
    }

    if( issymbol( start[0] ) ) {
        getSymbol( ss_new, 1 );
        return;
    }

    if( isdigit( *start ) ) {
        getNumber( ss_new, start );
        return;
    }

    if( isalpha( *start ) || (*start == '_') || (*start == '$') ) {
        getText( ss_new, start );
        return;
    }

    getInvalidChar( ss_new );
}
Ejemplo n.º 4
0
// -------------------------------------------------------------------
//	File parsing method.
void ObjFileParser::parseFile()
{
	if (m_DataIt == m_DataItEnd)
		return;

	while (m_DataIt != m_DataItEnd)
	{
		switch (*m_DataIt)
		{
		case 'v': // Parse a vertex texture coordinate
			{
				++m_DataIt;
				if (*m_DataIt == ' ')
				{
					// Read in vertex definition
					getVector3(m_pModel->m_Vertices);
				}
				else if (*m_DataIt == 't')
				{
					// Read in texture coordinate (2D)
					++m_DataIt;
					getVector2(m_pModel->m_TextureCoord);
				}
				else if (*m_DataIt == 'n')
				{
					// Read in normal vector definition
					++m_DataIt;
					getVector3( m_pModel->m_Normals );
				}
			}
			break;

		case 'f': // Parse a face
			{
				getFace();
			}
			break;

		case '#': // Parse a comment
			{
				getComment();
			}
			break;

		case 'u': // Parse a material desc. setter
			{
				getMaterialDesc();
			}
			break;

		case 'm': // Parse a material library
			{
				getMaterialLib();
			}
			break;

		case 'g': // Parse group name
			{
				getGroupName();
			}
			break;

		case 's': // Parse group number
			{
				getGroupNumber();
			}
			break;

		case 'o': // Parse object name
			{
				getObjectName();
			}
			break;
		
		default:
			{
				m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
			}
			break;
		}
	}
}
Ejemplo n.º 5
0
// -------------------------------------------------------------------
//  File parsing method.
void ObjFileParser::parseFile()
{
    if (m_DataIt == m_DataItEnd)
        return;

    while (m_DataIt != m_DataItEnd)
    {
        switch (*m_DataIt)
        {
        case 'v': // Parse a vertex texture coordinate
            {
                ++m_DataIt;
                if (*m_DataIt == ' ' || *m_DataIt == '\t') {
                    // read in vertex definition
                    getVector3(m_pModel->m_Vertices);
                } else if (*m_DataIt == 't') {
                    // read in texture coordinate ( 2D or 3D )
                                        ++m_DataIt;
                                        getVector( m_pModel->m_TextureCoord );
                } else if (*m_DataIt == 'n') {
                    // Read in normal vector definition
                    ++m_DataIt;
                    getVector3( m_pModel->m_Normals );
                }
            }
            break;

        case 'p': // Parse a face, line or point statement
        case 'l':
        case 'f':
            {
                getFace(*m_DataIt == 'f' ? aiPrimitiveType_POLYGON : (*m_DataIt == 'l'
                    ? aiPrimitiveType_LINE : aiPrimitiveType_POINT));
            }
            break;

        case '#': // Parse a comment
            {
                getComment();
            }
            break;

        case 'u': // Parse a material desc. setter
            {
                getMaterialDesc();
            }
            break;

        case 'm': // Parse a material library or merging group ('mg')
            {
                if (*(m_DataIt + 1) == 'g')
                    getGroupNumberAndResolution();
                else
                    getMaterialLib();
            }
            break;

        case 'g': // Parse group name
            {
                getGroupName();
            }
            break;

        case 's': // Parse group number
            {
                getGroupNumber();
            }
            break;

        case 'o': // Parse object name
            {
                getObjectName();
            }
            break;

        default:
            {
                m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
            }
            break;
        }
    }
}
Ejemplo n.º 6
0
void Post::postComment()
{
	const Record *r=(const Record *)commentS->currentData().value<quintptr>();
	QNetworkRequest request;
	QByteArray data;
	const Comment &c=getComment();
	switch(Utils::parseSite(r->source)){
	case Utils::Bilibili:
	{
		QString api("http://interface.%1/dmpost");
		api=api.arg(Utils::customUrl(Utils::Bilibili));
		request.setUrl(api);
		request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
		QUrlQuery params;
		params.addQueryItem("cid",QFileInfo(r->source).baseName());
		params.addQueryItem("date",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
		params.addQueryItem("pool","0");
		params.addQueryItem("playTime",QString::number((c.time-r->delay)/1000.0,'f',4));
		params.addQueryItem("color",QString::number(c.color));
		params.addQueryItem("fontsize",QString::number(c.font));
		params.addQueryItem("message",c.string);
		params.addQueryItem("rnd",QString::number(qrand()));
		params.addQueryItem("mode",QString::number(c.mode));
		data=QUrl::toPercentEncoding(params.query(QUrl::FullyEncoded),"%=&","-.~_");
		break;
	}
	case Utils::AcPlay:
	{
		QString api("http://api.%1/api/v1/comment/%2");
		api=api.arg(Utils::customUrl(Utils::AcPlay));
		api=api.arg(QFileInfo(r->source).baseName());
		request.setUrl(api);
		request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
		QJsonObject params;
		params["Token"]=0;
		params["Time"]=(c.time-r->delay)/1000.0;
		params["Mode"]=c.mode;
		params["Color"]=c.color;
		params["TimeStamp"]=QDateTime::currentMSecsSinceEpoch();
		params["Pool"]=0;
		params["UId"]=0;
		params["CId"]=0;
		params["Message"]=c.string;
		data=QJsonDocument(params).toJson();
		break;
	}
	default:
		break;
	}
	Danmaku::instance()->appendToPool(r->source,&c);
	QNetworkReply *reply=manager->post(request,data);
	connect(reply,&QNetworkReply::finished,[=](){
		int error=reply->error();
		if (error==QNetworkReply::NoError){
			switch(Utils::parseSite(reply->url().url()))
			{
			case Utils::Bilibili:
			{
				error=qMin<int>(QString(reply->readAll()).toInt(),QNetworkReply::NoError);
				break;
			}
			case Utils::AcPlay:
			{
				QJsonObject o=QJsonDocument::fromJson(reply->readAll()).object();
				error=o["Success"].toBool()?QNetworkReply::NoError:QNetworkReply::UnknownNetworkError;
				break;
			}
			default:
				break;
			}
		}
		if(error!=QNetworkReply::NoError){
			QString info=tr("Network error occurred, error code: %1").arg(error);
			QString sugg=Local::instance()->suggestion(error);
			QMessageBox::warning(lApp->mainWidget(),tr("Network Error"),sugg.isEmpty()?info:(info+'\n'+sugg));
		}
		else{
			emit posted(&c);
		}
		reply->deleteLater();
	});
}
Ejemplo n.º 7
0
//--------------------------------------------------------------------------
// Function:	CommonFG::getComment
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function in that it takes an
///		\c std::string for \a name.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
H5std_string CommonFG::getComment( const H5std_string& name, size_t bufsize ) const
{
   return( getComment( name.c_str(), bufsize ));
}
Ejemplo n.º 8
0
Archivo: xml.c Proyecto: BIllli/mget
static void parseXML(const char *dir, XML_CONTEXT *context)
{
	const char *tok;
	char directory[256] = "";
	size_t pos = 0;

	if (!(context->hints & XML_HINT_HTML)) {
		pos = strlcpy(directory, dir, sizeof(directory));
		if (pos >= sizeof(directory)) pos = sizeof(directory) - 1;
	}

	do {
		getContent(context, directory);
		if (context->token_len)
			debug_printf("%s=%.*s\n", directory, (int)context->token_len, context->token);

		if (!(tok = getToken(context))) return;
		// debug_printf("A Token '%.*s'\n", (int)context->token_len, context->token);

		if (context->token_len == 1 && *tok == '<') {
			// get element name and add it to directory
			int flags = XML_FLG_BEGIN;

			if (!(tok = getToken(context))) return;
			// debug_printf("A2 Token '%.*s'\n", (int)context->token_len, context->token);

			if (!(context->hints & XML_HINT_HTML)) {
				if (!pos || directory[pos - 1] != '/')
					snprintf(&directory[pos], sizeof(directory) - pos, "/%.*s", (int)context->token_len, tok);
				else
					snprintf(&directory[pos], sizeof(directory) - pos, "%.*s", (int)context->token_len, tok);
			} else {
				// snprintf(directory, sizeof(directory), "%.*s", (int)context->token_len, tok);
				if (context->token_len < sizeof(directory)) {
					strncpy(directory, tok, context->token_len);
					directory[context->token_len] = 0;
				} else {
					strncpy(directory, tok, sizeof(directory) - 1);
					directory[sizeof(directory) - 1] = 0;
				}
			}

			while ((tok = getToken(context))) {
				// debug_printf("C Token %.*s\n", (int)context->token_len, context->token);
				if (context->token_len == 2 && !strncmp(tok, "/>", 2)) {
					if (context->callback)
						context->callback(context->user_ctx, flags | XML_FLG_END, directory, NULL, NULL, 0, 0);
					break; // stay in this level
				} else if (context->token_len == 1 && *tok == '>') {
					if (context->callback)
						context->callback(context->user_ctx, flags | XML_FLG_CLOSE, directory, NULL, NULL, 0, 0);
					if (context->hints & XML_HINT_HTML) {
						if (!mget_strcasecmp_ascii(directory, "script")) {
							// special HTML <script> content parsing
							// see http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#the-script-element
							// 4.3.1.2 Restrictions for contents of script elements
							debug_printf("*** need special <script> handling\n");
							getScriptContent(context);
							if (context->token_len)
								debug_printf("%s=%.*s\n", directory, (int)context->token_len, context->token);
						}
					} else
						parseXML(directory, context); // descend one level
					break;
				} else {
//					snprintf(attribute, sizeof(attribute), "%.*s", (int)context->token_len, tok);
					char attribute[context->token_len + 1];
					strncpy(attribute, tok, context->token_len);
					attribute[context->token_len] = 0;

					if (getValue(context) == 0) return;
					if (context->token_len) {
						debug_printf("%s/@%s=%.*s\n", directory, attribute, (int)context->token_len, context->token);
						if (context->callback)
							context->callback(context->user_ctx, flags | XML_FLG_ATTRIBUTE, directory, attribute, context->token, context->token_len, context->token - context->buf);
					} else {
						debug_printf("%s/@%s\n", directory, attribute);
						if (context->callback)
							context->callback(context->user_ctx, flags | XML_FLG_ATTRIBUTE, directory, attribute, NULL, 0, 0);
					}
					flags = 0;
				}
			}
			directory[pos] = 0;
		} else if (context->token_len == 2) {
			if (!strncmp(tok, "</", 2)) {
				// ascend one level
				// cleanup - get name and '>'
				if (!(tok = getToken(context))) return;
				// debug_printf("X Token %s\n",tok);
				if (context->callback) {
					if (!(context->hints & XML_HINT_HTML))
						context->callback(context->user_ctx, XML_FLG_END, directory, NULL, NULL, 0, 0);
					else {
						char tag[context->token_len + 1]; // we need to \0 terminate tok
						memcpy(tag, tok, context->token_len);
						tag[context->token_len] = 0;
						context->callback(context->user_ctx, XML_FLG_END, tag, NULL, NULL, 0, 0);
					}
				}
				if (!(tok = getToken(context))) return;
				// debug_printf("Y Token %s\n",tok);
				if (!(context->hints & XML_HINT_HTML))
					return;
				else
					continue;
			} else if (!strncmp(tok, "<?", 2)) { // special info - ignore
				getProcessing(context);
				debug_printf("%s=<?%.*s?>\n", directory, (int)context->token_len, context->token);
				continue;
			} else if (!strncmp(tok, "<!", 2)) {
				getSpecial(context);
				debug_printf("%s=<!%.*s>\n", directory, (int)context->token_len, context->token);
			}
		} else if (context->token_len == 4 && !strncmp(tok, "<!--", 4)) { // comment - ignore
			getComment(context);
			debug_printf("%s=<!--%.*s-->\n", directory, (int)context->token_len, context->token);
			continue;
		}
	} while (tok);
}
Ejemplo n.º 9
0
char	*checkComment(char *str, t_header *header)
{
 checkInstruC(str);
 CheckQuoteC(str);
 return (getComment(str, header));
}
Ejemplo n.º 10
0
/**
 * Create the string representation of this code parameter.
 * @return      QString
 */
void CodeParameter::syncToParent( )
{
    getComment()->setText(getParentObject()->doc());

    updateContent();
}
Ejemplo n.º 11
0
//--------------------------------------------------------------------------
// Function:	H5Location::getComment
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function in that it takes an
///		\c H5std_string for \a name.
// Programmer	Binh-Minh Ribler - 2000 (moved from CommonFG, Sep 2013)
//--------------------------------------------------------------------------
H5std_string H5Location::getComment(const H5std_string& name, size_t buf_size) const
{
    return(getComment(name.c_str(), buf_size));
}
Ejemplo n.º 12
0
/**
 * Set the class attributes of this object from
 * the passed element node.
 */
void CodeParameter::setAttributesFromNode ( QDomElement & root)
{
    // set local attributes, parent object first
    QString idStr = root.attribute("parent_id","-1");
    Uml::IDType id = STR2ID(idStr);

    // always disconnect
    m_parentObject->disconnect(this);

    // now, what is the new object we want to set?
    UMLObject * obj = UMLApp::app()->document()->findObjectById(id);
    if(obj)
    {
        // FIX..one day.
        // Ugh. This is UGLY, but we have to do it this way because UMLRoles
        // don't go into the document list of UMLobjects, and have the same
        // ID as their parent UMLAssociations. So..the drill is then special
        // for Associations..in that case we need to find out which role will
        // serve as the parameter here. The REAL fix, of course, would be to
        // treat UMLRoles on a more even footing, but im not sure how that change
        // might ripple throughout the code and cause problems. Thus, since the
        // change appears to be needed for only this part, I'll do this crappy
        // change instead. -b.t.
        UMLAssociation * assoc = dynamic_cast<UMLAssociation*>(obj);
        if(assoc) {
            // In this case we init with indicated role child obj.
            UMLRole * role = 0;
            int role_id = root.attribute("role_id","-1").toInt();
            if(role_id == 1)
                role = assoc->getUMLRole(Uml::A);
            else if(role_id == 0)
                role = assoc->getUMLRole(Uml::B);
            else
                uError() << "corrupt save file? "
                << "cant get proper UMLRole for codeparameter uml id:"
                << ID2STR(id) << " w/role_id:" << role_id;

            // init using UMLRole obj
            initFields ( m_parentDocument, role);

        } else
            initFields ( m_parentDocument, obj); // just the regular approach

    } else
        uError() << "Cant load CodeParam: parentUMLObject w/id:"
        << ID2STR(id) << " not found, corrupt save file?";

    // other attribs now
    setInitialValue(root.attribute("initialValue",""));

    // load comment now
    // by looking for our particular child element
    QDomNode node = root.firstChild();
    QDomElement element = node.toElement();
    bool gotComment = false;
    while( !element.isNull() ) {
        QString tag = element.tagName();
        if( tag == "header" ) {
            QDomNode cnode = element.firstChild();
            QDomElement celem = cnode.toElement();
            getComment()->loadFromXMI(celem);
            gotComment = true;
            break;
        }
        node = element.nextSibling();
        element = node.toElement();
    }

    if(!gotComment)
        uWarning()<<" loadFromXMI : Warning: unable to initialize CodeComment in codeparam:"<<this;
}
Ejemplo n.º 13
0
QString Uic::createTableRowColumnImpl( const QDomElement &e, const QString &parent,
                                       QString *value ) {
  QString objClass = getClassName( e.parentNode().toElement() );
  QDomElement n = e.firstChild().toElement();
  QString txt;
  QString com;
  QString pix;
  QString field;
  bool isRow = e.tagName() == "row";
  while ( !n.isNull() ) {
    if ( n.tagName() == "property" ) {
      QString attrib = n.attribute( "name" );
      QVariant v = DomTool::elementToVariant( n.firstChild().toElement(), QVariant() );
      if ( attrib == "text" ) {
        txt = v.toString();
        com = getComment( n );
      } else if ( attrib == "pixmap" ) {
        pix = v.toString();
        if ( !pix.isEmpty() && !pixmapLoaderFunction.isEmpty() ) {
          pix.prepend( pixmapLoaderFunction + "( " + QString( externPixmaps ? "\"" : "" ) );
          pix.append( QString( externPixmaps ? "\"" : "" ) + " )" );
        }
      } else if ( attrib == "field" )
        field = v.toString();
    }
    n = n.nextSibling().toElement();
  }

  if ( value )
    *value = trcall( txt, com );

  // ### This generated code sucks! We have to set the number of
  // rows/cols before and then only do setLabel/()
  // ### careful, though, since QDataTable has an API which makes this code pretty good

  QString s;
  if ( isRow ) {
    s = indent + parent + "->setNumRows( " + parent + "->numRows() + 1 );\n";
    if ( pix.isEmpty() )
      s += indent + parent + "->verticalHeader()->setLabel( " + parent + "->numRows() - 1, "
           + trcall( txt, com ) + " );\n";
    else
      s += indent + parent + "->verticalHeader()->setLabel( " + parent + "->numRows() - 1, "
           + pix + ", " + trcall( txt, com ) + " );\n";
  } else {
    if ( objClass == "QTable" ) {
      s = indent + parent + "->setNumCols( " + parent + "->numCols() + 1 );\n";
      if ( pix.isEmpty() )
        s += indent + parent + "->horizontalHeader()->setLabel( " + parent + "->numCols() - 1, "
             + trcall( txt, com ) + " );\n";
      else
        s += indent + parent + "->horizontalHeader()->setLabel( " + parent + "->numCols() - 1, "
             + pix + ", " + trcall( txt, com ) + " );\n";
    } else if ( objClass == "QDataTable" ) {
      if ( !txt.isEmpty() && !field.isEmpty() ) {
        if ( pix.isEmpty() )
          out << indent << parent << "->addColumn( " << fixString( field ) << ", " << trcall( txt, com ) << " );" << endl;
        else
          out << indent << parent << "->addColumn( " << fixString( field ) << ", " << trcall( txt, com ) << ", " << pix << " );" << endl;
      }
    }
  }
  return s;
}
/**
 * This will be called by syncToParent whenever the parent object is "modified".
 */
void DCodeClassFieldDeclarationBlock::updateContent()
{
    CodeClassField * cf = getParentClassField();
    DCodeClassField * jcf = dynamic_cast<DCodeClassField*>(cf);

    if (!jcf)
    {
       uError() << "jcf: invalid dynamic cast";
       return;
    }

    CodeGenerationPolicy * commonpolicy = UMLApp::app()->commonPolicy();

    Uml::Visibility::Enum scopePolicy = commonpolicy->getAssociationFieldScope();

    // Set the comment
    QString notes = getParentObject()->doc();
    getComment()->setText(notes);

    // Set the body
    QString staticValue = getParentObject()->isStatic() ? QLatin1String("static ") : QString();
    QString scopeStr = Uml::Visibility::toString(getParentObject()->visibility());

    // IF this is from an association, then scope taken as appropriate to policy
    if (!jcf->parentIsAttribute())
    {
        switch (scopePolicy) {
        case Uml::Visibility::Public:
        case Uml::Visibility::Private:
        case Uml::Visibility::Protected:
              scopeStr = Uml::Visibility::toString(scopePolicy);
            break;
        default:
        case Uml::Visibility::FromParent:
            // do nothing here... will leave as from parent object
            break;
        }
    }

    QString typeName = jcf->getTypeName();
    QString fieldName = jcf->getFieldName();
    QString initialV = jcf->getInitialValue();

    if (!cf->parentIsAttribute() && !cf->fieldIsSingleValue())
        typeName = QLatin1String("List");

    QString body = staticValue + scopeStr + QLatin1Char(' ') + typeName + QLatin1Char(' ') + fieldName;
    if (!initialV.isEmpty())
        body.append(QLatin1String(" = ") + initialV);
    else if (!cf->parentIsAttribute())
    {
        UMLRole * role = dynamic_cast<UMLRole*>(cf->getParentObject());

        // Check for dynamic casting failure!
        if (role == NULL)
        {
            uError() << "role: invalid dynamic cast";
            return;
        }

        if (role->object()->baseType() == UMLObject::ot_Interface)
        {
            // do nothing.. can't instantiate an interface
        } else {

            // FIX?: IF a constructor method exists in the classifiercodedoc
            // of the parent Object, then we can use that instead (if its empty).
            if(cf->fieldIsSingleValue())
            {
                if(!typeName.isEmpty())
                    body.append(QLatin1String(" = new ") + typeName + QLatin1String(" ()"));
            } else
                body.append(QLatin1String(" = new Vector ()"));
        }
    }

    setText(body + QLatin1Char(';'));

}
Ejemplo n.º 15
0
void BrowseThread::populateModel() {
    m_path_mutex.lock();
    MDir thisPath = m_path;
    BrowseTableModel* thisModelObserver = m_model_observer;
    m_path_mutex.unlock();

    // Refresh the name filters in case we loaded new SoundSource plugins.
    QStringList nameFilters(SoundSourceProxy::getSupportedFileNamePatterns());

    QDirIterator fileIt(thisPath.dir().absolutePath(), nameFilters,
                        QDir::Files | QDir::NoDotAndDotDot);

    // remove all rows
    // This is a blocking operation
    // see signal/slot connection in BrowseTableModel
    emit(clearModel(thisModelObserver));

    QList< QList<QStandardItem*> > rows;

    int row = 0;
    // Iterate over the files
    while (fileIt.hasNext()) {
        // If a user quickly jumps through the folders
        // the current task becomes "dirty"
        m_path_mutex.lock();
        MDir newPath = m_path;
        m_path_mutex.unlock();

        if (thisPath.dir() != newPath.dir()) {
            qDebug() << "Abort populateModel()";
            return populateModel();
        }

        QString filepath = fileIt.next();
        auto pTrack = Track::newTemporary(filepath, thisPath.token());
        SoundSourceProxy(pTrack).updateTrackFromSource();

        QList<QStandardItem*> row_data;

        QStandardItem* item = new QStandardItem("0");
        item->setData("0", Qt::UserRole);
        row_data.insert(COLUMN_PREVIEW, item);

        item = new QStandardItem(pTrack->getFileName());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_FILENAME, item);

        item = new QStandardItem(pTrack->getArtist());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ARTIST, item);

        item = new QStandardItem(pTrack->getTitle());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_TITLE, item);

        item = new QStandardItem(pTrack->getAlbum());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ALBUM, item);

        item = new QStandardItem(pTrack->getAlbumArtist());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ALBUMARTIST, item);

        item = new QStandardItem(pTrack->getTrackNumber());
        item->setToolTip(item->text());
        item->setData(item->text().toInt(), Qt::UserRole);
        row_data.insert(COLUMN_TRACK_NUMBER, item);

        const QString year(pTrack->getYear());
        item = new YearItem(year);
        item->setToolTip(year);
        // The year column is sorted according to the numeric calendar year
        item->setData(mixxx::TrackMetadata::parseCalendarYear(year), Qt::UserRole);
        row_data.insert(COLUMN_YEAR, item);

        item = new QStandardItem(pTrack->getGenre());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_GENRE, item);

        item = new QStandardItem(pTrack->getComposer());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_COMPOSER, item);

        item = new QStandardItem(pTrack->getGrouping());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_GROUPING, item);

        item = new QStandardItem(pTrack->getComment());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_COMMENT, item);

        QString duration = pTrack->getDurationText(mixxx::Duration::Precision::SECONDS);
        item = new QStandardItem(duration);
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_DURATION, item);

        item = new QStandardItem(pTrack->getBpmText());
        item->setToolTip(item->text());
        item->setData(pTrack->getBpm(), Qt::UserRole);
        row_data.insert(COLUMN_BPM, item);

        item = new QStandardItem(pTrack->getKeyText());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_KEY, item);

        item = new QStandardItem(pTrack->getType());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_TYPE, item);

        item = new QStandardItem(pTrack->getBitrateText());
        item->setToolTip(item->text());
        item->setData(pTrack->getBitrate(), Qt::UserRole);
        row_data.insert(COLUMN_BITRATE, item);

        QString location = pTrack->getLocation();
        QString nativeLocation = QDir::toNativeSeparators(location);
        item = new QStandardItem(nativeLocation);
        item->setToolTip(nativeLocation);
        item->setData(location, Qt::UserRole);
        row_data.insert(COLUMN_NATIVELOCATION, item);

        QDateTime modifiedTime = pTrack->getFileModifiedTime().toLocalTime();
        item = new QStandardItem(modifiedTime.toString(Qt::DefaultLocaleShortDate));
        item->setToolTip(item->text());
        item->setData(modifiedTime, Qt::UserRole);
        row_data.insert(COLUMN_FILE_MODIFIED_TIME, item);

        QDateTime creationTime = pTrack->getFileCreationTime().toLocalTime();
        item = new QStandardItem(creationTime.toString(Qt::DefaultLocaleShortDate));
        item->setToolTip(item->text());
        item->setData(creationTime, Qt::UserRole);
        row_data.insert(COLUMN_FILE_CREATION_TIME, item);

        const mixxx::ReplayGain replayGain(pTrack->getReplayGain());
        item = new QStandardItem(
                mixxx::ReplayGain::ratioToString(replayGain.getRatio()));
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_REPLAYGAIN, item);

        rows.append(row_data);
        ++row;
        // If 10 tracks have been analyzed, send it to GUI
        // Will limit GUI freezing
        if (row % 10 == 0) {
            // this is a blocking operation
            emit(rowsAppended(rows, thisModelObserver));
            qDebug() << "Append " << rows.count() << " from " << filepath;
            rows.clear();
        }
        // Sleep additionally for 10ms which prevents us from GUI freezes
        msleep(20);
    }
    emit(rowsAppended(rows, thisModelObserver));
    qDebug() << "Append last " << rows.count();
}
/**
 * update the start and end text for this ownedhierarchicalcodeblock.
 */
void JavaClassDeclarationBlock::updateContent ( )
{

    JavaClassifierCodeDocument *parentDoc = dynamic_cast<JavaClassifierCodeDocument*>(getParentDocument());
    UMLClassifier *c = parentDoc->getParentClassifier();
    CodeGenerationPolicy *commonPolicy = UMLApp::app()->getCommonPolicy();
    QString endLine = commonPolicy->getNewLineEndingChars();
    bool isInterface = parentDoc->parentIsInterface(); // a little shortcut
    QString JavaClassName = parentDoc->getJavaClassName(c->getName());

    // COMMENT
    if(isInterface)
        getComment()->setText("Interface "+JavaClassName+endLine+c->getDoc());
    else
        getComment()->setText("Class "+JavaClassName+endLine+c->getDoc());

    bool forceDoc = UMLApp::app()->getCommonPolicy()->getCodeVerboseDocumentComments();
    if(forceDoc || !c->getDoc().isEmpty())
        getComment()->setWriteOutText(true);
    else
        getComment()->setWriteOutText(false);


    // Now set START/ENDING Text
    QString startText = "";
    // In Java, we need declare abstract only on classes
    if (c->getAbstract() && !isInterface)
        startText.append("abstract ");

    if (c->getVisibility() != Uml::Visibility::Public) {
        // We should probably emit a warning in here .. java doesn't like to allow
        // private/protected classes. The best we can do (I believe)
        // is to let these declarations default to "package visibility"
        // which is a level between traditional "private" and "protected"
        // scopes. To get this visibility level we just print nothing..
    } else
        startText.append("public ");

    if(parentDoc->parentIsInterface())
        startText.append("interface ");
    else
        startText.append("class ");

    startText.append(JavaClassName);

    // write inheritances out
    UMLClassifierList superclasses =
        c->findSuperClassConcepts(UMLClassifier::CLASS);
    UMLClassifierList superinterfaces =
        c->findSuperClassConcepts(UMLClassifier::INTERFACE);
    int nrof_superclasses = superclasses.count();
    int nrof_superinterfaces = superinterfaces.count();

    // write out inheritance
    int i = 0;
    if(nrof_superclasses >0)
        startText.append(" extends ");
    for (UMLClassifier * concept= superclasses.first(); concept; concept = superclasses.next())
    {
        startText.append(parentDoc->cleanName(concept->getName()));
        if(i != (nrof_superclasses-1))
            startText.append(", ");
        i++;
    }

    // write out what we 'implement'
    i = 0;
    if(nrof_superinterfaces >0)
    {
        // In Java interfaces "extend" other interfaces. Classes "implement" interfaces
        if(isInterface)
            startText.append(" extends ");
        else
            startText.append(" implements ");
    }
    for (UMLClassifier * concept= superinterfaces.first(); concept; concept = superinterfaces.next())
    {
        startText.append(parentDoc->cleanName(concept->getName()));
        if(i != (nrof_superinterfaces-1))
            startText.append(", ");
        i++;
    }

    // Set the header and end text for the hier.codeblock
    setStartText(startText+" {");

    // setEndText("}"); // not needed

}
Ejemplo n.º 17
0
// this reads the zipfile comment and parses it into a key->value map.
void zppZipArchive::parseAttrMap()
{
	int len = getCommentLength();
	int line;
	char *wstart, *bol, *p, *eol;
	std::string key, data;

	if (len == 0) return;	// no comment, we're done.

	char *cmntBuf = new char[len+1];

	// get comment into buffer (we could do this in chunks, but
	// for now we'll just snag the whole thing.)
	getComment(cmntBuf);

	cmntBuf[len] = '\0';	// nul terminate.

	if (strncmp(cmntBuf,"%ZPP%",4)!=0) {
		// printf("comment buf didn't match magic string; not parsing.\n");
		delete[] cmntBuf;
		return;
	}

	// parse the whole comment.
	// I could put this in a string and use getline(), but I'm not sure
	// that I'm guaranteed that getline() will deal with all three types
	// of likely line-ending characters (MAC: \r  UNIX: \n and PC: \r\n)
	// so I do it the old fashioned way.
	eol = cmntBuf; line = 0;
	try {
		while (1) {
			if (*eol == '\0') break; // we're done.
			// isolate a line.
			bol = eol;
			line++;
			while (*eol && *eol != '\n' && *eol != '\r') eol++;
	
			// if we get a CR, it's a DOS style file or a MAC style file
			// make sure we clobber the eol char and skip it.
			if (*eol == '\r') { *eol++ = '\0'; } // mac or first PC eol char
			if (*eol == '\n') { *eol++ = '\0'; } // unix or second DOS eol char
	
			// debug: print line.
			// printf("%d: '%s'\n", line, bol);
	
			// start at beginning of line..
			p = bol;
			while (*p && isspace(*p)) p++;
	
			// at end of line or comment character, go get next line.
			if (*p==0 || *p == '#' || *p == '%') continue;
	
			// mark start of word
			wstart = p;
	
			// skip to first space or '='
			while (*p && !isspace(*p) && *p != '=') p++;
	
			if (*p == 0)
				throw zppError("syntax error parsing zipcomment: didn't find '='");
	
			// not at the "="? clobber end-of-token and keep looking.
			if (*p != '=') {
	
				// clobber whitespace trailing token name
				*p++ = '\0';
	
				// it's gotta just be spaces til' the token.
				while (*p && isspace(*p) && *p != '=') p++;
				if (*p != '=')
					throw zppError("syntax error parsing zipcomment: expecting '='");
	
			}
			// clobber and skip "="
			*p++ = 0;
	
			// create string to store token
			key = wstart;
	
			// printf("got token '%s'\n",key.c_str());
	
			// now look for a quote (" or ') to start a string or a non-ws
			// character.
			while (*p && isspace(*p)) p++;
			if (*p == '\0') 
				throw zppError("syntax error parsing zip comment: premature end of line\n");
	
			// if we got a quote (single or double)...
			if (*p == '"' || *p == '\'') {
				// ... we're parsing a string
				char termChar = *p;
	
				p++; // skip "open quote"
				wstart = p;
				while (*p && *p != termChar) p++;
				if (!*p) 
					throw zppError("syntax error parsing zip comment: missing string terminator\n");
	
				// clobber terminator.
				*p++ = '\0';
				data = std::string(wstart);
				// printf("got data %c%s%c\n",termChar,data.c_str(),termChar);
	
			} else {
				// otherwise, we're just grabbing a "token", eat up to first ws
				wstart = p;
				while (*p && !isspace(*p)) p++;
				if (*p) *p++ = '\0'; // clobber first whitespace
				data = std::string(wstart);
				// printf("got data <%s>\n",data.c_str());
			}
			// put key in map (overwrite duplicate keys) -- maybe we should
			// make this a multimap?
			attrMap[key] = data;
		}
	} catch (zppError e) {
		// if there was a parsing error, cleanup and re-throw
		delete[] cmntBuf;
		throw e;
	}
}
Ejemplo n.º 18
0
Result ResourceFile::writeCpp (MemoryOutputStream& cpp, const File& headerFile, int& i, const int maxFileSize)
{
    const bool isFirstFile = (i == 0);

    cpp << "/* ==================================== " << resourceFileIdentifierString << " ===================================="
        << getComment()
        << "namespace " << className << newLine
        << "{" << newLine;

    bool containsAnyImages = false;

    while (i < files.size())
    {
        const File& file = files.getReference(i);
        const String variableName (variableNames[i]);

        FileInputStream fileStream (file);

        if (fileStream.openedOk())
        {
            containsAnyImages = containsAnyImages
                                 || (ImageFileFormat::findImageFormatForStream (fileStream) != nullptr);

            const String tempVariable ("temp_binary_data_" + String (i));

            cpp  << newLine << "//================== " << file.getFileName() << " ==================" << newLine
                << "static const unsigned char " << tempVariable << "[] =" << newLine;

            {
                MemoryBlock data;
                fileStream.readIntoMemoryBlock (data);
                CodeHelpers::writeDataAsCppLiteral (data, cpp, true, true);
            }

            cpp << newLine << newLine
                << "const char* " << variableName << " = (const char*) " << tempVariable << ";" << newLine;
        }

        ++i;

        if (cpp.getPosition() > maxFileSize)
            break;
    }

    if (isFirstFile)
    {
        if (i < files.size())
        {
            cpp << newLine
                << "}" << newLine
                << newLine
                << "#include \"" << headerFile.getFileName() << "\"" << newLine
                << newLine
                << "namespace " << className << newLine
                << "{";
        }

        cpp << newLine
            << newLine
            << "const char* getNamedResource (const char*, int&) throw();" << newLine
            << "const char* getNamedResource (const char* resourceNameUTF8, int& numBytes) throw()" << newLine
            << "{" << newLine;

        StringArray returnCodes;
        for (int j = 0; j < files.size(); ++j)
        {
            const File& file = files.getReference(j);
            const int64 dataSize = file.getSize();
            returnCodes.add ("numBytes = " + String (dataSize) + "; return " + variableNames[j] + ";");
        }

        CodeHelpers::createStringMatcher (cpp, "resourceNameUTF8", variableNames, returnCodes, 4);

        cpp << "    numBytes = 0;" << newLine
            << "    return 0;" << newLine
            << "}" << newLine
            << newLine
            << "const char* namedResourceList[] =" << newLine
            << "{" << newLine;

        for (int j = 0; j < files.size(); ++j)
            cpp << "    " << variableNames[j].quoted() << (j < files.size() - 1 ? "," : "") << newLine;

        cpp << "};" << newLine;
    }

    cpp << newLine
        << "}" << newLine;

    return Result::ok();
}