void CommandProcessor::customEvent(QEvent* e) { if (e->type() == 10000) { // EngineEvent return ; } else if (e->type() == 10001) { MClientEvent* me = static_cast<MClientEvent*>(e); if(me->dataTypes().contains("XMLAll")) { emit parseMudOutput(me->payload()->toString(), me->dataTypes()); } else if (me->dataTypes().contains("UserInput")) { emit parseUserInput(me->payload()->toString()); } else if (me->dataTypes().contains("SocketConnected")) { emit socketOpen(true); } else if (me->dataTypes().contains("SocketDisconnected")) { emit socketOpen(false); } else if (me->dataTypes().contains("UnlockProcessor")) { qDebug() << "* got UNLOCK message"; _task->_semaphore.release(); } } }
int main(int argc, char *argv[]){ sleepy = argc != 1? 0 : 1;//So that if a machine is playing, sleeps can be removed struct timespec delayTime;// delayTime.tv_sec = 0;//These three lines create something that nanosleep can use to sleep. Details can be changed to change sleep time delayTime.tv_nsec = 500*1000*1000;//Starting at 500,000,000 nanoseconds (0.5s). Can be reassigned. puts("This is an in-development version. The treasure and traps are always visible."); char dungeon[DUNGEON_X][DUNGEON_Y]; uint8_t playerPos[2] = {1, 1};//Starting position for the player uint8_t playing = 1; //So we don't instantly exit uint8_t monsterPos[2] = {2, 2}; //Starting monster position - randomisation incoming uint8_t awake = 0; //The monster starts invisible. This doubles as 'is the monster active?' uint8_t trapPos[2][2] = {{1, 2}, {3, 5}}; //Two traps to wake the monster - will be randomised uint8_t treasurePos[2] = {2, 1}; //The treasure was once in the same place as the monster. Randomisation will need to ensure that this is never the case setUpDungeon(&dungeon, playerPos, trapPos, monsterPos, treasurePos);//Because setUpDungeon takes a pointer, and a bunch of positions to tell it where stuff goes //validateDungeon(&dungeon);//As does validateDungeon. Commented because reasons if (sleepy) nanosleep(&delayTime, NULL);//Wait a moment while(playing){//If you're not playing anymore, the game really ought to end system("clear");//We are now officially *NIX specific uint8_t isValidCommand = 0;//So that if the input is invalid, it can be ignored and retried without redrawing uint8_t ignoreNext = 0;//For invalid strings, helps prevent ignorance of next valid input int8_t parseReturn; setUpDungeon(&dungeon, playerPos, trapPos, monsterPos, treasurePos);//Because setUpDungeon takes a pointer to a char[][] //and a bunch of positions so that all things are in their rightful places drawDungeon(&dungeon, playerPos, trapPos, monsterPos, awake, treasurePos);//drawDungeon must know all things' positions printPrompt(&dungeon, awake, playerPos, trapPos, monsterPos, treasurePos); char text[3];//Command char, \n and \0 while(!isValidCommand){ fgets(text, 3, stdin);//Technically, this reads a file. stdin is a file, though. Uses a pointer, the number of characters you want and file if((text[1] == '\n' && text[2] == '\0') || text[1] == '\0'){//If the only input characters are the command, \n and EOF, or the command is \nEOF //in the event that the previous command was invalid and of the correct length type. //Rejects strings terminated with ^D but no \n, and glitches out, but that's not the kind of thing if(ignoreNext || text[0] == '\n'){ //any normal person would be inputting, anyway. Machines will learn what constitutes valid, too ignoreNext = 0; } else{ parseReturn = parseUserInput(&dungeon, text[0], &playerPos, &awake, &trapPos); isValidCommand = parseReturn == 1? 1 : 0; } } else{ if(!ignoreNext){ puts("Invalid command."); ignoreNext = 1; if (sleepy) nanosleep(&delayTime, NULL); } } } if (sleepy) nanosleep(&delayTime, NULL); doMonsterMove(&dungeon, playerPos, &monsterPos, &playing); } return 0; }
int main(int argc, char *args) { struct termios newTermio; struct termios storedTermio; bool running = true; char choice[8] = {0}; int count = 0; tcgetattr(0,&storedTermio); memcpy(&newTermio,&storedTermio,sizeof(struct termios)); // Disable canonical mode, and set buffer size to 0 byte(s) newTermio.c_lflag &= (~ICANON); newTermio.c_lflag &= (~ECHO); newTermio.c_cc[VTIME] = 0; newTermio.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&newTermio); printf("\nOpenJAUS Node Manager Version %s (%s)\n\n", OJ_NODE_MANAGER_VERSION, __DATE__); FileLoader *configData = new FileLoader("nodeManager.conf"); MyHandler *handler = new MyHandler(); nm = new NodeManager(configData, handler); printHelpMenu(); while(running) { bzero(choice, 8); count = read(0, &choice, 8); //printf("%d %d %d %d %d %d %d %d %d\n", count, choice[0], choice[1], choice[2], choice[3], choice[4], choice[5], choice[6], choice[7]); if(count == 1 && choice[0] == 27) // ESC { running = false; } else if(count == 1) { parseUserInput(choice[0]); } } tcsetattr(0, TCSANOW, &storedTermio); return 0; }
void Game::run() { /*TODO:The timer should be an object, Game::run should not call * sdl functions directly */ LCVAR_Event gameEvent; gameEvent.type = NOTHING; int startTicks = 0; //TODO: Clean this up, do not hardcode turn = WHITE; bool gameEnd = false; short errorCode = 0; //TODO: Don't hardcode these settings engine->init(32, 600, 600, ".", errorCode); handleErrors(errorCode); drawEverything(); refreshScreen(); while (!gameEnd){ getEvent(gameEvent); if(gameEvent.type == QUIT){ gameEnd = true; }else if (gameEvent.type == MOVE){ parseUserInput(gameEvent); } drawEverything(); refreshScreen(); gameEvent.type = NOTHING; } }
void QgsAdvancedDigitizingDockWidget::lockConstraint( bool activate /* default true */ ) { CadConstraint *constraint = objectToConstraint( sender() ); if ( !constraint ) { return; } if ( activate ) { QString textValue = constraint->lineEdit()->text(); if ( !textValue.isEmpty() ) { bool ok; double value = parseUserInput( textValue, ok ); if ( ok ) { constraint->setValue( value ); } else { activate = false; } } else { activate = false; } } constraint->setLockMode( activate ? CadConstraint::HardLock : CadConstraint::NoLock ); if ( activate ) { // deactivate perpendicular/parallel if angle has been activated if ( constraint == mAngleConstraint.get() ) { lockAdditionalConstraint( NoConstraint ); } // run a fake map mouse event to update the paint item emit pointChanged( mCadPointList.value( 0 ) ); } }
void QgsAdvancedDigitizingDockWidget::updateConstraintValue( CadConstraint *constraint, const QString &textValue, bool convertExpression ) { if ( !constraint || textValue.isEmpty() ) { return; } if ( constraint->lockMode() == CadConstraint::NoLock ) return; bool ok; double value = parseUserInput( textValue, ok ); if ( !ok ) return; constraint->setValue( value, convertExpression ); // run a fake map mouse event to update the paint item emit pointChanged( mCadPointList.value( 0 ) ); }
/** * Application entry point. Configures the peripherals and starts the echo * server. * * For a description of parameters, please refer to the file description. * * \return 0 if successful, -1 in case of any error. */ int main(int argc, char *argv[]) { /* The client parameters specified by the user. */ static ClientParams clientParams; /* The client statistics. */ static ClientStats clientStats; /* The socket for sending/receiving the echo. */ int echoSocket; /* Address of the echo server. */ struct sockaddr_in echoServer; /* Address received by the echo client. */ struct sockaddr_in echoClient; /* Length of the address received by echo client. */ uint32_t clientLength = sizeof(struct sockaddr_in); /* Time stamp before sending the echo request. */ struct timeval timeBeforeSend; /* Time stamp after receiving the echo response. */ struct timeval timeAfterReceive; /* ID of the current fork. */ uint32_t forkNr = 0; /* Macro for logging debug messages to the console. */ #define LOGMSG(format,args...) printf("[%d] " format "\n", forkNr, ##args) printBanner(); /* Parse program options. */ if (!parseUserInput(argc, argv, &clientParams)) { printUsage(); return -1; } if (clientParams.showHelp) { printUsage(); return 0; } if (clientParams.showLicense) { printLicense(); return 0; } /* Create the requested number of forks. */ if (clientParams.numForks) { pid_t pid; do { if ((pid = fork()) == 0) { break; } forkNr++; clientParams.numForks--; } while (clientParams.numForks); } /* Create the echo request and response buffers. */ uint8_t *echoRequest; uint8_t *echoResponse = malloc(clientParams.echoLength); if (!echoResponse) { LOGMSG("*** Error allocating echo response buffer."); return -1; } /* Create the UDP socket. */ echoSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (echoSocket < 0) { LOGMSG("*** Error creating echo socket."); return -1; } /* Create the echo server address. */ memset(&echoServer, 0, sizeof(echoServer)); echoServer.sin_family = AF_INET; echoServer.sin_addr.s_addr = clientParams.serverAddr; echoServer.sin_port = htons(7); /* Prepare the stats. */ clientStats.numErrors = 0; clientStats.maxTime = 0; clientStats.minTime = 0xFFFFFFFF; clientStats.averageTime = 0; clientStats.elapsedTime = malloc(sizeof(uint32_t) * clientParams.numIterations); if (!clientStats.elapsedTime) { LOGMSG("*** Error allocating memory."); return -1; } /* Loop through the number of selected iterations. */ uint32_t iter; for (iter = 0; iter < clientParams.numIterations; iter++) { LOGMSG("Iteration %d/%d.", iter + 1, clientParams.numIterations); /* Prepare the echo request message. */ echoRequest = getEchoRequest(clientParams.echoLength); clientStats.elapsedTime[iter] = 0; /* Send the data to the echo server. */ LOGMSG("Sending %d characters to %s...", clientParams.echoLength, clientParams.serverAddrString); gettimeofday(&timeBeforeSend, NULL); int32_t requestLength = sendto(echoSocket, echoRequest, clientParams.echoLength, 0, (struct sockaddr *)&echoServer, sizeof(echoServer)); if (requestLength != clientParams.echoLength) { LOGMSG("*** Error sending echo request."); clientStats.numErrors++; continue; } /* Set timeout for echo reception. */ if (sigsetjmp(receiveTimeout, 1)) { LOGMSG("*** Timeout while waiting for echo."); clientStats.numErrors++; continue; } signal(SIGALRM, receiveTimeoutHandler); alarm(ECHO_RECEIVE_TIMEOUT); /* Wait for the echo response. */ int32_t responseLength = recvfrom(echoSocket, echoResponse, clientParams.echoLength, 0, (struct sockaddr *)&echoClient, &clientLength); /* Clear the timeout alarm and remember the time. */ alarm(0); signal(SIGALRM, SIG_DFL); gettimeofday(&timeAfterReceive, NULL); /* Check the echo response. */ if (responseLength == -1) { LOGMSG("*** Echo receive error: %s", strerror(errno)); continue; } if (responseLength != clientParams.echoLength) { LOGMSG("*** Echo size mismatch: received %d bytes, expected %d.", responseLength, clientParams.echoLength); clientStats.numErrors++; continue; } if (echoServer.sin_addr.s_addr != echoClient.sin_addr.s_addr) { LOGMSG("*** Received unexpected echo from %s, expected %s.", inet_ntoa(echoClient.sin_addr), inet_ntoa(echoServer.sin_addr)); clientStats.numErrors++; continue; } if (memcmp(echoRequest, echoResponse, responseLength) != 0) { LOGMSG("*** Echo data mismatch."); clientStats.numErrors++; continue; } /* Remember the echo duration. */ clientStats.elapsedTime[iter] = getElapsedTime(&timeBeforeSend, &timeAfterReceive); LOGMSG("Received echo after %u milliseconds.", clientStats.elapsedTime[iter]); /* Calculate the statistics. */ clientStats.averageTime += clientStats.elapsedTime[iter]; if (clientStats.elapsedTime[iter] > clientStats.maxTime) { clientStats.maxTime = clientStats.elapsedTime[iter]; } if (clientStats.elapsedTime[iter] < clientStats.minTime) { clientStats.minTime = clientStats.elapsedTime[iter]; } } /* Calculate the statistics. */ if (clientParams.numIterations > clientStats.numErrors) { clientStats.averageTime = clientStats.averageTime / (clientParams.numIterations - clientStats.numErrors); } else { clientStats.averageTime = clientStats.maxTime; } /* Print the statistics. */ printf("\n"); LOGMSG("Finished with %d errors.", clientStats.numErrors); LOGMSG("Echo length = %d bytes: Avg = %d ms, Min = %d ms, Max = %d ms.", clientParams.echoLength, clientStats.averageTime, clientStats.minTime, clientStats.maxTime); printf("\n"); return 0; }
/** * Main function * */ int main(int argc, char* argv[]) { int i, j, cmdargv_len; int rc = 0; int pipeExists = 0; char *formattedInput = NULL; char *userInput = NULL; char **cmdargv = NULL ; char *cdCmd = NULL; char *pipeCmd = NULL; if((userInput = malloc(sizeof(char)*MAX_CMD_LEN)) == NULL) ERROR("Failed malloc\n"); cmdargv_len = sizeof(char*) * MAX_CMD_ARGS; if((cmdargv = (char**) malloc(cmdargv_len)) == NULL) { ERROR("Failed malloc\n"); } else { memset(cmdargv, '\0', sizeof(char*) * MAX_CMD_ARGS); } registerSignalHandler(); while(1) { printf("_dash > "); got_sigint = false; if (fgets(userInput, MAX_CMD_LEN, stdin) == NULL) { if (got_sigint) { printf("\n"); continue; } else { // Ctrl+D return 0; } } // TODO: Sanitize user input! We're currently hoping the user is a // benelovent, sweet human being. HA! if( (formattedInput = malloc(sizeof(userInput))) == NULL ) ERROR("Failed malloc\n"); removeNewLine(userInput, formattedInput); // See if user wants out. if((strcmp("quit", formattedInput) == 0) || (strcmp("exit", formattedInput) == 0) || (strcmp("q", formattedInput) == 0)) { printf("Quitting!\n"); goto cleanup; } // Check to see if user wants to change working directories if( (cdCmd = strstr(formattedInput, "cd ")) != NULL ) { if(changeDir(cdCmd) != 0) ERROR("cd failed."); free(cdCmd); // No need to fork/exec, can just move on. continue; } // Check to see if user wants to pipe commands if( (pipeCmd = strstr(formattedInput, "|")) != NULL ) { pipeExists = 1; // Don't need to free pipeCmd bc freeing formattedInput will take // care of that for us. //free(pipeCmd); } parseUserInput(formattedInput, cmdargv); for(j=0; cmdargv[j] != NULL; j++) printf("%d: cmdargv[%d]: %s\n", __LINE__, j, cmdargv[j]); rc = execute_fork(cmdargv, pipeExists); ASSERT( rc != 0 ); pipeExists = 0; } /* Cleanup! */ cleanup: free(formattedInput); free(userInput); if (cmdargv) { for (i = 0; i < MAX_CMD_ARGS; i++) { free(cmdargv[i]); /* free(NULL) is ok with glibc */ } } free(cmdargv); printf("All finished.\n"); return 0; }
int main(int argc, char *args) { // Console parameters HANDLE handleStdin; INPUT_RECORD inputEvents[128]; DWORD eventCount; // Control parameter bool running = true; int i = 0; printf("\nOpenJAUS Node Manager Version %s (%s)\n\n", OJ_NODE_MANAGER_VERSION, __DATE__); // Setup the console window's input handle handleStdin = GetStdHandle(STD_INPUT_HANDLE); MyHandler *handler = new MyHandler(); FileLoader *configData = new FileLoader("nodeManager.conf"); nm = new NodeManager(configData, handler); printHelpMenu(); while(running) { // See how many events are waiting for us, this prevents blocking if none GetNumberOfConsoleInputEvents(handleStdin, &eventCount); if(eventCount > 0) { // Check for user input here ReadConsoleInput( handleStdin, // input buffer handle inputEvents, // buffer to read into 128, // size of read buffer &eventCount); // number of records read } // Parse console input events for (i = 0; i < (int) eventCount; i++) { switch(inputEvents[i].EventType) { case KEY_EVENT: // keyboard input if(inputEvents[i].Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE) { running = false; } else if(inputEvents[i].Event.KeyEvent.bKeyDown) { parseUserInput(inputEvents[i].Event.KeyEvent.uChar.AsciiChar); } break; default: break; } } Sleep((DWORD)(0.2*1e3)); } return 0; }
char getUserInput() { char retVal = FALSE; int choice; #if defined(WIN32) int i = 0; #endif if(verbose) { #if defined(WIN32) INPUT_RECORD inputEvents[128]; DWORD eventCount; // See how many events are waiting for us, this prevents blocking if none GetNumberOfConsoleInputEvents(handleStdin, &eventCount); if(eventCount > 0) { // Check for user input here ReadConsoleInput( handleStdin, // input buffer handle inputEvents, // buffer to read into 128, // size of read buffer &eventCount); // number of records read } // Parse console input events for (i = 0; i < (int) eventCount; i++) { switch(inputEvents[i].EventType) { case KEY_EVENT: // keyboard input parseUserInput(inputEvents[i].Event.KeyEvent.uChar.AsciiChar); retVal = TRUE; break; default: break; } } #elif defined(__linux) || defined(linux) || defined(__linux__) || defined(__APPLE__) choice = getc(stdin); if(choice > -1) { parseUserInput(choice); retVal = TRUE; } #endif } else { choice = getch(); // Get the key that the user has selected updateScreen(keyboardLock, choice); if(choice > -1) { parseUserInput(choice); retVal = TRUE; } } return retVal; }