Esempio n. 1
0
void parseData(char data[8]) {
    char m;
    int v;

    //printf("%s %d %c\n", data, strlen(data), data[1]);
    
    if(data[1]==':') {
        m = data[0];
        //printf("mode: %c\n", m);

        mode = m;
        modeChange = 2;
    }
    else if(0!=sscanf(data, "%x", &v)) {
        //printf("value:%02x\n", v); 

        if(modeChange==2 && mode!='X') {
            addr = v;
        } else if(modeChange==1 && mode!='X') {
            i2c_reg = v;
        } else if(modeChange && mode=='X') {
            v = strtol(data, NULL, 10);
            executeCmd(v);
        } else {
            executeCmd(v);
        }
        modeChange--;
    } 
}
Esempio n. 2
0
/**
 * Command processing thread.
 */
msg_t CmdExecutor::main(void){
  this->setName("CmdExecutor");
  eventmask_t evt = 0;
  struct EventListener el_command_long;
  chEvtRegisterMask(&event_mavlink_in_command_long, &el_command_long, EVMSK_MAVLINK_IN_COMMAND_LONG);

  /* wait modems */
  while(GlobalFlags.messaging_ready == 0)
    chThdSleepMilliseconds(50);

  /* main loop */
  while(!chThdShouldTerminate()){
    evt = chEvtWaitOneTimeout(EVMSK_MAVLINK_IN_COMMAND_LONG, MS2ST(50));

    switch (evt){
    case EVMSK_MAVLINK_IN_COMMAND_LONG:
      executeCmd(&mavlink_in_command_long_struct);
      break;

    default:
      break;
    }
  }

  chEvtUnregister(&event_mavlink_in_command_long, &el_command_long);
  chThdExit(0);
  return 0;
}
const std::string& EnConsole::dispatchCmdLine( const std::string& cmdline )
{
    static std::string result;
    result = "";

    std::vector< std::string > cmds;
    yaf3d::explode( cmdline, ";", &cmds ); // multiple commands can be given separated by semicolon
    std::vector< std::string >::iterator p_beg = cmds.begin(), p_end = cmds.end();
    for ( ; p_beg != p_end; ++p_beg )
    {
        // clean up cmd from leading whitespaces
        std::string cmd = *p_beg;
        cmd.erase( 0, cmd.find_first_not_of( " " ) );

        // append to log if log is created
        if ( _p_log )
            *_p_log << ">" << cmd << std::endl;

        result += executeCmd( cmd );

        // append to log if log is created
        if ( _p_log )
        {
            *_p_log << result << std::endl;
            _p_log->flush();
        }
    }

    return result;
}
Esempio n. 4
0
void device_PRT::CommitData()
{
	timeOutAt = 0;

	BOOL wait = 0;

	if (destination == "direct") {

		DWORD dwBytesWritten = 0;

		HANDLE lptPort = CreateFile(name, (GENERIC_READ | GENERIC_WRITE), 0, 0, OPEN_EXISTING, 0, 0);

		BOOL bErrorFlag = WriteFile(
			lptPort,           // open file handle
			rawdata.c_str(),      // start of data to write
			(DWORD)rawdata.size(),  // number of bytes to write
			&dwBytesWritten, // number of bytes that were written
			NULL);            // no overlapped structure

		if (FALSE == bErrorFlag)
		{
			ErrorDialog("ERROR: Unable open '%s'", name);
		}
		rawdata.clear();
		CloseHandle(lptPort);
		return;
	}

	if (!destination.empty()) {
		char* tmpFile = getTempFileName();

		if (tmpFile == NULL) {
			ErrorDialog("ERROR: Unable to get temporary filename.");
			return;
		}

		FILE* fh = fopen(tmpFile, "wb");

		if (fh) {
			if (fwrite(rawdata.c_str(), rawdata.size(), 1, fh)) {
				fclose(fh);
				executeCmd((char*)destination.c_str(), tmpFile, wait);
				if (wait) {
					remove(tmpFile);
				}
			} else {
				ErrorDialog("ERROR: Unable to write to temporary file '%s'.", tmpFile);
			}
		} else {
			ErrorDialog("ERROR: Unable to create temporary file '%s'.", tmpFile);
		}
		free(tmpFile);
	} else {
		ErrorDialog("ERROR: Port '%s' is not configured.", name);
	}
	rawdata.clear();
}
Esempio n. 5
0
void meshRemapTool::completeAction()
{
	if( resolveMapping() != MStatus::kSuccess )
	{
		reset();
		return;
	}
	executeCmd();
}
Esempio n. 6
0
//do special command processing,here we process the command to control the relay shield
void CommandControl::processCmd(byte headPos){
  //execute the command content
  executeCmd(rxBuffer+headPos+cmdHeadLen);
  //dump the processed command,and move the rest commands foward
  memcpy(rxBuffer,rxBuffer+headPos+cmdLen,rxLenInBuffer-headPos-cmdLen);
  rxLenInBuffer -= (headPos+cmdLen);
  
  
}
Esempio n. 7
0
void executeCmds (const char * page, uint8_t * ids, const char * cmd)
{
	uint8_t i = 0;
	while (255 != ids[i]) // ueber alle ids
	{
		executeCmd (page, ids[i], cmd);
		i++;
		// ggf. sleep (1); // ms
	}
}
Esempio n. 8
0
void bootGetUSART1( void )
{
    static u8 ucBuffer[ 256 ], ucIndex = 0;
    u8 ucByte, CurrentStream;

    CurrentStream = streamGetSTDIO();
    streamSetSTDIO( COM1 );
    if( USART1->SR & USART_RXNE ) { 
        USART1->SR &= ~USART_RXNE;
        ucByte = USART1->DR ;
        USART1->DR = ucByte;
        if( xmodemProcess( &XModem, ucByte ) ){
            streamSetSTDIO( CurrentStream );
            return;
        } // if
        if( ucByte == '+' ){
            globalBootStatus = BOOT_CANCEL;
            //putstr( (u8*)BOOT_PROMPT );
            //print( COM3, BOOT_PROMPT );
            bootPrintPrompt();
            streamSetSTDIO( CurrentStream );
            return;
        } // if
        if( globalBootStatus & BOOT_CANCEL ){
            if( ucByte == '\r' ){
                ucBuffer[ ucIndex ] = '\0'; // Add NULL to terminate string
                ucIndex = 0;
                if( executeCmd( ucBuffer, (PYGMYCMD *)BOOTCOMMANDS ) ){
                    //print( COM3, BOOT_PROMPT  ); 
                    bootPrintPrompt();
                } else{
                    //print( COM3, BOOT_ERROR ); 
                    print( STDIO, "\rERROR" );
                    bootPrintPrompt();
                } // else
            } else{
                //putcUSART3( ucByte );
                //print( COM3, "%c", ucByte );
                USART1->DR = ucByte;
                if( ucByte == '\b'  ){
                    if( ucIndex ){
                        --ucIndex;
                    } // if
                } else {
                    ucBuffer[ ucIndex++ ] = ucByte;
                } // else
            } // else
        } // if
    } // if
    streamSetSTDIO( CurrentStream );
}
Esempio n. 9
0
/* Main thread function
 * This function is called once and must handle every blocking action.
 * All shared class members (= the one used by the API) MUST be protected by the global mutex.
 */
void Player::run()
{
    QSettings settings;
    unsigned int statusPeriod = settings.value("player/status_period", EMS_MPD_STATUS_PERIOD).toUInt();

    /* Blocking connection. */
    connectToMpd();

    /* Set initial state of the player */
    configureInitial();

    /* Get the list of sound cards, this list does not change as the correspond
     * to the list defined in the mpd configuration file */
    retrieveSndCardList();

    /* Execute each command, or timeout each X ms
     * In all cases, the status is retrieved at the end.
     */
    while (true)
    {
        bool cmdInQueue = cmdAvailable.tryAcquire(1, statusPeriod);

        /* Quit this thread if asked */
        if (isInterruptionRequested())
        {
            break;
        }

        if (cmdInQueue)
        {
            EMSPlayerCmd cmd;
            mutex.lock();
            if(queue.size() == 0)
            {
                qCritical() << "Error, no command in the queue, but the semaphore was not empty.";
                mutex.unlock();
                continue;
            }
            cmd = queue.dequeue();
            mutex.unlock();

            executeCmd(cmd);
        }

        updateStatus();
    }

    /* Clean exit */
    disconnectToMpd();
}
Esempio n. 10
0
void processCmd (t_query * query)
{
	if (isnt (query->cmd,"")) // neues Kommando?
	{
		if (query->selectedId == 255) // entspricht "alle gelisteten Devices"
		{
			executeCmds (query->page, query->ids, query->cmd);
		}
		else
		{
			executeCmd (query->page, query->selectedId, query->cmd);
		}
	}
}
Esempio n. 11
0
void bootGetUSART2( void )
{
    static u8 COM2Buffer[ 256 ], COM2Index = 0;
    u8 ucByte, CurrentStream;

    //pinSet( LED0, HIGH );
    CurrentStream = streamGetSTDIO();
    streamSetSTDIO( COM2 );
    if( USART2->SR & USART_RXNE ) { 
        USART2->SR &= ~USART_RXNE;
        ucByte = USART2->DR;
        
        if( xmodemProcess( &XModem, ucByte ) ){
            streamSetSTDIO( CurrentStream );
            return;
        } // if
        if( ucByte == '+' ){
            taskDelete( "boot" );
            globalBootStatus = BOOT_CANCEL;
            bootPrintPrompt();
            streamSetSTDIO( CurrentStream );
            return;
        } // if
        if( globalBootStatus & BOOT_CANCEL ){
            if( ucByte == '\r' ){
                COM2Buffer[ COM2Index ] = '\0'; // Add NULL to terminate string
                COM2Index = 0;
                if( executeCmd( COM2Buffer, (PYGMYCMD *)BOOTCOMMANDS ) ){
                    bootPrintPrompt();
                } else{
                    print( STDIO, "\rERROR" );
                    bootPrintPrompt();
                } // else
            } else{
                USART2->DR = ucByte;
                if( ucByte == '\b'  ){
                    if( COM2Index ){
                        --COM2Index;
                    } // if
                } else {
                    COM2Buffer[ COM2Index++ ] = ucByte;
                } // else
            } // else
        } // if
    } // if
    streamSetSTDIO( CurrentStream );
    //pinSet( LED0, LOW );
}
Esempio n. 12
0
void executeScript(char* scriptname,char* envp[]){
	int fd=0,pid=0,status=0;
	char* buffer=malloc(MAX_LENGTH);
	char* input=malloc(MAX_LENGTH);
	if((fd = open(scriptname, O_RDONLY)) < 0) {
		printf("===cannot open file:%s [error]!===\n",scriptname);
		printf("enter 'exit' to quit or other to continue!\n");
	}

	char ch;
	int i=0;
	while(1) {
		
		if(read(fd, &ch, 1) == 0) {
			#ifdef DEBUG	
			printf("not read file\n");
			#endif
			break;
		}
		buffer[i++]=ch;
		#ifdef DEBUG			
		printf("read a char:%c\n",buffer[i]);
		#endif
		if(ch == '\n') {
			input=buffer;
			buffer[i]='\0';
			#ifdef DEBUG
			printf("ch is:%c\n",buffer[0]);
			printf("Input is: %s\n",input);
			#endif
			pid = fork();
			if(pid == 0) {
				//printf("Input is:%s\n",buffer);
				executeCmd(input,envp);
				exit(0);
			} else {
				waitpid(pid, &status, 0);
			}
			//buffer=malloc(MAX_LENGTH);
			//memset(buffer,0,sizeof(buffer));
			//printf("i is:%d\n",i);
			i=0;
		}
		//i++;
	}

	close(fd);
}
Esempio n. 13
0
// -------------------------------------------------------------
mcResult_t getDevinfo(uint32_t *index, uint32_t *result)
{
    mcResult_t  ret;

    
    ret = executeCmd(index, result, CMD_DEVINFO_GET );
    if (ret != RET_OK) 
    {
        printf("Unable to execute CMD_FOO_SUB command: %d", ret);
        goto exit;
    }   

    printf("The result is %d \n", *result);

exit:    
    return ret;
}
Esempio n. 14
0
// -------------------------------------------------------------
mcResult_t add(uint32_t *num1, uint32_t *num2, uint32_t *result)
{
    mcResult_t  ret;

	LOG_I("Foo perform addition (%d) + (%d)", *num1, *num2);
    
    ret = executeCmd(num1, num2, result, CMD_FOO_ADD);
    if (ret != RET_OK) 
    {
        LOG_E("Unable to execute CMD_FOO_ADD command: %d", ret);
        goto exit;
    }   

    LOG_I("The result is %d", *result);

exit:    
    return ret;
}
Esempio n. 15
0
// -------------------------------------------------------------
mcResult_t minus(uint32_t *num1, uint32_t *num2, uint32_t *result)
{
    mcResult_t  ret;

	LOG_I("Foo perform minus (%d) - (%d)", *num2, *num1);
    
    ret = executeCmd(num1, num2, result, CMD_FOO_SUB);
    if (ret != RET_OK) 
    {
        LOG_E("Unable to execute CMD_FOO_SUB command: %d", ret);
        goto exit;
    }   

    LOG_I("The result is %d", *result);

exit:    
    return ret;
}
Esempio n. 16
0
int main(void)
{
	PORTA.DIRSET = PIN0_bm;
	PORTA.OUTSET = PIN0_bm;
	
	if (!systemSetClk32Mhz())
		badInitAlarm();
    if (!uartInit(19200, 1, 1))
		badInitAlarm();
	
	stepperInit(800, 255, 0, 255);

	//attach all servos:
	/*
	for (uint8_t i = 0; i < SERVO_AMNT; ++i)
		servoAttach(i, 45);*/
		
	systemInterruptEnable(INT_LOW);
	sei();
	
	char str[CMD_LENGTH];
	
    while (1)
    {		
		if (uartLinesReceived() > 0)
		{
			uartGetLine(str, CMD_LENGTH);

			switch (executeCmd(str))
			{
				case BAD_FORMAT:
					uartWrite("Err - cmd is NaN\r\n");
					break;
				case BAD_ARG:
					uartWrite("Err - not enough args or NaN\r\n");
					break;
				case BAD_CMD:
					uartWrite("Err - invalid cmd\r\b");
					break;
			}
		}
    }
}
Esempio n. 17
0
int main(void){
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	static char string[1000] = "";	
	char cmd[1000] = "";
	int exitCheck = 0;
	changeSize();
	printIntro(string);
	SetConsoleTextAttribute(hConsole, 0);
	system("cls");
	printMainString(string, 1);
	printInputField(string);
	while (!exitCheck){
		SetConsoleTextAttribute(hConsole, 14);
		fgets(cmd, 999, stdin);
		if ((strcmp(cmd, "") != 0)) exitCheck = executeCmd(cmd, string, 7 + strlen(string) / 74);
		cleanStr(cmd);
	}
	return 0;
}
Esempio n. 18
0
int main()
{
  int i;
	int inputSize;
	char buff[128];		// Character buffer
	char **args;	// Character buffer

  write(1, "Welcome to Hector Tejada's Shell (type 'x' to exit)\n", 52);

  while(1)
	{
		// Request a line of input
		write(1, "\nshell -> ", 10);

    inputSize = read(0, buff, 128);
    // Strip off carriage return
		buff[inputSize-1] = '\0';

		if(buff[0] == 0)
			continue;

		if((buff[0] == 'x') && (buff[1] == '\0'))
		{
			exit(0);
		}

		// make the argument vector
		args = argtok(buff, ' ');

		// execute the command
		executeCmd(args);

    free(args);

	}

	return 0;

}
Esempio n. 19
0
// interprets the user command;
// try to find the username in the database,
// forces the next command to be PASS
void user(char **params, short *abor, int fd,
	struct state *cstate, struct config *configuration) {
	if (params[0] == NULL) {
		respond(fd, 5, 0, 4, "Require username.");
		return;
	}
	switch (lookupUser(configuration->user_db, params[0], NULL, 0)) {
		// some error occured while reading the database
		case -1:
			respond(fd, 4, 5, 1, "Internal server error.");
			return;
		break;
		// user exists
		case 0:
			respond(fd, 3, 3, 1, "OK, awaiting password.");
		break;
		// user does not exist
		case 1:
			respond(fd, 4, 3, 0, "Unknown user.");
			return;
		break;
	}
	// waits for the next command and check if it is PASS
	struct cmd psswd;
	readCmd(fd, &psswd);
	if (strcasecmp(psswd.name, "PASS") != 0) {
		respond(fd, 5, 0, 3, "Bad command sequence.");
		return;
	}
	// sets the username and initial path
	strcpy(cstate->user, params[0]);
	(*cstate->path) = '/';
	(*(cstate->path + 1)) = 0;
	cstate->logged = 0;
	executeCmd(&psswd, NULL, fd, cstate, configuration);
}
Esempio n. 20
0
int main(int argc, char* argv[],char* envp[]) {

	getEnv(envp);
	#ifdef DEBUG
	printf("%s\t%s\t%s\n",envp[0],envp[1],envp[2]);
	#endif
	if(argc > 1) {
		executeScript(argv[1],envp);
		exit(0);
	}

	while(TRUE){

		shellPrompt();
		char* input=malloc(MAX_LENGTH);
		scanf("%s",input);//different from standard scanf which ignores space!
		/*int i=scanf("%[^\n]%*c",input);
		
		if(i==0){
			char tmp;
			scanf("%c",&tmp);
			continue;
		}*/
		//gets(input);
		//fgets(input,MAX_LENGTH,stdin);
		
		#ifdef DEBUG
		
		printf("(main) input is: %s\n",input);
		#endif

		executeCmd(input,envp);
		
	}

}
Esempio n. 21
0
void MMSInputManager::handleInput(MMSInputEvent *inputevent) {
	MMSWindow *window=NULL;

	this->mutex.lock();

	//lock mmsfb to ensure inputs are not interrupted by other threads
	mmsfb->lock();

	if (inputevent->type == MMSINPUTEVENTTYPE_KEYPRESS) {
		/* keyboard inputs */

#ifdef __ENABLE_DEBUG__
		/* check crtl+c and exit */
		if((inputevent->key==MMSKEY_SMALL_C)&&(this->lastkey==MMSKEY_CONTROL))
			exit(1);
#endif

/*
#ifdef ROTATE_180
		switch (inputevent->key) {
		case MMSKEY_CURSOR_LEFT:
			inputevent->key = MMSKEY_CURSOR_RIGHT;
			break;
		case MMSKEY_CURSOR_RIGHT:
			inputevent->key = MMSKEY_CURSOR_LEFT;
			break;
		case MMSKEY_CURSOR_UP:
			inputevent->key = MMSKEY_CURSOR_DOWN;
			break;
		case MMSKEY_CURSOR_DOWN:
			inputevent->key = MMSKEY_CURSOR_UP;
			break;
		default:
			break;
		}
#endif
*/

		this->lastkey = inputevent->key;

		this->mapper->mapkey(inputevent);

#if __ENABLE_LOG__ || __ENABLE_DEBUG__
		string symbol = mmskeys[inputevent->key];
		TRACEOUT("MMSINPUT", "KEY PRESS %d (MMSKEY_%s)", this->lastkey, symbol.c_str());
		if(lastkey != inputevent->key) {
			symbol = mmskeys[inputevent->key];
			TRACEOUT("MMSINPUT", " >MAPPED TO %d (MMSKEY_%s)", inputevent->key, symbol.c_str());
		}
#endif

		if((inputevent->key==MMSKEY_POWER)||(inputevent->key==MMSKEY_POWER2)) {
			if(config->getShutdown() == true) {
				DEBUGMSG("MMSINPUTMANAGER", "executing: %s", config->getShutdownCmd().c_str());

				executeCmd(config->getShutdownCmd());
				sleep(30);
			}
			exit(0);
		}

		window = this->windowmanager->getToplevelWindow();

		if(window!=NULL) {
			if	((inputevent->key==MMSKEY_CURSOR_DOWN)||(inputevent->key==MMSKEY_CURSOR_UP)
				||(inputevent->key==MMSKEY_CURSOR_LEFT)||(inputevent->key==MMSKEY_CURSOR_RIGHT)) {
				/* ok execute input on window */
				window->handleInput(inputevent);
				memset(inputevent, 0, sizeof(MMSInputEvent));
				this->mutex.unlock();
				mmsfb->unlock();
				return;
			}
		}

		// have to call subscriptions?
		bool call_subscriptions = true;
		if (window) {
			bool modal = false;
			window->getModal(modal);
			if (modal)
				call_subscriptions = false;
		}

		if (call_subscriptions) {
			// go through subscriptions
			for(unsigned int i = 0; i < subscriptions.size();i++) {
				MMSKeySymbol key;
				if (subscriptions.at(i)->getKey(key)) {
					if (key == inputevent->key) {
						DEBUGMSG("MMSINPUTMANAGER", "found a subscription");
						// ok i found one execute
						subscriptions.at(i)->callback.emit(subscriptions.at(i));
						// stop it only one key per subscription
						DEBUGMSG("MMSINPUTMANAGER", "returning from handle input");
						mmsfb->unlock();
						this->mutex.unlock();
						return;
					}
				}
			}
		}

		if(window != NULL)
			window->handleInput(inputevent);
			memset(inputevent, 0, sizeof(MMSInputEvent));
	}
	else
	if (inputevent->type == MMSINPUTEVENTTYPE_KEYRELEASE) {
		/* keyboard inputs */
#if __ENABLE_LOG__ || __ENABLE_DEBUG__
		string symbol = mmskeys[inputevent->key];
		TRACEOUT("MMSINPUT", "KEY RELEASE %d (MMSKEY_%s)", this->lastkey, symbol.c_str());
#endif
		MMSKeySymbol beforemap = inputevent->key;
		this->mapper->mapkey(inputevent);
#if __ENABLE_LOG__ || __ENABLE_DEBUG__
		if(inputevent->key != beforemap) {
			symbol = mmskeys[inputevent->key];
			TRACEOUT("MMSINPUT", " >MAPPED TO %d (MMSKEY_%s)", inputevent->key, symbol.c_str());
		}
#endif

		window = this->windowmanager->getToplevelWindow();

		if(window != NULL)
			window->handleInput(inputevent);
			memset(inputevent, 0, sizeof(MMSInputEvent));
	}
	else
	if (inputevent->type == MMSINPUTEVENTTYPE_BUTTONPRESS) {
		DEBUGMSG("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON PRESSED AT: %d,%d", inputevent->posx, inputevent->posy);
		MSG2OUT("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON PRESSED AT: %d,%d", inputevent->posx, inputevent->posy);
		struct timespec ts;
		clock_gettime(CLOCK_REALTIME,&ts);
		clock_gettime(CLOCK_REALTIME,&this->lastinput);

		this->button_pressed = true;
		this->windowmanager->setPointerPosition(inputevent->posx, inputevent->posy, true);

		this->oldx = inputevent->posx;
		this->oldy = inputevent->posy;
		window = this->windowmanager->getToplevelWindow();
		if (window) {
			/* get the window rect and check if the pointer is in there */
			MMSFBRectangle rect = window->getGeometry();

			if ((inputevent->posx - rect.x < 0)||(inputevent->posy - rect.y < 0)
					||(inputevent->posx - rect.x - rect.w >= 0)||(inputevent->posy - rect.y - rect.h >= 0)) {
				/* pointer is not over the window */
				DEBUGMSG("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON PRESSED, NOT OVER THE WINDOW");
				MSG2OUT("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON PRESSED, NOT OVER THE WINDOW");

				mmsfb->unlock();
				this->mutex.unlock();
				memset(inputevent, 0, sizeof(MMSInputEvent));
				return;
			}
			if(inputevent->posx < 0 || inputevent->posy<0) {
				inputevent->absx = this->oldx;
				inputevent->absy = this->oldy;
			} else {
				this->oldx = inputevent->posx;
				this->oldy = inputevent->posy;
			}


			// save the pointer for release event
			this->buttonpress_window = window;

			inputevent->absx = inputevent->posx;
			inputevent->absy = inputevent->posy;
			inputevent->posx-= rect.x;
			inputevent->posy-= rect.y;
			inputevent->dx = 0;
			inputevent->dy = 0;

			window->handleInput(inputevent);
			memset(inputevent, 0, sizeof(MMSInputEvent));
		}
	}
	else
	if (inputevent->type == MMSINPUTEVENTTYPE_BUTTONRELEASE) {
		DEBUGMSG("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON RELEASED AT: %d,%d", inputevent->posx, inputevent->posy);
//		MSG2OUT("MMSINPUTMANAGER", "MMSInputManager:handleInput: BUTTON RELEASED AT: %d,%d", inputevent->posx, inputevent->posy);
		this->button_pressed = false;

		this->windowmanager->setPointerPosition(inputevent->posx, inputevent->posy, false);

		window = this->windowmanager->getToplevelWindow();
		if (!window)
			window = this->buttonpress_window;
		if (window) {
			/* get the window rect and check if the pointer is in there */
			MMSFBRectangle rect = window->getGeometry();

			if ((window == this->buttonpress_window)
				||   ((this->buttonpress_window)
					&&(inputevent->posx - rect.x >= 0)&&(inputevent->posy - rect.y >= 0)
					&& (inputevent->posx - rect.x - rect.w < 0)&&(inputevent->posy - rect.y - rect.h < 0))) {
				/* call windows handleInput with normalized coordinates */

				if(inputevent->posx < 0 || inputevent->posy<0) {
					inputevent->absx = this->oldx;
					inputevent->absy = this->oldy;
				}
				inputevent->absx = inputevent->posx;
				inputevent->absy = inputevent->posy;
				inputevent->posx-= rect.x;
				inputevent->posy-= rect.y;
				inputevent->dx = inputevent->absx - this->oldx;
				inputevent->dy = inputevent->absy - this->oldy;

				this->oldx = -1;
				this->oldy = -1;

				if (window->handleInput(inputevent)) {
					this->buttonpress_window = NULL;
					memset(inputevent, 0, sizeof(MMSInputEvent));
					mmsfb->unlock();
					this->mutex.unlock();
					return;
				}
			}
		}
		this->buttonpress_window = NULL;


		// have to call subscriptions?
		bool call_subscriptions = true;
		if (window) {
			bool modal = false;
			window->getModal(modal);
			if (modal)
				call_subscriptions = false;
		}

		if (call_subscriptions) {
			// go through subscriptions
			for(unsigned int i = 0; i < subscriptions.size();i++) {
				MMSFBRectangle pointer_area;
				if (subscriptions.at(i)->getPointerArea(pointer_area)) {
					if ((inputevent->posx >= pointer_area.x)&&(inputevent->posy >= pointer_area.y)
					  &&(inputevent->posx < pointer_area.x + pointer_area.w)&&(inputevent->posy < pointer_area.y + pointer_area.h)) {
						DEBUGMSG("MMSINPUTMANAGER", "found a subscription");
						// ok i found one execute
						subscriptions.at(i)->callback.emit(subscriptions.at(i));
						// stop it only one key per subscription
						DEBUGMSG("MMSINPUTMANAGER", "returning from handle input");
						memset(inputevent, 0, sizeof(MMSInputEvent));
						mmsfb->unlock();
						this->mutex.unlock();
						return;
					}
				}
			}
		}

	}
	else
	if (inputevent->type == MMSINPUTEVENTTYPE_AXISMOTION) {

		/*this->oldx = inputevent->absx;
		this->oldy = inputevent->absy;
		memset(inputevent, 0, sizeof(MMSInputEvent));
		return;
		*/

		/* */
		this->windowmanager->setPointerPosition(inputevent->posx, inputevent->posy, this->button_pressed);


		window = this->windowmanager->getToplevelWindow();
		if (window) {
			/* get the window rect and check if the pointer is in there */
			MMSFBRectangle rect = window->getGeometry();

			if ((inputevent->posx - rect.x < 0)||(inputevent->posy - rect.y < 0)
					||(inputevent->posx - rect.x - rect.w >= 0)||(inputevent->posy - rect.y - rect.h >= 0)) {
				/* pointer is not over the window */
				mmsfb->unlock();
				this->mutex.unlock();
				return;
			}

			inputevent->absx = inputevent->posx;
			inputevent->absy = inputevent->posy;
			inputevent->posx-=rect.x;
			inputevent->posy-=rect.y;
			if(this->button_pressed) {
				inputevent->dx = inputevent->absx - this->oldx;
				inputevent->dy = inputevent->absy - this->oldy;
			} else {
				inputevent->dx = 0;
				inputevent->dy = 0;
			}

			if(this->oldx == inputevent->absx && this->oldy == inputevent->absy) {

				memset(inputevent, 0, sizeof(MMSInputEvent));
				mmsfb->unlock();
				this->mutex.unlock();
				return;
			}
			//printf("oldx = %d\n", this->oldx);
			fflush(stdout);
			this->oldx = inputevent->absx;
			this->oldy = inputevent->absy;


			window->handleInput(inputevent);
			memset(inputevent, 0, sizeof(MMSInputEvent));
		}
	}

	mmsfb->unlock();
	this->mutex.unlock();
}
Esempio n. 22
0
void parseCmd(const char **strptr)
{
	// Parse Executable Filename
	char exe[MAX_CMD_SIZE + 1] = "";
	char path[MAX_CMD_SIZE + 1] = "";
	bool exeValid;

	PARSE_ASSERT(getToken(exe, strptr) == IDENTIFIER);
	exeValid = getPath(path, exe);
	if (!exeValid) {
		char msg[MAX_CMD_SIZE + 30];

		sprintf(msg, "Unknown command: [%s].", exe);
		throw std::string(msg);
	}
	

	// Parse Arguments
	int num_arg = 0;
	char *arg[16];
	while (peekToken(*strptr) == IDENTIFIER) {
		arg[num_arg] = new char[MAX_CMD_SIZE + 1];
		getToken(arg[num_arg++], strptr);
	}

	// Parse Pipe to File
	bool pipeToFile = false;
	char file[MAX_CMD_SIZE + 1];
	if (peekToken(*strptr) == OUT) {
		pipeToFile = true;
		getToken(NULL, strptr);	// '>'
		PARSE_ASSERT(getToken(file, strptr) == IDENTIFIER);
	}

	// Parse Pipe
	bool pipe = false;
	bool pipenum = false;
	int pipenumCount;
	if (peekToken(*strptr) == PIPE) {
		getToken(NULL, strptr); // '|'
		
		/*
		// Test whether this is the last process
		char nextCmdName[MAX_CMD_SIZE + 1];
		Token token;
		char temp[MAX_CMD_SIZE + 1];
		token = peekToken(*strptr, nextCmdName);
		if (token == END || 
			token == IDENTIFIER && !getPath(temp, nextCmdName))
		{
			// Consider '|' as '|1'
			pipenum = true;
			pipenumCount = 1;
		}
		else {
		*/
			pipe = true;
		//}
	}

	// Parse Pipenum 
	if (peekToken(*strptr) == PIPENUM) {
		char temp[MAX_CMD_SIZE + 1];
		pipenum = true;
		getToken(temp, strptr); // '|?'
		pipenumCount = atoi(temp + 1);
	}

	// Parse Pipeerrnum
	bool pipeerrnum = false;
	int pipeerrnumCount;
	if (peekToken(*strptr) == PIPEERRNUM) {
		char temp[MAX_CMD_SIZE + 1];
		pipeerrnum = true;
		getToken(temp, strptr); // '!?'
		pipeerrnumCount = atoi(temp + 1);	
	}

	// Parse Pipenum again if !? exists
	if (!pipenum && pipeerrnum) {
		if (peekToken(*strptr) == PIPENUM) {
			char temp[MAX_CMD_SIZE + 1];
			pipenum = true;
			getToken(temp, strptr); // '|?'
			pipeerrnumCount = atoi(temp + 1);
		}
	}

	// Some assertions
	PARSE_ASSERT(pipeToFile + pipe + pipenum <= 1); // No multiple outputs

	// Execute
	executeCmd(exe, path, num_arg, (const char **)arg, pipeToFile, file, pipe, 
		pipenum, pipenumCount, pipeerrnum, pipeerrnumCount);

	// Release Argument List
	for (int i = 0; i < num_arg; i++) {
		delete [] arg[i];
	}
}
Esempio n. 23
0
//
// Selects objects within the user defined area, then process them
// 
MStatus meshRemapTool::doRelease( MEvent & event )
{
	char buf[1024];

	// Perform the base actions
	MStatus stat = MPxSelectionContext::doRelease(event);

	// Get the list of selected items 
	MGlobal::getActiveSelectionList( fSelectionList );

	//
	//  Get the selection's details, we must have exactly one component selected
	//
	MObject component;
	MDagPath path;

	MItSelectionList selectionIt (fSelectionList, MFn::kComponent);

	MStringArray	selections;
	selectionIt.getStrings( selections );
	
	// There are valid cases where only the meshes are selected.
	if( selections.length() == 0 )
	{
		// Handling the case where the user's workflow is
		// 1) select src mesh, select vtx1, vtx2, vtx3 (i.e. fNumSelectedPoints == 0)
		// 2) select dst mesh, select vtx1, vtx2, vtx3 (i.e. fNumSelectedPoints == 3)
		if( fNumSelectedPoints == 0 || fNumSelectedPoints == 3 )
		{
			MItSelectionList selectionDag (fSelectionList, MFn::kDagNode);
			if (!selectionDag.isDone() && selectionDag.getDagPath(path) == MS::kSuccess)
			{
				path.extendToShape();
				// return true there is exactly one mesh selected
				if (path.hasFn(MFn::kMesh))
				{
					selectionDag.next();
					if (selectionDag.isDone())
					{
						//	If this is the destination mesh, make sure that
						//	it doesn't have history.
						if (fNumSelectedPoints == 3)
						{
							return checkForHistory(path);
						}

						return MS::kSuccess;
					}
				}
			}
		}

		// Handling the case where the user is doing the auto remap, i.e.
		// select src mesh, and then dst mesh when fNumSelectedPoints == 0.
		if( fNumSelectedPoints == 0 )
		{
			MItSelectionList selectionDag (fSelectionList, MFn::kDagNode);
			if (!selectionDag.isDone() && selectionDag.getDagPath(path) == MS::kSuccess)
			{
				path.extendToShape();
				// Confirm first selection is a mesh
				if (path.hasFn(MFn::kMesh))
				{
					selectionDag.next();
					if (!selectionDag.isDone() &&
					    selectionDag.getDagPath(path) == MS::kSuccess)
					{
						path.extendToShape();
						// Confirm second selection is a mesh
						if (path.hasFn(MFn::kMesh))
						{
							selectionDag.next();
							// Confirm there are exactly 2 selections
							if (selectionDag.isDone())
							{
								//	Make sure that the destination mesh
								//	doesn't have history.
								return checkForHistory(path);
							}
						}
					}
				}
			}
		}
	}

	if( selections.length() != 1 )
	{
		MGlobal::displayError( "Must select exactly one vertex" );
		return MS::kSuccess;
	}

	if (selectionIt.isDone ())
	{
		MGlobal::displayError( "Selected item not a vertex" );
		return MS::kSuccess;
	}

	if( selectionIt.getDagPath (path, component) != MStatus::kSuccess )
	{
		MGlobal::displayError( "Must select a mesh or its vertex" );
		return MS::kSuccess;
	}

	if (!path.node().hasFn(MFn::kMesh) && !(path.node().hasFn(MFn::kTransform) && path.hasFn(MFn::kMesh)))
	{
		MGlobal::displayError( "Must select a mesh or its transform" );
		return MS::kSuccess;
	}

	//	If this is the first vertex of the destination mesh, make sure that
	//	it doesn't have history.
	if ((fNumSelectedPoints == 3) && (checkForHistory(path) != MS::kSuccess))
	{
		return MS::kSuccess;
	}

	MItMeshVertex fIt ( path, component, &stat );
	if( stat != MStatus::kSuccess )
	{
		MGlobal::displayError( "MItMeshVertex failed");
		return MStatus::kFailure;
	}

	if (fIt.count() != 1 )
	{
		sprintf(buf, "Invalid selection '%s'. Vertices must be picked one at a time.", selections[0].asChar() );
		MGlobal::displayError( buf );
		return MS::kSuccess;
	}
	else
	{
		sprintf(buf, "Accepting vertex '%s'", selections[0].asChar() );
		MGlobal::displayInfo(  buf );
	}

	//
	// Now that we know it's valid, process the selection, the first 3 items are the source, the second
	// 3 define the target
	//

	if( fNumSelectedPoints < 3 )
	{
		fSelectedPathSrc.append( path );
		fSelectedComponentSrc.append( component );
	}
	else 
	{
		fSelectedPathDst.append( path );
		fSelectedComponentDst.append( component );
	}

	//
	//  When each of the source/target are defined, process them. An error/invalid selection will restart the selection for
	//  that particular mesh.
	//  
	if( fNumSelectedPoints == 2 )
	{
		if( ( stat = meshMapUtils::validateFaceSelection( fSelectedPathSrc, fSelectedComponentSrc, &fSelectedFaceSrc, &fSelectVtxSrc ) ) != MStatus::kSuccess )
		{
			MGlobal::displayError("Selected vertices don't define a unique face on source mesh");
			reset();
			return stat;
		}
	}

	//
	// Once the target is defined, invoke the command
	//
	if( fNumSelectedPoints == 5 )
	{
		if( ( stat = meshMapUtils::validateFaceSelection( fSelectedPathDst, fSelectedComponentDst, &fSelectedFaceDst, &fSelectVtxDst ) ) != MStatus::kSuccess )
		{
			MGlobal::displayError("Selected vertices don't define a unique face on destination mesh");
			reset();
			return stat;
		}

		executeCmd();
	}
	else
	{
		//
		// We don't have all the details yet, just move to the next item
		//
		fNumSelectedPoints++;	
	}

	helpStateHasChanged();

	return stat;
}
Esempio n. 24
0
bool Entry::onProcessMessage(Message* msg)
{
  switch (msg->type()) {

    case kTimerMessage:
      if (hasFocus() && static_cast<TimerMessage*>(msg)->timer() == &m_timer) {
        // Blinking caret
        m_state = m_state ? false: true;
        invalidate();
      }
      break;

    case kFocusEnterMessage:
      if (shouldStartTimer(true))
        m_timer.start();

      m_state = true;
      invalidate();

      if (m_lock_selection) {
        m_lock_selection = false;
      }
      else {
        selectAllText();
        m_recent_focused = true;
      }

      // Start processing dead keys
      if (m_translate_dead_keys)
        os::instance()->setTranslateDeadKeys(true);
      break;

    case kFocusLeaveMessage:
      invalidate();

      m_timer.stop();

      if (!m_lock_selection)
        deselectText();

      m_recent_focused = false;

      // Stop processing dead keys
      if (m_translate_dead_keys)
        os::instance()->setTranslateDeadKeys(false);
      break;

    case kKeyDownMessage:
      if (hasFocus() && !isReadOnly()) {
        // Command to execute
        EntryCmd cmd = EntryCmd::NoOp;
        KeyMessage* keymsg = static_cast<KeyMessage*>(msg);
        KeyScancode scancode = keymsg->scancode();

        switch (scancode) {

          case kKeyLeft:
            if (msg->ctrlPressed() || msg->altPressed())
              cmd = EntryCmd::BackwardWord;
            else if (msg->cmdPressed())
              cmd = EntryCmd::BeginningOfLine;
            else
              cmd = EntryCmd::BackwardChar;
            break;

          case kKeyRight:
            if (msg->ctrlPressed() || msg->altPressed())
              cmd = EntryCmd::ForwardWord;
            else if (msg->cmdPressed())
              cmd = EntryCmd::EndOfLine;
            else
              cmd = EntryCmd::ForwardChar;
            break;

          case kKeyHome:
            cmd = EntryCmd::BeginningOfLine;
            break;

          case kKeyEnd:
            cmd = EntryCmd::EndOfLine;
            break;

          case kKeyDel:
            if (msg->shiftPressed())
              cmd = EntryCmd::Cut;
            else if (msg->ctrlPressed())
              cmd = EntryCmd::DeleteForwardToEndOfLine;
            else
              cmd = EntryCmd::DeleteForward;
            break;

          case kKeyInsert:
            if (msg->shiftPressed())
              cmd = EntryCmd::Paste;
            else if (msg->ctrlPressed())
              cmd = EntryCmd::Copy;
            break;

          case kKeyBackspace:
            if (msg->ctrlPressed())
              cmd = EntryCmd::DeleteBackwardWord;
            else
              cmd = EntryCmd::DeleteBackward;
            break;

          default:
            // Map common macOS/Windows shortcuts for Cut/Copy/Paste/Select all
#if defined __APPLE__
            if (msg->onlyCmdPressed())
#else
            if (msg->onlyCtrlPressed())
#endif
            {
              switch (scancode) {
                case kKeyX: cmd = EntryCmd::Cut; break;
                case kKeyC: cmd = EntryCmd::Copy; break;
                case kKeyV: cmd = EntryCmd::Paste; break;
                case kKeyA: cmd = EntryCmd::SelectAll; break;
              }
            }
            break;
        }

        if (cmd == EntryCmd::NoOp) {
          if (keymsg->unicodeChar() >= 32) {
            executeCmd(EntryCmd::InsertChar, keymsg->unicodeChar(),
                       (msg->shiftPressed()) ? true: false);

            // Select dead-key
            if (keymsg->isDeadKey()) {
              if (lastCaretPos() < m_maxsize)
                selectText(m_caret-1, m_caret);
            }
            return true;
          }
          // Consume all key down of modifiers only, e.g. so the user
          // can press first "Ctrl" key, and then "Ctrl+C"
          // combination.
          else if (keymsg->scancode() >= kKeyFirstModifierScancode) {
            return true;
          }
          else {
            break;              // Propagate to manager
          }
        }

        executeCmd(cmd, keymsg->unicodeChar(),
                   (msg->shiftPressed()) ? true: false);
        return true;
      }
      break;

    case kMouseDownMessage:
      captureMouse();

    case kMouseMoveMessage:
      if (hasCapture()) {
        bool is_dirty = false;
        int c = getCaretFromMouse(static_cast<MouseMessage*>(msg));

        if (static_cast<MouseMessage*>(msg)->left() || !isPosInSelection(c)) {
          // Move caret
          if (m_caret != c) {
            setCaretPos(c);
            is_dirty = true;
            invalidate();
          }

          // Move selection
          if (m_recent_focused) {
            m_recent_focused = false;
            m_select = m_caret;
          }
          else if (msg->type() == kMouseDownMessage)
            m_select = m_caret;
        }

        // Show the caret
        if (is_dirty) {
          if (shouldStartTimer(true))
            m_timer.start();
          m_state = true;
        }

        return true;
      }
      break;

    case kMouseUpMessage:
      if (hasCapture()) {
        releaseMouse();

        MouseMessage* mouseMsg = static_cast<MouseMessage*>(msg);
        if (mouseMsg->right()) {
          // This flag is disabled in kFocusEnterMessage message handler.
          m_lock_selection = true;

          showEditPopupMenu(mouseMsg->position());
          requestFocus();
        }
      }
      return true;

    case kDoubleClickMessage:
      forwardWord();
      m_select = m_caret;
      backwardWord();
      invalidate();
      return true;

    case kMouseEnterMessage:
    case kMouseLeaveMessage:
      // TODO theme stuff
      if (isEnabled())
        invalidate();
      break;
  }

  return Widget::onProcessMessage(msg);
}
Esempio n. 25
0
static int handle_xml_cmd(int sock, char *data, int len)
{
	int   out_fields[RESP_FIELD_MAX + 1];
	void *out_params[RESP_FIELD_MAX + 1];
	int   in_fields[CMD_FIELD_MAX + 1];
	void *in_params[CMD_FIELD_MAX];

	int ret;
	char *resp_buf = NULL;
	struct node_info info = {
		.cmd = -1,
		.timeout = DEF_TIMEOUT,
		.debug = 0
	};

	INFO("recv cmd: %s", data);

	memset(in_fields, 0, sizeof(in_fields));
	memset(in_params, 0, sizeof(in_params));
	memset(out_fields, 0, sizeof(out_fields));
	memset(out_params, 0, sizeof(out_params));

	if (parseXmlContent(data, len, in_fields, in_params, &info)) {
		ERROR("xml parsing error.");
		return -1;
	}

	if (!info.debug) {
		/* DEBUG("alarm %d", info.timeout); */
		alarm(info.timeout);
	}
	ret = executeCmd(info.cmd, in_fields, in_params, out_fields, out_params);
	freeParams(in_fields, in_params);

	if (ret)
		ERROR("cmd %s failed: %s", cmd_name[info.cmd], strerror(ret));

	ret = createXmlResult(info.cmd, ret, out_fields, out_params, &resp_buf);
	freeParams(out_fields, out_params);

	if (!info.debug)
		alarm(0);

	if (ret || !resp_buf) {
		ERROR("create result string error.");
		return -1;
	}

	ret = send_resp(sock, resp_buf, strlen(resp_buf));
	free(resp_buf);

	return ret;
}

static void handle_request(int sock)
{
	int command, ret = 0;
	char *buffer = malloc(MAX_CMD_BUF + 1);

	if (!buffer) {
		ERROR("malloc error : %s", strerror(errno));
		return;
	}

	while (ret == 0) {

		ret = receive_cmd(sock, buffer, MAX_CMD_BUF, &command);
		//DEBUG("received cmd %d len %d", command, ret);

		if (ret == 0) {
			ERROR("Socket closed");
			break;
		}

		if (ret > 0 && command != CMD_XML) {
			ERROR("Not supported command %d", command);
			ret = INVALID_DATA;
		}

		if (ret < 0) {
			sprintf(buffer, resp_xml, status_str[-ret]);
			send_resp(sock, buffer, strlen(buffer));
			break;
		}

		ret = handle_xml_cmd(sock, buffer, ret /* len */);
		if (ret < 0) {
			ERROR("xml command %d error %d", command, ret);
			break;
		}
	}
	free(buffer);
}
Esempio n. 26
0
//MAIN
int main() {
    
   signal(SIGINT, sighandler);
    
    char cmd[MAX_COMMAND_LENGTH + 1];
    char histar[10][MAX_COMMAND_LENGTH + 1];
    char hischar[MAX_COMMAND_LENGTH + 1];
    
    int a = 0;
    int piped =0;
    int redirin = 0;
    int redirout = 0;
    int hiscount = 0;
    

    while(1) {
        
        char* params[MAX_NUMBER_OF_PARAMS + 1];
       
        printf("azarifog> ");
        

        // Read command from standard input
        if(fgets(cmd, sizeof(cmd), stdin) == NULL) break;
        
        // Remove trailing newline character, if any
        if(cmd[strlen(cmd)-1] == '\n') {
            cmd[strlen(cmd)-1] = '\0';
        }
        
        //Copy the input for history to save later..
        strncpy(hischar, cmd, MAX_COMMAND_LENGTH + 1);

        // Split cmd into array of parameters
        int n = parseCmd(cmd, params);
        
        // If exit is entered
        if(strcmp(params[0], "exit") == 0) break;
        
        //History
        if(strcmp(params[0], "history") == 0){
            int count_num = 1;
            if(hiscount < 10) count_num = hiscount;
            else count_num = 10;
            
            for(int h = 0 ; h < count_num; h++){
                printf("%s\n" , histar[h]);
            }
            
            continue;
        }
        else {
            int hc = hiscount % 10;
            strcpy(histar[hc], hischar);
            //printf("Copying to index at %d: %s\n" ,hc, hischar);
            hiscount++;
        }
        
        
        //Check variables to find out if commands is pipe or redirect
        for(a = 0; a < n; a++){
            if(!strcmp(params[a], "|")){
                piped++;  //pipe command entered
                //printf("piped: %i", piped);
            }
            if(!strcmp(params[a], "<")){
                redirin++;  //redireted in command
                 //printf("redirin: %i", redirin);
            }
            if(!strcmp(params[a], ">")){
                redirout++; //redirected out command
                 //printf("redirout: %i", redirout);
            }
        }
        
        //If there is no need for pipe or redirection
        if(piped == 0 && redirin == 0 && redirout == 0){
            //printf("PARAM: %s\n", params[0]);
            if(executeCmd(params) == 0) break;
        }
        else{
            
            //If there is a need for pipe
            if(piped != 0 ){
                //Pipe function
                do_pipe(params, piped);
            }
            
            //If there is redirection
            else if(redirin == 1 || redirout == 1){
                
                int ic1 = 2;
                int ic2 = 4;
                
                for(int i=0;params[i]!='\0';i++)
                {
                    if(strcmp(params[i],"<")==0)
                    {
                        params[i]=NULL;
                        ic1 = i+1;
                    }
                    
                    else if(strcmp(params[i],">")==0)
                    {
                        params[i]=NULL;
                        ic2 = i+1;
                    }
                }
                
                
                // Fork process
                pid_t pid = fork();
                
                // Error
                if (pid == -1) {
                    char* error = strerror(errno);
                    printf("fork: %s\n", error);
                    return 1;
                }
                
                // Child process
                else if (pid == 0) {
                    
                    int in, out;
                    
                    int p = 0;
                    
                    char *args2[MAX_COMMAND_LENGTH + 1] = {};
                    
                    for(p =0; p < ic1; p++){
                        args2[p] = params [p];
                        //printf("%s" , args2[p]);
                    }
                    
                    args2[p] = NULL;
                    
                    
                    // Open input and output files
                    if(redirin == 1){
                       in = open(params[ic1], O_RDONLY);
                        
                        //Error handling if the file does not exist.
                        if(in == -1){
                            printf("The file does not exist: %s\n", params[ic1]);
                            piped = 0;
                            redirin = 0;
                            redirout = 0;
                            close(in);
                            break;
                        }
                        
                        // Replace standard input with input file
                        dup2(in, 0);
                        close(in);
                        
                        
                    }
                    if(redirout == 1){
                        out = open(params[ic2], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
                        
                        // replace standard output with output file
                        dup2(out, 1);
                        close(out);
                    }
                    
                    
                    // execute arguments
                    execvp(args2[0], args2);
                    
                    // Error occurred
                    char* error = strerror(errno);
                    printf("Error! azarifog: %s: %s\n", params[0], error);
                    
                }
                
                // Parent process
                else {
                    // Wait for child process to finish
                    int childStatus;
                    waitpid(pid, &childStatus, 0);
                    
                }

                
            } // redirect
            
            
            
        }
        //reset variables
        piped = 0;
        redirin = 0;
        redirout = 0;
        
        //For the signal handler testing
        //sleep(1);
        
    }
    
    return 0;
}
Esempio n. 27
0
bool Entry::onProcessMessage(Message* msg)
{
  switch (msg->type()) {

    case kTimerMessage:
      if (hasFocus() && static_cast<TimerMessage*>(msg)->timer() == &m_timer) {
        // Blinking caret
        m_state = m_state ? false: true;
        invalidate();
      }
      break;

    case kFocusEnterMessage:
      m_timer.start();

      m_state = true;
      invalidate();

      if (m_lock_selection) {
        m_lock_selection = false;
      }
      else {
        selectAllText();
        m_recent_focused = true;
      }
      break;

    case kFocusLeaveMessage:
      invalidate();

      m_timer.stop();

      if (!m_lock_selection)
        deselectText();

      m_recent_focused = false;
      break;

    case kKeyDownMessage:
      if (hasFocus() && !isReadOnly()) {
        // Command to execute
        EntryCmd cmd = EntryCmd::NoOp;
        KeyMessage* keymsg = static_cast<KeyMessage*>(msg);
        KeyScancode scancode = keymsg->scancode();

        switch (scancode) {

          case kKeyLeft:
            if (msg->ctrlPressed())
              cmd = EntryCmd::BackwardWord;
            else
              cmd = EntryCmd::BackwardChar;
            break;

          case kKeyRight:
            if (msg->ctrlPressed())
              cmd = EntryCmd::ForwardWord;
            else
              cmd = EntryCmd::ForwardChar;
            break;

          case kKeyHome:
            cmd = EntryCmd::BeginningOfLine;
            break;

          case kKeyEnd:
            cmd = EntryCmd::EndOfLine;
            break;

          case kKeyDel:
            if (msg->shiftPressed())
              cmd = EntryCmd::Cut;
            else
              cmd = EntryCmd::DeleteForward;
            break;

          case kKeyInsert:
            if (msg->shiftPressed())
              cmd = EntryCmd::Paste;
            else if (msg->ctrlPressed())
              cmd = EntryCmd::Copy;
            break;

          case kKeyBackspace:
            cmd = EntryCmd::DeleteBackward;
            break;

          default:
            // Map common Windows shortcuts for Cut/Copy/Paste
#if defined __APPLE__
            if (msg->onlyCmdPressed())
#else
            if (msg->onlyCtrlPressed())
#endif
            {
              switch (scancode) {
                case kKeyX: cmd = EntryCmd::Cut; break;
                case kKeyC: cmd = EntryCmd::Copy; break;
                case kKeyV: cmd = EntryCmd::Paste; break;
              }
            }
            else if (keymsg->unicodeChar() >= 32) {
              // Ctrl and Alt must be unpressed to insert a character
              // in the text-field.
              if ((msg->keyModifiers() & (kKeyCtrlModifier | kKeyAltModifier)) == 0) {
                cmd = EntryCmd::InsertChar;
              }
            }
            break;
        }

        if (cmd == EntryCmd::NoOp)
          break;

        executeCmd(cmd, keymsg->unicodeChar(),
                   (msg->shiftPressed()) ? true: false);
        return true;
      }
      break;

    case kMouseDownMessage:
      captureMouse();

    case kMouseMoveMessage:
      if (hasCapture()) {
        gfx::Point mousePos = static_cast<MouseMessage*>(msg)->position();
        base::utf8_const_iterator utf8_begin = base::utf8_const_iterator(getText().begin());
        base::utf8_const_iterator utf8_end = base::utf8_const_iterator(getText().end());
        int textlen = base::utf8_length(getText());
        int c, x;

        bool move = true;
        bool is_dirty = false;

        // Backward scroll
        if (mousePos.x < getBounds().x) {
          if (m_scroll > 0) {
            m_caret = --m_scroll;
            move = false;
            is_dirty = true;
            invalidate();
          }
        }
        // Forward scroll
        else if (mousePos.x >= getBounds().x2()) {
          if (m_scroll < textlen - getAvailableTextLength()) {
            m_scroll++;
            x = getBounds().x + this->border_width.l;
            for (c=m_scroll; utf8_begin != utf8_end; ++c) {
              int ch = (c < textlen ? *(utf8_begin+c) : ' ');

              x += getFont()->charWidth(ch);
              if (x > getBounds().x2()-this->border_width.r) {
                c--;
                break;
              }
            }
            m_caret = c;
            move = false;
            is_dirty = true;
            invalidate();
          }
        }

        c = getCaretFromMouse(static_cast<MouseMessage*>(msg));

        if (static_cast<MouseMessage*>(msg)->left() ||
            (move && !isPosInSelection(c))) {
          // Move caret
          if (move) {
            if (m_caret != c) {
              m_caret = c;
              is_dirty = true;
              invalidate();
            }
          }

          // Move selection
          if (m_recent_focused) {
            m_recent_focused = false;
            m_select = m_caret;
          }
          else if (msg->type() == kMouseDownMessage)
            m_select = m_caret;
        }

        // Show the caret
        if (is_dirty) {
          m_timer.start();
          m_state = true;
        }

        return true;
      }
      break;

    case kMouseUpMessage:
      if (hasCapture()) {
        releaseMouse();

        MouseMessage* mouseMsg = static_cast<MouseMessage*>(msg);
        if (mouseMsg->right()) {
          // This flag is disabled in kFocusEnterMessage message handler.
          m_lock_selection = true;

          showEditPopupMenu(mouseMsg->position());
          requestFocus();
        }
      }
      return true;

    case kDoubleClickMessage:
      forwardWord();
      m_select = m_caret;
      backwardWord();
      invalidate();
      return true;

    case kMouseEnterMessage:
    case kMouseLeaveMessage:
      // TODO theme stuff
      if (isEnabled())
        invalidate();
      break;
  }

  return Widget::onProcessMessage(msg);
}
Esempio n. 28
0
File: core.c Progetto: vojtsek/FTP
// function running in separate thread, handling data connection
int controlRoutine(struct control_info *info) {
	int fd = info->fd;
	struct cmd command;
	time_t now = time(NULL);
	struct state cstate = (struct state) { .logged = 0,
		.path = "/",
		.data_port = info->configuration->data_port,
		.transfer_count = 0,
		.data_sock = 0,
		.control_sock = 0,
		.port = 1,
		.last_accepted = 0,
		.addr_family = 1,
		.data_thread = 0,
		.transfer_type = Image,
		.client_addr = *(info->client_addr) };
	snprintf(cstate.dir, 32, "%d", (int)now);
	short abor = 0;
	if (isDir("/control_sockets") == -1)
		if (mkdir("/control_sockets", 0755) == -1) {
			perror("Failed to create control_sockets directory.");
			return (-1);
		}
	// reads commands from the accepted connection and executes it
	while (readCmd(fd, &command) != -1) {
		executeCmd(&command, &abor, fd, &cstate, info->configuration);
		freeCmd(&command);
		if (abor) break;
	}
	if (errno == EINTR)
		return (1);
	return (0);
}

// function running in separate thread, handles data connection
void *dataRoutine(void *arg) {
	struct data_info *info = (struct data_info *) arg;
	int sck;
	struct sockaddr_un sa;
	struct sockaddr_in in;
	bzero(&in, sizeof (in));
	bzero(&sa, sizeof (sa));
	struct state cstate = *(info->cstate);
	strncpy(sa.sun_path, info->control_sock, sizeof (sa.sun_path));
	sa.sun_family = AF_UNIX;

	// tries to create a connection
	// for communicating with the control thread
	if ((sck = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
		perror("Error creating control socket.");
		return (arg);
	}
	if (connect(sck, (struct sockaddr *) &sa, sizeof (sa)) == -1) {
		perror("Error connecting to control socket.");
		return (arg);
	}
	struct cmd command;
	cstate.data_sock = 0;
	// reads commands from control thread and executes them
	while (1) {
		// printf("Data socket: %d\n", cstate.data_sock);
		readUntil(command.name, sck, 0, 256);
		if (command.name[0] == 'Q') {
			break;
		}
		executeCmd(&command, NULL, sck, &cstate, info->configuration);
		// projects the changes to the control thread,
		info->cstate->data_sock = cstate.data_sock;
		info->cstate->last_accepted = cstate.last_accepted;
	}
	if (cstate.data_sock) {
		close(cstate.data_sock);
	}
	free(info);
	return (arg);
}