示例#1
0
文件: main.c 项目: sebnow/mush
void run()
{
	char *input = NULL;
	char *prompt = NULL;
	queue_t *commandQueue = NULL;
	MushErrorCode errorCode;
	do {
		prompt = getPrompt();
		printf("%s", prompt);
		/* Free input buffer from previous loop run */
		if(input != NULL) {
			free(input);
		}
		input = (char *)getInput();
		commandQueue = commandQueueFromInput(input);
		if(commandQueue == NULL && mushError() != kMushNoError) {
			fprintf(stderr, "mush: %s\n", mushErrorDescription());
		} else {
			errorCode = executeCommandsInQueue(commandQueue);
			if(errorCode != 0 && mushError() != kMushNoError) {
				fprintf(stderr, "mush: %s\n", mushErrorDescription());
			}
			queueFree(commandQueue);
		}
	} while(1);
}
示例#2
0
static int process_input()
/*
 * purpose: runs the main loop of the shell program and in each loop iteration
	    takes input from user and execute it by calling command module
*   Return : 0 as this funtion does not prpagate errors out of it. Gets the
*		the status of last command ran and reports error if any.
*   This funtion gets the input, create arguments, run command and finally
*	free memory allocated for arguments.Hence this function guarantees that 
	it will release memory it has acquired.   
*/
{
	char tempstr[1024];
	char **argv;//command arguments
	const char* prompt = getPrompt();//shell program prompt
	int argc;//number of command arguments
	while(1)
	{
		//get next command and create aruments
		if ( (argv = next_cmd(prompt,&argc)) != NULL )
		{
			//run command
			if(run_command(argc,argv) != 0)
			{
				sprintf(tempstr,"%s\r\n",my_strerr(my_errno));uprintf(tempstr);
			}
			//destroy arguments
			arguments_destroy(argc,argv);
		}
	}
	return 0;
}
示例#3
0
void mainLoop(std::shared_ptr<WalletInfo> walletInfo, CryptoNote::INode &node)
{
    if (walletInfo->viewWallet)
    {
        printCommands(basicViewWalletCommands());
    }
    else
    {
        printCommands(basicCommands());
    }
    
    while (true)
    {
        std::string command;

        if (walletInfo->viewWallet)
        {
            command = parseCommand(
                basicViewWalletCommands(),
                allViewWalletCommands(),
                getPrompt(walletInfo),
                true,
                walletInfo
            );
        }
        else
        {
            command = parseCommand(
                basicCommands(),
                allCommands(),
                getPrompt(walletInfo),
                true,
                walletInfo
            );
        }

        /* User exited */
        if (!handleCommand(command, walletInfo, node))
        {
            return;
        }
    }
}
示例#4
0
/* Get the value of an option */
bool JPWiFly::getopt(int opt, String& buf) {
	StCommand st(this);

	writeData_P(requests[opt].req);
	if (match(requests[opt].resp, 500)) {
		buffer.readTo_P(PSTR("\r\n"), &buf);
		getPrompt();
		return true;
	}
	return false;
}
示例#5
0
/*
*   Creates call tree. 
*   Reads line by line from input, checks the type of line
*   A nested Ifblock has parent COMMSEQ. sets the COMMSEQ
*   as parent of if block. the_if_block points to top level
*   if block.
*   each if block has sequence of then and else commands.
*   the sequence is represented as linked list. The elements
*   of sequence can be a regular command or nested_if.   
*   creates a command sequence node when a then/else command
*   is encountered. if command is nested if block calls itself
*   to build tree for nested if block and passes the command sequence
*   node as parent. keeps poiter to current node in order to set
*   its next element.
*   parameters: FILE* fp - input file
*               IFBLOCK* ifBlock - current if block
*               COMMSEQ* parent - parent of ifblock
*   returns : 0 if success otherwise 1
*/
static int buildTree(FILE* fp,IFBLOCK* ifBlock,COMMSEQ* parent)
{
    enum ControlType type;//control type
    enum ControlState state = WANT_THEN;//control staes
    COMMSEQ **currSeq,*tempSeq;//current node and a temp node
    IFBLOCK* newIfBlock;//for programming convenience
    char **arglist,*cmdline;
    int ret = 0;
    const char* getPrompt();
    
    if( parent != NULL){
        parent->cmd = (void*)ifBlock;
    }
    while((cmdline = next_cmd(getPrompt(), fp)) != NULL){//get next line
        cmdline = varSubstitute(cmdline); //variable substituion
        arglist = splitline(cmdline);
        if(arglist[0] != NULL){
            type = getCtrlType(arglist[0]);
            if(type == T_IF){//nested if
                tempSeq = getNewComSeq(NESTED_IF);//create new comm seq node
                newIfBlock = getNewIfBlock(arglist);//create new if block
                *currSeq = tempSeq;//update currseq
                currSeq = &tempSeq->next;
                ret = buildTree(fp,newIfBlock,tempSeq);//build tree recursively
            }
            else if(type == T_THEN){//Then block
                if(state != WANT_THEN)
                    return errorMsg("unexpected then");//something wrong
                state = WANT_ELSE_FI;
                currSeq = &(ifBlock->thenComSeq);//update currseq to then seq
            } 
            else if(type == T_ELSE){//else
                if(state != WANT_ELSE_FI)
                    return errorMsg("unexpected else");//something wrong
                state = WANT_FI;
                currSeq = &(ifBlock->elseComSeq);//update currseq to then seq
            } 
            else if(type == T_FI){//fi
                if(state != WANT_FI && state != WANT_ELSE_FI)
                    return errorMsg("unexpected fi");//something wrong
                return ret;//return when fi is encountered
            }
            else{//then/else regular commands
                tempSeq = getNewComSeq(COMMAND);//new comm seq node
                tempSeq->cmd = (void*)cmdline;
                *currSeq = tempSeq;
                currSeq = &tempSeq->next;//update currseq
            }
        }
    }//something wrong EOF is encountered, expected:fi
    return ( (cmdline == NULL) ? errorMsg("unexpected") : ret );    
}
示例#6
0
void QConsoleWidget::endEvals() {
	/* 
	当此函栈反解的时候eval才结束
	提前结束eval会出现逻辑错误
	*/
	class EndEvalsLock__ {
		QConsoleWidget * __this_0_;
	public:
		EndEvalsLock__(QConsoleWidget * _t_):
			__this_0_(_t_){
			__this_0_->isEvaling_ = true;
		}
		~EndEvalsLock__() {
			__this_0_->isEvaling_ = false;
		}
	};
	EndEvalsLock__ __lock__this__(this);

	bool need_update_charFormate__ = false;
    do{//: get all command information here
        auto doc_ = this->document();
        doc_->clearUndoRedoStacks();
        auto block_ = doc_->findBlock( this->promptEndPos_);
		
		/*
		当clear and save 时调用
		*/
		if (block_.isValid() == false) { 
			need_update_charFormate__ = true;
			break; 
		}
		
		{
			QTextCursor tc_( block_ );
			auto bf_ = block_.blockFormat();
			bf_.setTextIndent(0);
			tc_.setBlockFormat( bf_ );
			this->setTextCursor(tc_);
		}

	} while (0);

    setPrompt( getPrompt() );
    this->setUndoRedoEnabled(true);
	_pf<void, EnableActions>(this);

	if ( need_update_charFormate__ ) {
		this->updateCharFormat();
	}
}
void MainWindow::generatePrompt()
{
    bool generatedDict = false;
    QFile dictionary(QDir::currentPath() + "/lib/dictionary.txt");
    if(dictionary.exists())
    {
        if(dictionary.size())
        {
            dictionary.open(QIODevice::ReadOnly);
            QString str(dictionary.readAll());
            prompts = str.split("\n");
        }
        else
        {
            first->setText("dictionary");
            second->setText("has no");
            third->setText("entries");
            return;
        }
    }
    else
    {
        dictionary.setFileName(QDir::currentPath() + "/lib/dictionary.txt");
        dictionary.open(QIODevice::WriteOnly);
        dictionary.write("each\nword\ngoes\non\na\nnew\nline");
        dictionary.close();
        first->setText("dictionary");
        second->setText("was");
        third->setText("created");
        generatedDict = true;
    }

    if(!prompts.isEmpty())
    {
        QStringList tempPrompt = getPrompt();
        first->setText(tempPrompt[0]);
        second->setText(tempPrompt[1]);
        third->setText(tempPrompt[2]);
    }
    else
    {
        if(!generatedDict)
        {
            first->setText(QString::fromStdString("dictionary"));
            second->setText(QString::fromStdString("not"));
            third->setText(QString::fromStdString("found"));
        }
    }
}
示例#8
0
bool CalcOptions::load(const char *filename)
{
	if(PrefReader::load(filename))
	{
		getFontValue("normalFmt", &_normalFmt);
		getFontValue("resultFmt", &_resultFmt);
		getFontValue("errorFmt", &_errorFmt);

		// append a space to the end of the prompt string
		setValue("prompt", std::string(getPrompt()) + " ");
		return true;
	}
	else
		return false;
}
示例#9
0
//-------------------------------------------------------------------------------------------------
void QCommandPrompt::keyPressEvent(QKeyEvent *e)
{
    // Wenn Enter gedrückt wird, wird die Eingabe als Kommando interpretiert
    switch(e->key())
    {
    case Qt::Key_Return:
        {
            // Alles zwischen Promptposition und dem Textende ist das Kommando
            QString sAll = toPlainText();
            QString sCmd = sAll.right(sAll.count() - m_nPromptPos);

            if (sCmd.length()>0 && (m_vHistory.size()==0 || m_vHistory.back()!=sCmd) )
            {
                m_vHistory.push_back(sCmd);

                while (m_vHistory.size() > m_nMaxHist)
                    m_vHistory.removeFirst();

                m_nHistPos = m_vHistory.size() - 1;
            }

            sCmd = sCmd.trimmed();
            if (!sCmd.isEmpty())
            {
                addLine(getPrompt() + sCmd.trimmed());
                emit commandInput(sCmd);
            }

            // Textcursor ans Ende versetzen
            QTextCursor tc = textCursor();
            tc.movePosition(QTextCursor::End);
            setTextCursor(tc);
        }
        break;

    case Qt::Key_Up:
    case Qt::Key_Down:
        if (m_vHistory.size()==0)
            break;

        clearLineExceptPrompt();
        insertPlainText(m_vHistory[m_nHistPos]);

        m_nHistPos = m_nHistPos + ((e->key()==Qt::Key_Up) ? -1 : 1);
        m_nHistPos = Utils::clamp(0, m_vHistory.size()-1, m_nHistPos);
        break;

    case Qt::Key_Home:
        {
            QTextCursor tc = textCursor();
            Qt::KeyboardModifiers mod = e->modifiers();
            if (mod & Qt::ShiftModifier)
                tc.setPosition(m_nPromptPos, QTextCursor::KeepAnchor);
            else
                tc.setPosition(m_nPromptPos, QTextCursor::MoveAnchor);

            setTextCursor(tc);

        }
        break;

    case Qt::Key_Backspace:
    case Qt::Key_Left:
        {
            int nPos = textCursor().position();
            if (nPos > m_nPromptPos)
                QPlainTextEdit::keyPressEvent(e);
        }
        break;

    default:
        {
            int nPos = textCursor().position();
            if (nPos < m_nPromptPos)
            {
                QTextCursor tc = textCursor();
                tc.movePosition(QTextCursor::End);
                setTextCursor(tc);
            }

            QPlainTextEdit::keyPressEvent(e);
        }
    }
}
示例#10
0
int main(int argc, char **argv)
{
	if(isArgumentForShowingVersion(argv)) showVersionAndExit();
	char	   *buf;
	char       *bufCopy;
	pid_t	   pid = getpid();
	pid_t      backgroundJob;
	int		   status = 0;
	char       *prompt = getPrompt();
	int  	   bg;
	int        jobNumber = 1;
	int counts;
	int jumpSet = 0;
	char *arguments[2048];
	initialize();
	printf("\n");
	setPrompt(prompt);
	while ((buf = readline(prompt))) {
		if(strlen(buf) != 0) {
			bufCopy = buddy_malloc((strlen(buf)+1)*sizeof(char));
			strcpy(bufCopy, buf);
			add_history(bufCopy);
		}
		else
		{
			 printFinishedJobs(jobList);
			 free(buf);
			 continue;
		}
		free(buf);
		if(isCommandNotEmpty(bufCopy)) bg = isBackgroundCommand(bufCopy);
		getArgument(arguments, bufCopy, &counts);
		if(isExitCommand(bufCopy)){
			buddy_free(bufCopy);
			freeList(jobList);
			if(arguments != NULL){
				freeArguments(counts, arguments, NULL);
			}
			exit(0);
		}
		if(isCdCommand(bufCopy, arguments)){
			changeDir(arguments);
		    freeArguments(counts, arguments, bufCopy);		
		}
		else if(isJobsCommand(bufCopy)) {
			printList(jobList);
			freeArguments(counts, arguments, bufCopy);
		}
		else if(isFgCommand(bufCopy, arguments)){			
			fg(arguments, jobList, counts, bufCopy);
		}
		else if(isBgCommand(bufCopy, arguments)){
			bgS(arguments, jobList, counts, bufCopy);
		}
		else if (isCommandNotEmpty(bufCopy)) 
		{
			if(bg == 1)
			{
				backgroundJob = fork();
				if(backgroundJob == 0) {
					ignoreSignals();
					runCommand(arguments, bufCopy);
				}
				else{
					NodePtr n = createAndSetNode(&jobNumber, backgroundJob, bufCopy, bg);
					recordCommand(n, jobNumber, bg);
					freeArguments(counts, arguments, bufCopy);
				}
			}
			else
			{		
				pid = fork();
				if(pid == 0){
					runCommand(arguments, bufCopy);
				}
				else {
					NodePtr n = createAndSetNode(&jobNumber, pid, bufCopy, bg);
					ignoreSignals();
					if((waitpid(pid,&status,WUNTRACED))<0) err_sys("waitpid error");
					freeArguments(counts, arguments, bufCopy);
					restoreSignalsAndDetermineStatus(status, jobList, n);
				}
			}
		}
		else
		{
			freeArguments(counts, arguments, bufCopy);
		}
		if(jumpSet == 0){
			sigsetjmp(env, 1);
			jumpSet = 1;
		}
		continue;
	}
	if(buf == NULL) printf("\n");
	exit(0);
}