示例#1
0
static void startTokenizer( const char *fileName, int (*getCharFunc)() )
{
    yyInPos = 0;
    getChar = getCharFunc;

    yyFileName = fileName;
    yyCh = getChar();
    yySavedBraceDepth.clear();
    yySavedParenDepth.clear();
    yyBraceDepth = 0;
    yyParenDepth = 0;
    yyCurLineNo = 1;
    yyBraceLineNo = 1;
    yyParenLineNo = 1;
}
示例#2
0
void AntProjectPart::populateProject()
{
  QApplication::setOverrideCursor(Qt::waitCursor);

  QValueStack<QString> s;
  int prefixlen = m_projectDirectory.length()+1;
  s.push(m_projectDirectory);

  QDir dir;
  do
  {
    dir.setPath(s.pop());
    kdDebug() << "Examining: " << dir.path() << endl;
    const QFileInfoList *dirEntries = dir.entryInfoList();
    QPtrListIterator<QFileInfo> it(*dirEntries);
    for (; it.current(); ++it)
    {
      QString fileName = it.current()->fileName();
      if (fileName == "." || fileName == "..")
        continue;
      QString path = it.current()->absFilePath();
      if (it.current()->isDir())
      {
        kdDebug() << "Pushing: " << path << endl;
        s.push(path);
      }
      else
      {
        kdDebug() << "Adding: " << path << endl;
        m_sourceFiles.append(path.mid(prefixlen));
      }
    }
  }
  while (!s.isEmpty());

  QApplication::restoreOverrideCursor();
}
示例#3
0
bool QExp::isLast(QValueStack<char> opr){
	int ins=0;
	bool b=true;
	while(b && !opr.empty()){
		if(opr.top()==tLpr){
			if(ins == 0)
				b= true;
			else
				ins--;
		} else if(opr.top()==tLpr)
			ins++;
		else if(opr.top()==tComa)
			b= false;
		else if(opr.top()==tEof)
			b= false;
		opr.pop();
	}
	return b;
}
示例#4
0
/**
   \internal
*/
bool GetOpt::parse( bool untilFirstSwitchOnly )
{
    //    qDebug( "parse(%s)", args.join( QString( "," ) ).ascii() );
    // push all arguments as we got them on a stack
    // more pushes might following when parsing condensed arguments
    // like --key=value.
    QValueStack<QString> stack;
    {
	QStringList::const_iterator it = args.fromLast();
	const QStringList::const_iterator end = args.end();
	while ( it != end ) {
	    stack.push( *it );
	    --it;
	}
    }

    const OptionConstIterator obegin = options.begin();
    const OptionConstIterator oend = options.end();
    enum { StartState, ExpectingState, OptionalState } state = StartState;
    Option currOpt;
    enum TokenType { LongOpt, ShortOpt, Arg, End } t, currType = End;
    bool extraLoop = true; // we'll do an extra round. fake an End argument
    while ( !stack.isEmpty() || extraLoop ) {
	QString a;
	QString origA;
	// identify argument type
	if ( !stack.isEmpty() ) {
	    a = stack.pop();
	    currArg++;
	    origA = a;
	    //	    qDebug( "popped %s", a.ascii() );
	    if ( a.startsWith( QString::fromLatin1( "--" ) ) ) {
		// recognized long option
		a = a.mid( 2 );
		if ( a.isEmpty() ) {
		    qWarning( "'--' feature not supported, yet" );
		    exit( 2 );
		}
		t = LongOpt;
		// split key=value style arguments
		int equal = a.find( '=' );
		if ( equal >= 0 ) {
		    stack.push( a.mid( equal + 1 ) );
		    currArg--;
		    a = a.left( equal );
		}
	    } else if ( a.length() == 1 ) {
		t = Arg;
	    } else if ( a[0] == '-' ) {
#if 0 // compat mode for -long style options
		if ( a.length() == 2 ) {
		    t = ShortOpt;
		    a = a[1];
		} else {
		    a = a.mid( 1 );
		    t = LongOpt;
		    // split key=value style arguments
		    int equal = a.find( '=' );
		    if ( equal >= 0 ) {
			stack.push( a.mid( equal + 1 ) );
			currArg--;
			a = a.left( equal );
		    }
		}
#else
		// short option
		t = ShortOpt;
		// followed by an argument ? push it for later processing.
		if ( a.length() > 2 ) {
		    stack.push( a.mid( 2 ) );
		    currArg--;
		}
		a = a[1];
#endif
	    } else {
		t = Arg;
	    }
	} else {
	    // faked closing argument
	    t = End;
	}
	// look up among known list of options
	Option opt;
	if ( t != End ) {
	    OptionConstIterator oit = obegin;
	    while ( oit != oend ) {
		const Option &o = *oit;
		if ( ( t == LongOpt && a == o.lname ) || // ### check state
		     ( t == ShortOpt && a[0].unicode() == o.sname ) ) {
		    opt = o;
		    break;
		}
		++oit;
	    }
	    if ( t == LongOpt && opt.type == OUnknown ) {
		if ( currOpt.type != OVarLen ) {
		    qWarning( "Unknown option --%s", a.ascii() );
		    return false;
		} else {
		    // VarLength options support arguments starting with '-'
		    t = Arg;
		}
	    } else if ( t == ShortOpt && opt.type == OUnknown ) {
		if ( currOpt.type != OVarLen ) {
		    qWarning( "Unknown option -%c", a[0].unicode() );
		    return false;
		} else {
		    // VarLength options support arguments starting with '-'
		    t = Arg;
		}
	    }

	} else {
	    opt = Option( OEnd );
	}

	// interpret result
	switch ( state ) {
	case StartState:
	    if ( opt.type == OSwitch ) {
		setSwitch( opt );
		setOptions.insert( opt.lname, 1 );
		setOptions.insert( QString( QChar( opt.sname ) ), 1 );
	    } else if ( opt.type == OArg1 || opt.type == ORepeat ) {
		state = ExpectingState;
		currOpt = opt;
		currType = t;
		setOptions.insert( opt.lname, 1 );
		setOptions.insert( QString( QChar( opt.sname ) ), 1 );
	    } else if ( opt.type == OOpt || opt.type == OVarLen ) {
		state = OptionalState;
		currOpt = opt;
		currType = t;
		setOptions.insert( opt.lname, 1 );
		setOptions.insert( QString( QChar( opt.sname ) ), 1 );
	    } else if ( opt.type == OEnd ) {
		// we're done
	    } else if ( opt.type == OUnknown && t == Arg ) {
		if ( numReqArgs > 0 ) {
		    if ( reqArg.stringValue->isNull() ) { // ###
			*reqArg.stringValue = a;
		    } else {
			qWarning( "Too many arguments" );
			return false;
		    }
		} else if ( numOptArgs > 0 ) {
		    if ( optArg.stringValue->isNull() ) { // ###
			*optArg.stringValue = a;
		    } else {
			qWarning( "Too many arguments" );
			return false;
		    }
		}
	    } else {
		qFatal( "unhandled StartState case %d",  opt.type );
	    }
	    break;
	case ExpectingState:
	    if ( t == Arg ) {
		if ( currOpt.type == OArg1 ) {
		    *currOpt.stringValue = a;
		    state = StartState;
		} else if ( currOpt.type == ORepeat ) {
		    currOpt.listValue->append( a );
		    state = StartState;
		} else {
		    abort();
		}
	    } else {
		QString n = currType == LongOpt ?
			    currOpt.lname : QString( QChar( currOpt.sname ) );
		qWarning( "Expected an argument after '%s' option", n.ascii() );
		return false;
	    }
	    break;
	case OptionalState:
	    if ( t == Arg ) {
		if ( currOpt.type == OOpt ) {
		    *currOpt.stringValue = a;
		    state = StartState;
		} else if ( currOpt.type == OVarLen ) {
		    currOpt.listValue->append( origA );
		    // remain in this state
		} else {
		    abort();
		}
	    } else {
		// optional argument not specified
		if ( currOpt.type == OOpt )
		    *currOpt.stringValue = currOpt.def;
		if ( t != End ) {
		    // re-evaluate current argument
		    stack.push( origA );
		    currArg--;
		}
		state = StartState;
	    }
	    break;
	}

	if ( untilFirstSwitchOnly && opt.type == OSwitch )
	    return true;

	// are we in the extra loop ? if so, flag the final end
	if ( t == End )
	    extraLoop = false;
    }

    if ( numReqArgs > 0 && reqArg.stringValue->isNull() ) {
	qWarning( "Lacking required argument" );
	return false;
    }

    return true;
}
示例#5
0
DrMain* LprHandler::loadToolDriver(const QString& filename)
{
	QFile	f(filename);
	if (f.open(IO_ReadOnly))
	{
		DrMain	*driver = new DrMain;
		QValueStack<DrGroup*>	groups;
		QTextStream	t(&f);
		QStringList	l;
		DrListOption	*lopt(0);
		DrBase	*opt(0);

		groups.push(driver);
		driver->set("text", "Tool Driver");
		while (!t.atEnd())
		{
			l = QStringList::split('|', t.readLine().stripWhiteSpace(), false);
			if (l.count() == 0)
				continue;
			if (l[0] == "GROUP")
			{
				DrGroup	*grp = new DrGroup;
				grp->setName(l[1]);
				grp->set("text", l[2]);
				groups.top()->addGroup(grp);
				groups.push(grp);
			}
			else if (l[0] == "ENDGROUP")
			{
				groups.pop();
			}
			else if (l[0] == "OPTION")
			{
				opt = 0;
				lopt = 0;
				if (l.count() > 3)
				{
					if (l[3] == "STRING")
						opt = new DrStringOption;
					else if (l[3] == "BOOLEAN")
					{
						lopt = new DrBooleanOption;
						opt = lopt;
					}
				}
				else
				{
					lopt = new DrListOption;
					opt = lopt;
				}
				if (opt)
				{
					opt->setName(l[1]);
					opt->set("text", l[2]);
					groups.top()->addOption(opt);
				}
			}
			else if (l[0] == "CHOICE" && lopt)
			{
				DrBase	*ch = new DrBase;
				ch->setName(l[1]);
				ch->set("text", l[2]);
				lopt->addChoice(ch);
			}
			else if (l[0] == "DEFAULT" && opt)
			{
				opt->setValueText(l[1]);
				opt->set("default", l[1]);
			}
		}
		return driver;
	}
	return NULL;
}
示例#6
0
// Print a range of lines to a printer.
int QsciPrinter::printRange(QsciScintillaBase *qsb, int from, int to)
{
    // Sanity check.
    if (!qsb)
        return false;

    // Setup the printing area.
    QRect def_area;

    def_area.setX(0);
    def_area.setY(0);

    QPaintDeviceMetrics metrics(this);
    def_area.setWidth(metrics.width());
    def_area.setHeight(metrics.height());

    // Get the page range.
    int pgFrom, pgTo;

    pgFrom = fromPage();
    pgTo = toPage();

    // Find the position range.
    long startPos, endPos;

    endPos = qsb->SendScintilla(QsciScintillaBase::SCI_GETLENGTH);

    startPos = (from > 0 ? qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,from) : 0);

    if (to >= 0)
    {
        long toPos = qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,to + 1);

        if (endPos > toPos)
            endPos = toPos;
    }

    if (startPos >= endPos)
        return false;

    QPainter painter(this);
    bool reverse = (pageOrder() == LastPageFirst);
    bool needNewPage = false;

    qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTMAGNIFICATION,mag);
    qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTWRAPMODE,wrap);

    for (int i = 1; i <= numCopies(); ++i)
    {
        // If we are printing in reverse page order then remember the start
        // position of each page.
        QValueStack<long> pageStarts;

        int currPage = 1;
        long pos = startPos;

        while (pos < endPos)
        {
            // See if we have finished the requested page range.
            if (pgTo > 0 && pgTo < currPage)
                break;

            // See if we are going to render this page, or just see how much
            // would fit onto it.
            bool render = false;

            if (pgFrom == 0 || pgFrom <= currPage)
            {
                if (reverse)
                    pageStarts.push(pos);
                else
                {
                    render = true;

                    if (needNewPage)
                    {
                        if (!newPage())
                            return false;
                    }
                    else
                        needNewPage = true;
                }
            }

            QRect area = def_area;

            formatPage(painter,render,area,currPage);
            pos = qsb -> SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,render,&painter,area,pos,endPos);

            ++currPage;
        }

        // All done if we are printing in normal page order.
        if (!reverse)
            continue;

        // Now go through each page on the stack and really print it.
        while (!pageStarts.isEmpty())
        {
            --currPage;

            long ePos = pos;
            pos = pageStarts.pop();

            if (needNewPage)
            {
                if (!newPage())
                    return false;
            }
            else
                needNewPage = true;

            QRect area = def_area;

            formatPage(painter,true,area,currPage);
            qsb->SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,true,&painter,area,pos,ePos);
        }
    }

    return true;
}
示例#7
0
static int getToken()
{
    const char tab[] = "abfnrtv";
    const char backTab[] = "\a\b\f\n\r\t\v";
    uint n;

    yyIdentLen = 0;
    yyCommentLen = 0;
    yyStringLen = 0;

    while ( yyCh != EOF ) {
	yyLineNo = yyCurLineNo;

	if ( isalpha(yyCh) || yyCh == '_' ) {
	    do {
		if ( yyIdentLen < sizeof(yyIdent) - 1 )
		    yyIdent[yyIdentLen++] = (char) yyCh;
		yyCh = getChar();
	    } while ( isalnum(yyCh) || yyCh == '_' );
	    yyIdent[yyIdentLen] = '\0';

	    switch ( yyIdent[0] ) {
	    case 'Q':
		if ( strcmp(yyIdent + 1, "_OBJECT") == 0 ) {
		    return Tok_Q_OBJECT;
		} else if ( strcmp(yyIdent + 1, "T_TR_NOOP") == 0 ) {
		    return Tok_tr;
		} else if ( strcmp(yyIdent + 1, "T_TRANSLATE_NOOP") == 0 ) {
		    return Tok_translate;
		}
		break;
	    case 'T':
		// TR() for when all else fails
		if ( qstricmp(yyIdent + 1, "R") == 0 )
		    return Tok_tr;
		break;
	    case 'c':
		if ( strcmp(yyIdent + 1, "lass") == 0 )
		    return Tok_class;
		break;
	    case 'f':
		/*
		  QTranslator::findMessage() has the same parameters as
		  QApplication::translate().
		*/
		if ( strcmp(yyIdent + 1, "indMessage") == 0 )
		    return Tok_translate;
		break;
            case 'i':
                /* FOR KDE APPS */
                if ( strcmp( yyIdent + 1,  "8n") == 0 )
                    return Tok_translate;
                break;
	    case 'n':
		if ( strcmp(yyIdent + 1, "amespace") == 0 )
		    return Tok_namespace;
		break;
	    case 'r':
		if ( strcmp(yyIdent + 1, "eturn") == 0 )
		    return Tok_return;
		break;
	    case 's':
		if ( strcmp(yyIdent + 1, "truct") == 0 )
		    return Tok_class;
		break;
	    case 't':
		if ( strcmp(yyIdent + 1, "r") == 0 ) {
		    return Tok_tr;
		} else if ( qstrcmp(yyIdent + 1, "rUtf8") == 0 ) {
		    return Tok_trUtf8;
		} else if ( qstrcmp(yyIdent + 1, "ranslate") == 0 ) {
		    return Tok_translate;
		}
	    }
	    return Tok_Ident;
	} else {
	    switch ( yyCh ) {
	    case '#':
		/*
		  Early versions of lupdate complained about
		  unbalanced braces in the following code:

		      #ifdef ALPHA
			  while ( beta ) {
		      #else
			  while ( gamma ) {
		      #endif
			      delta;
			  }

		  The code contains, indeed, two opening braces for
		  one closing brace; yet there's no reason to panic.

		  The solution is to remember yyBraceDepth as it was
		  when #if, #ifdef or #ifndef was met, and to set
		  yyBraceDepth to that value when meeting #elif or
		  #else.
		*/
		do {
		    yyCh = getChar();
		} while ( isspace(yyCh) && yyCh != '\n' );

		switch ( yyCh ) {
		case 'i':
		    yyCh = getChar();
		    if ( yyCh == 'f' ) {
			// if, ifdef, ifndef
			yySavedBraceDepth.push( yyBraceDepth );
                        yySavedParenDepth.push( yyParenDepth );
		    }
		    break;
		case 'e':
		    yyCh = getChar();
		    if ( yyCh == 'l' ) {
			// elif, else
			if ( !yySavedBraceDepth.isEmpty() ) {
			    yyBraceDepth = yySavedBraceDepth.top();
                            yyParenDepth = yySavedParenDepth.top();
			}
		    } else if ( yyCh == 'n' ) {
			// endif
			if ( !yySavedBraceDepth.isEmpty() ) {
			    yySavedBraceDepth.pop();
                            yySavedParenDepth.pop();
			}
		    }
		}
		while ( isalnum(yyCh) || yyCh == '_' )
		    yyCh = getChar();
		break;
	    case '/':
		yyCh = getChar();
		if ( yyCh == '/' ) {
		    do {
			yyCh = getChar();
		    } while ( yyCh != EOF && yyCh != '\n' );
		} else if ( yyCh == '*' ) {
		    bool metAster = FALSE;
		    bool metAsterSlash = FALSE;

		    while ( !metAsterSlash ) {
			yyCh = getChar();
			if ( yyCh == EOF ) {
			    fprintf( stderr,
				     "%s: Unterminated C++ comment starting at"
				     " line %d\n",
				     (const char *) yyFileName, yyLineNo );
			    yyComment[yyCommentLen] = '\0';
			    return Tok_Comment;
			}
			if ( yyCommentLen < sizeof(yyComment) - 1 )
			    yyComment[yyCommentLen++] = (char) yyCh;

			if ( yyCh == '*' )
			    metAster = TRUE;
			else if ( metAster && yyCh == '/' )
			    metAsterSlash = TRUE;
			else
			    metAster = FALSE;
		    }
		    yyCh = getChar();
		    yyCommentLen -= 2;
		    yyComment[yyCommentLen] = '\0';
		    return Tok_Comment;
		}
		break;
	    case '"':
		yyCh = getChar();

		while ( yyCh != EOF && yyCh != '\n' && yyCh != '"' ) {
		    if ( yyCh == '\\' ) {
			yyCh = getChar();

			if ( yyCh == '\n' ) {
			    yyCh = getChar();
			} else if ( yyCh == 'x' ) {
			    QCString hex = "0";

			    yyCh = getChar();
			    while ( isxdigit(yyCh) ) {
				hex += (char) yyCh;
				yyCh = getChar();
			    }
			    sscanf( hex, "%x", &n );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = (char) n;
			} else if ( yyCh >= '0' && yyCh < '8' ) {
			    QCString oct = "";

			    do {
				oct += (char) yyCh;
				yyCh = getChar();
			    } while ( yyCh >= '0' && yyCh < '8' );
			    sscanf( oct, "%o", &n );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = (char) n;
			} else {
			    const char *p = strchr( tab, yyCh );
			    if ( yyStringLen < sizeof(yyString) - 1 )
				yyString[yyStringLen++] = ( p == 0 ) ?
					(char) yyCh : backTab[p - tab];
			    yyCh = getChar();
			}
		    } else {
			if ( yyStringLen < sizeof(yyString) - 1 )
			    yyString[yyStringLen++] = (char) yyCh;
			yyCh = getChar();
		    }
		}
		yyString[yyStringLen] = '\0';

		if ( yyCh != '"' )
		    qWarning( "%s:%d: Unterminated C++ string",
			      (const char *) yyFileName, yyLineNo );

		if ( yyCh == EOF ) {
		    return Tok_Eof;
		} else {
		    yyCh = getChar();
		    return Tok_String;
		}
		break;
	    case '-':
		yyCh = getChar();
		if ( yyCh == '>' ) {
		    yyCh = getChar();
		    return Tok_Arrow;
		}
		break;
	    case ':':
		yyCh = getChar();
		if ( yyCh == ':' ) {
		    yyCh = getChar();
		    return Tok_Gulbrandsen;
		}
		return Tok_Colon;
	    case '\'':
		yyCh = getChar();
		if ( yyCh == '\\' )
		    yyCh = getChar();

		do {
		    yyCh = getChar();
		} while ( yyCh != EOF && yyCh != '\'' );
		yyCh = getChar();
		break;
	    case '{':
                if (yyBraceDepth == 0)
		    yyBraceLineNo = yyCurLineNo;
		yyBraceDepth++;
		yyCh = getChar();
		return Tok_LeftBrace;
	    case '}':
                if (yyBraceDepth == 0)
		    yyBraceLineNo = yyCurLineNo;
		yyBraceDepth--;
		yyCh = getChar();
		return Tok_RightBrace;
	    case '(':
                if (yyParenDepth == 0)
		    yyParenLineNo = yyCurLineNo;
		yyParenDepth++;
		yyCh = getChar();
		return Tok_LeftParen;
	    case ')':
		if (yyParenDepth == 0)
		    yyParenLineNo = yyCurLineNo;
		yyParenDepth--;
		yyCh = getChar();
		return Tok_RightParen;
	    case ',':
		yyCh = getChar();
		return Tok_Comma;
	    case ';':
		yyCh = getChar();
		return Tok_Semicolon;
	    default:
		yyCh = getChar();
	    }
	}
    }
    return Tok_Eof;
}
示例#8
0
void KArchiveDirectory::copyTo(const QString &dest, bool recursiveCopy) const
{
    QDir root;

    PosSortedPtrList fileList;
    QMap< int, QString > fileToDir;

    QStringList::Iterator it;

    // placeholders for iterated items
    KArchiveDirectory *curDir;
    QString curDirName;

    QStringList dirEntries;
    KArchiveEntry *curEntry;
    KArchiveFile *curFile;


    QPtrStack< KArchiveDirectory > dirStack;
    QValueStack< QString > dirNameStack;

    dirStack.push(this);     // init stack at current directory
    dirNameStack.push(dest); // ... with given path
    do
    {
        curDir = dirStack.pop();
        curDirName = dirNameStack.pop();
        root.mkdir(curDirName);

        dirEntries = curDir->entries();
        for(it = dirEntries.begin(); it != dirEntries.end(); ++it)
        {
            curEntry = curDir->entry(*it);
            if(!curEntry->symlink().isEmpty())
            {
                const QString linkName = curDirName + '/' + curEntry->name();
                kdDebug() << "symlink(" << curEntry->symlink() << ',' << linkName << ')';

                if(!::symlink(curEntry->symlink().local8Bit(), linkName.local8Bit()))
                {
                    kdDebug() << "symlink(" << curEntry->symlink() << ',' << linkName << ") failed:" << strerror(errno);
                }
            }
            else
            {
                if(curEntry->isFile())
                {
                    curFile = dynamic_cast< KArchiveFile * >(curEntry);
                    if(curFile)
                    {
                        fileList.append(curFile);
                        fileToDir.insert(curFile->position(), curDirName);
                    }
                }

                if(curEntry->isDirectory())
                    if(recursiveCopy)
                    {
                        KArchiveDirectory *ad = dynamic_cast< KArchiveDirectory * >(curEntry);
                        if(ad)
                        {
                            dirStack.push(ad);
                            dirNameStack.push(curDirName + "/" + curEntry->name());
                        }
                    }
            }
        }
    } while(!dirStack.isEmpty());

    fileList.sort(); // sort on m_pos, so we have a linear access

    KArchiveFile *f;
    for(f = fileList.first(); f; f = fileList.next())
    {
        int pos = f->position();
        f->copyTo(fileToDir[pos]);
    }
}
示例#9
0
/**
* Say or Synthesize text.
* @param inputText               The text that shall be spoken
* @param suggestedFilename       If not Null, synthesize only to this filename, otherwise
*                                synthesize and audibilize the text.
* @param userCmd                 The program that shall be executed for speaking
* @param stdIn                   True if the program shall recieve its data via standard input
* @param codec                   The QTextCodec if encoding==UseCodec
* @param language                The language code (used for the %l macro)
*/
void CommandProc::synth(const QString& inputText, const QString& suggestedFilename,
    const QString& userCmd, bool stdIn, QTextCodec *codec, QString& language)
{
    if (m_commandProc)
    {
        if (m_commandProc->isRunning()) m_commandProc->kill();
        delete m_commandProc;
        m_commandProc = 0;
        m_synthFilename = QString::null;
        if (!m_textFilename.isNull()) QFile::remove(m_textFilename);
        m_textFilename = QString::null;
    }
    QString command = userCmd;
    QString text = inputText.stripWhiteSpace();
    if (text.isEmpty()) return;
     // 1. prepare the text:
     // 1.a) encode the text
    text += "\n";
    QCString encodedText;
    if (codec)
        encodedText = codec->fromUnicode(text);
    else
        encodedText = text.latin1();  // Should not happen, but just in case.

    // 1.b) quote the text as one parameter
    QString escText = KShellProcess::quote(text);

    // 1.c) create a temporary file for the text, if %f macro is used.
    if (command.contains("%f"))
    {
        KTempFile tempFile(locateLocal("tmp", "commandplugin-"), ".txt");
        QTextStream* fs = tempFile.textStream();
        fs->setCodec(codec);
        *fs << text;
        *fs << endl;
        m_textFilename = tempFile.file()->name();
        tempFile.close();
    } else m_textFilename = QString::null;

    // 2. replace variables with values
    QValueStack<bool> stack;
    bool issinglequote=false;
    bool isdoublequote=false;
    int noreplace=0;
    QRegExp re_noquote("(\"|'|\\\\|`|\\$\\(|\\$\\{|\\(|\\{|\\)|\\}|%%|%t|%f|%l|%w)");
    QRegExp re_singlequote("('|%%|%t|%f|%l|%w)");
    QRegExp re_doublequote("(\"|\\\\|`|\\$\\(|\\$\\{|%%|%t|%f|%l|%w)");

    for	( int i = re_noquote.search(command);
        i != -1;
        i = (issinglequote?re_singlequote.search(command,i)
            :isdoublequote?re_doublequote.search(command,i)
            :re_noquote.search(command,i))
    )
    {
        if ((command[i]=='(') || (command[i]=='{')) // (...) or {...}
        {
            // assert(isdoublequote == false)
            stack.push(isdoublequote);
            if (noreplace > 0)
                // count nested braces when within ${...}
                noreplace++;
            i++;
        }
        else if (command[i]=='$')
        {
            stack.push(isdoublequote);
            isdoublequote = false;
            if ((noreplace > 0) || (command[i+1]=='{'))
                // count nested braces when within ${...}
                noreplace++;
            i+=2;
        }
        else if ((command[i]==')') || (command[i]=='}'))
            // $(...) or (...) or ${...} or {...}
        {
            if (!stack.isEmpty())
                isdoublequote = stack.pop();
            else
                qWarning("Parse error.");
            if (noreplace > 0)
                // count nested braces when within ${...}
                noreplace--;
            i++;
        }
        else if (command[i]=='\'')
        {
            issinglequote=!issinglequote;
            i++;
        }
        else if (command[i]=='"')
        {
            isdoublequote=!isdoublequote;
            i++;
        }
        else if (command[i]=='\\')
            i+=2;
        else if (command[i]=='`')
        {
            // Replace all `...` with safer $(...)
            command.replace (i, 1, "$(");
            QRegExp re_backticks("(`|\\\\`|\\\\\\\\|\\\\\\$)");
            for (	int i2=re_backticks.search(command,i+2);
                i2!=-1;
                i2=re_backticks.search(command,i2)
            )
            {
                if (command[i2] == '`')
                {
                    command.replace (i2, 1, ")");
                    i2=command.length(); // leave loop
                }
                else
                {   // remove backslash and ignore following character
                    command.remove (i2, 1);
                    i2++;
                }
            }
            // Leave i unchanged! We need to process "$("
        }
        else if (noreplace == 0) // do not replace macros within ${...}
        {
            QString match, v;

            // get match
            if (issinglequote)
                match=re_singlequote.cap();
            else if (isdoublequote)
                match=re_doublequote.cap();
            else
                match=re_noquote.cap();

            // substitue %variables
            if (match=="%%")
                v="%";
            else if (match=="%t")
                v=escText;
            else if (match=="%f")
                v=m_textFilename;
            else if (match=="%l")
                v=language;
            else if (match=="%w")
                v = suggestedFilename;

            // %variable inside of a quote?
            if (isdoublequote)
                v='"'+v+'"';
            else if (issinglequote)
                v="'"+v+"'";

            command.replace (i, match.length(), v);
            i+=v.length();
        }
        else
        {
            if (issinglequote)
                i+=re_singlequote.matchedLength();
            else if (isdoublequote)
                i+=re_doublequote.matchedLength();
            else
                i+=re_noquote.matchedLength();
        }
    }

    // 3. create a new process
    kdDebug() << "CommandProc::synth: running command: " << command << endl;
    m_commandProc = new KProcess;
    m_commandProc->setUseShell(true);
    m_commandProc->setEnvironment("LANG", language + "." + codec->mimeName());
    m_commandProc->setEnvironment("LC_CTYPE", language + "." + codec->mimeName());
    *m_commandProc << command;
    connect(m_commandProc, SIGNAL(processExited(KProcess*)),
        this, SLOT(slotProcessExited(KProcess*)));
    connect(m_commandProc, SIGNAL(receivedStdout(KProcess*, char*, int)),
        this, SLOT(slotReceivedStdout(KProcess*, char*, int)));
    connect(m_commandProc, SIGNAL(receivedStderr(KProcess*, char*, int)),
        this, SLOT(slotReceivedStderr(KProcess*, char*, int)));
    connect(m_commandProc, SIGNAL(wroteStdin(KProcess*)),
        this, SLOT(slotWroteStdin(KProcess* )));

    // 4. start the process

    if (suggestedFilename.isNull())
        m_state = psSaying;
    else
    {
        m_synthFilename = suggestedFilename;
        m_state = psSynthing;
    }
    if (stdIn) {
        m_commandProc->start(KProcess::NotifyOnExit, KProcess::All);
        if (encodedText.length() > 0)
            m_commandProc->writeStdin(encodedText, encodedText.length());
        else
            m_commandProc->closeStdin();
    }
    else
        m_commandProc->start(KProcess::NotifyOnExit, KProcess::AllOutput);
}
示例#10
0
/**
  Paints the actual data area.

  \param painter the QPainter onto which the chart should be painted
  \param data the data that will be displayed as a chart
  \param paint2nd specifies whether the main chart or the additional chart is to be drawn now
  \param regions a pointer to a list of regions that will be filled
  with regions representing the data segments, if not null
  */
void KDChartPiePainter::paintData( QPainter* painter,
        KDChartTableDataBase* data,
        bool paint2nd,
        KDChartDataRegionList* regions )
{
//bHelp=true;
    uint chart = paint2nd ? 1 : 0;

    QRect ourClipRect( _dataRect );
    ourClipRect.addCoords( -1,-1,1,1 );

    const QWMatrix & world = painter->worldMatrix();
    ourClipRect =
#if COMPAT_QT_VERSION >= 0x030000
        world.mapRect( ourClipRect );
#else
    world.map( ourClipRect );
#endif

    painter->setClipRect( ourClipRect );

    // find which dataset to paint
    uint dataset;
    if ( !params()->findDataset( KDChartParams::DataEntry
                ,
                dataset, dataset ) ) {
        return ; // nothing to draw
    }

    if ( dataset == KDCHART_ALL_DATASETS )
        // setChartSourceMode() has not been used (or all datasets have been
        // configured to be used); use the first dataset by
        // default
        dataset = 0;


    // Number of values: If -1, use all values, otherwise use the
    // specified number of values.
    if ( params()->numValues() != -1 )
        _numValues = params()->numValues();
    else
        _numValues = data->usedCols();

    _startAngles.resize( _numValues );
    _angleLens.resize( _numValues );

    // compute position
    _size = QMIN( _dataRect.width(), _dataRect.height() ); // initial size
    // if the pies explode, we need to give them additional space =>
    // make the basic size smaller
    if ( params()->explode() ) {
        double doubleSize = ( double ) _size;
        doubleSize /= ( 1.0 + params()->explodeFactor() * 2 );
        _size = ( int ) doubleSize;
    }

    int sizeFor3DEffect = 0;
    if ( !params()->threeDPies() ) {

        int x = ( _dataRect.width() == _size ) ? 0 : ( ( _dataRect.width() - _size ) / 2 );
        int y = ( _dataRect.height() == _size ) ? 0 : ( ( _dataRect.height() - _size ) / 2 );
        _position = QRect( x, y, _size, _size );
        _position.moveBy( _dataRect.left(), _dataRect.top() );
    } else {
        // threeD: width is the maximum possible width; height is 1/2 of that
        int x = ( _dataRect.width() == _size ) ? 0 : ( ( _dataRect.width() - _size ) / 2 );
        int height = _size;
        // make sure that the height plus the threeDheight is not more than the
        // available size
        if ( params()->threeDPieHeight() >= 0 ) {
            // positive pie height: absolute value
            sizeFor3DEffect = params()->threeDPieHeight();
            height = _size - sizeFor3DEffect;
        } else {
            // negative pie height: relative value
            sizeFor3DEffect = -( int ) ( ( ( double ) params()->threeDPieHeight() / 100.0 ) * ( double ) height );
            height = _size - sizeFor3DEffect;
        }
        int y = ( _dataRect.height() == height ) ? 0 : ( ( _dataRect.height() - height - sizeFor3DEffect ) / 2 );

        _position = QRect( _dataRect.left() + x, _dataRect.top() + y,
                _size, height );
        //  _position.moveBy( _dataRect.left(), _dataRect.top() );
    }

    double sum = data->rowAbsSum( dataset );
    if( sum==0 ) //nothing to draw
        return;
    double sectorsPerValue = 5760.0 / sum; // 5760 == 16*360, number of sections in Qt circle

    int currentValue = params()->pieStart() * 16;
    bool atLeastOneValue = false; // guard against completely empty tables
    QVariant vValY;
    for ( int value = 0; value < _numValues; value++ ) {
        // is there anything at all at this value
        /* see above for meaning of 16 */

        if( data->cellCoord( dataset, value, vValY, 1 ) &&
            QVariant::Double == vValY.type() ){
            _startAngles[ value ] = currentValue;
            const double cellValue = fabs( vValY.toDouble() );
            _angleLens[ value ] = ( int ) floor( cellValue * sectorsPerValue + 0.5 );
            atLeastOneValue = true;
        } else { // mark as non-existent
            _angleLens[ value ] = 0;
            if ( value > 0 )
                _startAngles[ value ] = _startAngles[ value - 1 ];
            else
                _startAngles[ value ] = currentValue;
        }

        currentValue = _startAngles[ value ] + _angleLens[ value ];
    }

    // If there was no value at all, bail out, to avoid endless loops
    // later on (e.g. in findPieAt()).
    if( !atLeastOneValue )
        return;


    // Find the backmost pie which is at +90° and needs to be drawn
    // first
    int backmostpie = findPieAt( 90 * 16 );
    // Find the frontmost pie (at -90°/+270°) that should be drawn last
    int frontmostpie = findPieAt( 270 * 16 );
    // and put the backmost pie on the TODO stack to initialize it,
    // but only if it is not the frontmostpie
    QValueStack < int > todostack;
    if ( backmostpie != frontmostpie )
        todostack.push( backmostpie );
    else {
        // Otherwise, try to find something else
        int leftOfCurrent = findLeftPie( backmostpie );
        if ( leftOfCurrent != frontmostpie ) {
            todostack.push( leftOfCurrent );
        } else {
            int rightOfCurrent = findRightPie( backmostpie );
            if ( rightOfCurrent != frontmostpie ) {
                todostack.push( rightOfCurrent );
            }
        }
        // If we get here, there was nothing else, and we will bail
        // out of the while loop below.
    }

    // The list with pies that have already been drawn

    QValueList < int > donelist;

    // Draw pies until the todostack is empty or only the frontmost
    // pie is there
    while ( !todostack.isEmpty() &&
            !( ( todostack.count() == 1 ) &&
                ( ( todostack.top() == frontmostpie ) ) ) ) {
        // The while loop cannot be cancelled if frontmostpie is on
        // top of the stack, but this is also backmostpie (can happen
        // when one of the pies covers more than 1/2 of the circle. In
        // this case, we need to find something else to put on the
        // stack to get things going.

        // take one pie from the stack
        int currentpie = todostack.pop();
        // if this pie was already drawn, ignore it
        if ( donelist.find( currentpie ) != donelist.end() )
            continue;

        // If this pie is the frontmost pie, put it back, but at the
        // second position (otherwise, there would be an endless
        // loop). If this pie is the frontmost pie, there must be at
        // least one other pie, otherwise the loop would already have
        // been terminated by the loop condition.
        if ( currentpie == frontmostpie ) {
            Q_ASSERT( !todostack.isEmpty() );
            // QValueStack::exchange() would be nice here...
            int secondpie = todostack.pop();
            if ( currentpie == secondpie )
                // no need to have the second pie twice on the stack,
                // forget about one instance and take the third
                // instead
                if ( todostack.isEmpty() )
                    break; // done anyway
                else
                    secondpie = todostack.pop();
            todostack.push( currentpie );
            todostack.push( secondpie );
            continue;
        }

        // When we get here, we can just draw the pie and proceed.
        drawOnePie( painter, data, dataset, currentpie, chart,
                sizeFor3DEffect,
                regions );

        // Mark the pie just drawn as done.
        donelist.append( currentpie );

        // Now take the pie to the left and to the right, check
        // whether these have not been painted already, and put them
        // on the stack.
        int leftOfCurrent = findLeftPie( currentpie );
        if ( donelist.find( leftOfCurrent ) == donelist.end() )
            todostack.push( leftOfCurrent );
        int rightOfCurrent = findRightPie( currentpie );
        if ( donelist.find( rightOfCurrent ) == donelist.end() )
            todostack.push( rightOfCurrent );
    }

    // now only the frontmost pie is left to draw
    drawOnePie( painter, data, dataset, frontmostpie, chart,
            sizeFor3DEffect,
            regions );
}
示例#11
0
QString Speech::prepareCommand (QString command, const QString &text,
                          const QString &filename, const QString &language) {
#ifdef macroExpander
   QMap<QChar,QString> map;
   map['t'] = text;
   map['f'] = filename;
   map['l'] = language;
   return KMacroExpander::expandMacrosShellQuote (command, map);
#else
   QValueStack<bool> stack;  // saved isdoublequote values during parsing of braces
   bool issinglequote=false; // inside '...' ?
   bool isdoublequote=false; // inside "..." ?
   int noreplace=0; // nested braces when within ${...}
   QString escText = KShellProcess::quote(text);

   // character sequences that change the state or need to be otherwise processed
   QRegExp re_singlequote("('|%%|%t|%f|%l)");
   QRegExp re_doublequote("(\"|\\\\|`|\\$\\(|\\$\\{|%%|%t|%f|%l)");
   QRegExp re_noquote  ("('|\"|\\\\|`|\\$\\(|\\$\\{|\\(|\\{|\\)|\\}|%%|%t|%f|%l)");

   // parse the command:
   for (int i = re_noquote.search(command);
        i != -1;
        i = (issinglequote?re_singlequote.search(command,i)
            :isdoublequote?re_doublequote.search(command,i)
            :re_noquote.search(command,i))
       )
      // while there are character sequences that need to be processed
   {
      if ((command[i]=='(') || (command[i]=='{')) { // (...) or {...}
         // assert(isdoublequote == false)
         stack.push(isdoublequote);
         if (noreplace > 0)
            // count nested braces when within ${...}
            noreplace++;
         i++;
      }
      else if (command[i]=='$') { // $(...) or ${...}
         stack.push(isdoublequote);
         isdoublequote = false;
         if ((noreplace > 0) || (command[i+1]=='{'))
            // count nested braces when within ${...}
            noreplace++;
         i+=2;
      }
      else if ((command[i]==')') || (command[i]=='}')) {
         // $(...) or (...) or ${...} or {...}
         if (!stack.isEmpty())
            isdoublequote = stack.pop();
         else
            qWarning("Parse error.");
         if (noreplace > 0)
            // count nested braces when within ${...}
            noreplace--;
         i++;
      }
      else if (command[i]=='\'') {
         issinglequote=!issinglequote;
         i++;
      }
      else if (command[i]=='"') {
         isdoublequote=!isdoublequote;
         i++;
      }
      else if (command[i]=='\\')
         i+=2;
      else if (command[i]=='`') {
         // Replace all `...` with safer $(...)
         command.replace (i, 1, "$(");
         QRegExp re_backticks("(`|\\\\`|\\\\\\\\|\\\\\\$)");
         for (int i2=re_backticks.search(command,i+2);
              i2!=-1;
              i2=re_backticks.search(command,i2)
             )
         {
            if (command[i2] == '`') {
               command.replace (i2, 1, ")");
               i2=command.length(); // leave loop
            }
            else {
               // remove backslash and ignore following character
               command.remove (i2, 1);
               i2++;
            }
         }
         // Leave i unchanged! We need to process "$("
      }
      else if (noreplace > 0) { // do not replace macros within ${...}
         if (issinglequote)
            i+=re_singlequote.matchedLength();
         else if (isdoublequote)
            i+=re_doublequote.matchedLength();
         else
            i+=re_noquote.matchedLength();
      }
      else { // replace macro
         QString match, v;

         // get match
         if (issinglequote)
            match=re_singlequote.cap();
         else if (isdoublequote)
            match=re_doublequote.cap();
         else
            match=re_noquote.cap();

         // substitute %variables
         if (match=="%t")
            v = escText;
         else if (match=="%f")
            v = filename;
         else if (match=="%%")
            v = "%";
         else if (match=="%l")
            v = language;

         // %variable inside of a quote?
         if (isdoublequote)
            v='"'+v+'"';
         else if (issinglequote)
            v="'"+v+"'";

         command.replace (i, match.length(), v);
         i+=v.length();
      }
   }
   return command;
#endif
}
示例#12
0
bool KMacroExpanderBase::expandMacrosShellQuote( QString &str, uint &pos )
{
    int len;
    uint pos2;
    QChar ec( escapechar );
    State state = { noquote, false };
    QValueStack<State> sstack;
    QValueStack<Save> ostack;
    QStringList rst;
    QString rsts;

    while (pos < str.length()) {
        QChar cc( str.unicode()[pos] );
        if (ec != (char)0) {
            if (cc != ec)
                goto nohit;
            if (!(len = expandEscapedMacro( str, pos, rst )))
                goto nohit;
        } else {
            if (!(len = expandPlainMacro( str, pos, rst )))
                goto nohit;
        }
            if (len < 0) {
                pos -= len;
                continue;
            }
            if (state.dquote) {
                rsts = rst.join( " " );
                rsts.replace( QRegExp("([$`\"\\\\])"), "\\\\1" );
            } else if (state.current == dollarquote) {
                rsts = rst.join( " " );
                rsts.replace( QRegExp("(['\\\\])"), "\\\\1" );
            } else if (state.current == singlequote) {
                rsts = rst.join( " " );
                rsts.replace( '\'', "'\\''");
            } else {
                if (rst.isEmpty()) {
                    str.remove( pos, len );
                    continue;
                } else {
                    rsts = "'";
#if 0 // this could pay off if join() would be cleverer and the strings were long
                    for (QStringList::Iterator it = rst.begin(); it != rst.end(); ++it)
                        (*it).replace( '\'', "'\\''" );
                    rsts += rst.join( "' '" );
#else
                    for (QStringList::ConstIterator it = rst.begin(); it != rst.end(); ++it) {
                        if (it != rst.begin())
                            rsts += "' '";
                        QString trsts( *it );
                        trsts.replace( '\'', "'\\''" );
                        rsts += trsts;
                    }
#endif
                    rsts += "'";
                }
            }
            rst.clear();
            str.replace( pos, len, rsts );
            pos += rsts.length();
            continue;
      nohit:
        if (state.current == singlequote) {
            if (cc == '\'')
                state = sstack.pop();
        } else if (cc == '\\') {
            // always swallow the char -> prevent anomalies due to expansion
            pos += 2;
            continue;
        } else if (state.current == dollarquote) {
            if (cc == '\'')
                state = sstack.pop();
        } else if (cc == '$') {
            cc = str[++pos];
            if (cc == '(') {
                sstack.push( state );
                if (str[pos + 1] == '(') {
                    Save sav = { str, pos + 2 };
                    ostack.push( sav );
                    state.current = math;
                    pos += 2;
                    continue;
                } else {
                    state.current = paren;
                    state.dquote = false;
                }
            } else if (cc == '{') {
                sstack.push( state );
                state.current = subst;
            } else if (!state.dquote) {
                if (cc == '\'') {
                    sstack.push( state );
                    state.current = dollarquote;
                } else if (cc == '"') {
                    sstack.push( state );
                    state.current = doublequote;
                    state.dquote = true;
                }
            }
            // always swallow the char -> prevent anomalies due to expansion
        } else if (cc == '`') {
            str.replace( pos, 1, "$( " ); // add space -> avoid creating $((
            pos2 = pos += 3;
            for (;;) {
                if (pos2 >= str.length()) {
                    pos = pos2;
                    return false;
                }
                cc = str.unicode()[pos2];
                if (cc == '`')
                    break;
                if (cc == '\\') {
                    cc = str[++pos2];
                    if (cc == '$' || cc == '`' || cc == '\\' ||
                        (cc == '"' && state.dquote))
                    {
                        str.remove( pos2 - 1, 1 );
                        continue;
                    }
                }
                pos2++;
            }
            str[pos2] = ')';
            sstack.push( state );
            state.current = paren;
            state.dquote = false;
            continue;
        } else if (state.current == doublequote) {
            if (cc == '"')
                state = sstack.pop();
        } else if (cc == '\'') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = singlequote;
            }
        } else if (cc == '"') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = doublequote;
                state.dquote = true;
            }
        } else if (state.current == subst) {
            if (cc == '}')
                state = sstack.pop();
        } else if (cc == ')') {
            if (state.current == math) {
                if (str[pos + 1] == ')') {
                    state = sstack.pop();
                    pos += 2;
                } else {
                    // false hit: the $(( was a $( ( in fact
                    // ash does not care, but bash does
                    pos = ostack.top().pos;
                    str = ostack.top().str;
                    ostack.pop();
                    state.current = paren;
                    state.dquote = false;
                    sstack.push( state );
                }
                continue;
            } else if (state.current == paren)
                state = sstack.pop();
            else
                break;
        } else if (cc == '}') {
            if (state.current == KMacroExpander::group)
                state = sstack.pop();
            else
                break;
        } else if (cc == '(') {
            sstack.push( state );
            state.current = paren;
        } else if (cc == '{') {
            sstack.push( state );
            state.current = KMacroExpander::group;
        }
        pos++;
    }
    return sstack.empty();
}