_Interchange_buffer::_Interchange_buffer(pixel_layout target_layout,
                                         alpha_mode target_alpha_mode,
                                         const std::byte *source_data,
                                         pixel_layout source_layout,
                                         alpha_mode source_alpha_mode,
                                         int source_width,
                                         int source_height,
                                         int source_stride)
{
    assert( source_data != 0 );
    assert( source_width >= 0 );
    assert( source_height >= 0 );
    assert( source_stride >= 0 );

    m_Layout = target_layout;
    m_Alpha = target_alpha_mode;
    m_Width = source_width;
    m_Height = source_height;
    m_Stride = DefaultStride(m_Width, m_Layout);
        
    if( source_width == 0 || source_height == 0 )
        return;
    
    if( source_stride == 0 )
        source_stride = DefaultStride(source_width, source_layout);

    m_Buffer = std::make_unique<byte[]>(m_Stride * m_Height);
    
    if( target_layout == source_layout && target_alpha_mode == source_alpha_mode )
        Copy( m_Buffer.get(), m_Stride, source_data, source_width, source_height, source_stride );
    else
        Interpret(m_Buffer.get(), m_Layout, m_Alpha, m_Stride, source_data, source_layout, source_alpha_mode, source_width, source_height, source_stride);        
}
Exemple #2
0
int main (int argc, char *argv[])
{
  /* Initialize command buffer */
  char* cmdLine = malloc(sizeof(char*)*BUFSIZE);

  /* shell initialization */
  if (signal(SIGINT, sig_handler) == SIG_ERR) PrintPError("SIGINT");
  if (signal(SIGTSTP, sig_handler) == SIG_ERR) PrintPError("SIGTSTP");

  while (!forceExit) /* repeat forever */
  {
    /* read command line */
    getCommandLine(&cmdLine, BUFSIZE);

    if(strcmp(cmdLine, "exit") == 0)
    {
      forceExit=TRUE;
      continue;
    }
    //printf("after exit\n");
    /* checks the status of background jobs */
    //if(strcmp(cmdLine, "jobs") != 0){
    CheckJobs();
      //printf("after checkjobs\n");
    //}
    /* interpret command and line
     * includes executing of commands */
    Interpret(cmdLine);

  }

  /* shell termination */
  free(cmdLine);
  return 0;
} /* end main */
Exemple #3
0
static void
Do_Enter_Interpreter (void)
{
  Interpret (0);
  outf_fatal ("\nThe interpreter returned to top level!\n");
  Microcode_Termination (TERM_EXIT);
}
Exemple #4
0
//*****************************************************************************
// Start Main
//*****************************************************************************
int main(void) {
	char data_in[128];

  //***************************************************************************
  // Setting the system Clock
  //
  // 400 MHz PLL driven by 16 MHz external crystal
  // builtin /2 from PLL, then /4 --> 50Hz Clock speed
	SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
  //
  //***************************************************************************

	InitUART3();
	MotorInit();		//Initialize Motors
	LineInit();			//Initialize Line Sensors
	ultrasonicInit();	//Initialize UltraSonic
	IRdsitinit();		//Initialize IR Distance Sensor
	colorinit();		//Initialize Color Sensor
	FollowINIT();		//Initialize timer interrupts for following
	ShaftEncoder_Init();
	IntMasterEnable();	//Enable Interrupts
	UARTprintf("An & Paolina's Robot says Hello\n\r");



	while (1) {
		UARTgets(data_in,128);
		MB_Get((unsigned char *)data_in);
		Interpret(data_in);

	}


}
Exemple #5
0
int ExecTree(Node *tree, int bg)
{
    //解析二叉树
    if(tree==NULL) return 1;
    if(tree->lchild==NULL && tree->rchild==NULL)
    {
        return Interpret(tree->data,-1,NULL,bg);
    }
    if(tree->data[0]=='&')
    {
        if(ExecTree(tree->lchild,1) && ExecTree(tree->rchild,0))
            return 1;
        else return 0;
    }
    if(tree->data[0]=='>')
    {
        return Interpret(tree->lchild->data,1,tree->rchild->data,bg);
    }
    else if(tree->data[0]=='<')
    {
        return Interpret(tree->lchild->data,0,tree->rchild->data,bg);
    }
    else if(tree->data[0]=='|')
    {
        int fds[2],pid;
        pipe(fds);
        pid=fork();
        if(pid>0) //父进程
        {
            int sfd=dup(STDIN_FILENO);  //先把标准输入保存下来
            dup2(fds[0],STDIN_FILENO);  //管道重定向到标准输入
            close(fds[1]);  close(fds[0]);
            ExecTree(tree->rchild,bg);
            waitpid(pid,NULL,0);
            dup2(sfd,STDIN_FILENO); //还原标准输入
        }
        else    //子进程
        {
            dup2(fds[1],STDOUT_FILENO); //管道重定向到标准输出
            close(fds[0]); close(fds[1]);
            ExecTree(tree->lchild,bg); //这里的bg情况暂时搞不清楚
            exit(0);
        }
    }
    return 1;
    
}
Exemple #6
0
static void amaproc(char path[])
{
  InitOptions(False, path);
  CreateInterpreter();
  for(;;)
  {
    char expr[stringsize] = "";
    getstring(">> ", expr);
    WriteString("\n<\n");
    Interpret(expr);
    WriteString("\n>\n");
  }
}
int _tmain(int argc, _TCHAR* argv[])
{
    auto nonterminal = std::make_shared<NonterminalExpression>();
    nonterminal->Add(std::make_shared<TerminalExpression>());
    nonterminal->Add(std::make_shared<TerminalExpression>());

    auto start = std::make_shared<NonterminalExpression>();
    start->Add(std::make_shared<TerminalExpression>());
    start->Add(nonterminal);

    start->Interpret(Context());
	
    return 0;
}
Exemple #8
0
/*
 * main
 *
 * arguments:
 *	 int argc: the number of arguments provided on the command line
 *	 char *argv[]: array of strings provided on the command line
 *
 * returns: int: 0 = OK, else error
 *
 * This sets up signal handling and implements the main loop of tsh.
 */
int main(int argc, char *argv[])
{
	/* Initialize command buffer */
	char* cmdLine = malloc(sizeof(char*) * BUFSIZE);

	/* shell initialization */
	if (signal(SIGINT, sig) == SIG_ERR)
		PrintPError("SIGINT");
	if (signal(SIGTSTP, sig) == SIG_ERR)
		PrintPError("SIGTSTP");

	while (!forceExit) /* repeat forever */ {
		char* prompt = getenv("PS1");
		if (prompt != NULL) {
			printf("%s", prompt);
		}
		
		/* read command line */
		getCommandLine(&cmdLine, BUFSIZE);

		if (strcmp(cmdLine, "exit") == 0)
			forceExit = TRUE;
		
		/* checks the status of background jobs */
		if (!forceExit) {
			CheckJobs();
		}

		/* interpret command and line
		 * includes executing of commands */
		Interpret(cmdLine);

	}

	bgjobL* curr = bgjobs;
	while (curr != NULL) {
		curr = bgjobs;
		int status;
		int res = waitpid(curr->pid, &status, WNOHANG | WUNTRACED | WCONTINUED);
		if (!(res == curr->pid && !WIFCONTINUED(status))) {
			kill(curr->pid, SIGKILL);
		}
		RemoveJob(curr->jid);
	}
	
	/* shell termination */
	free(cmdLine);
	return 0;
} /* main */
Exemple #9
0
int main (int argc, char *argv[])
{
  /* Initialize command buffer */
  char* cmdLine = malloc(sizeof(char*)*BUFSIZE);
  fgcommands = (char *) malloc(500 * sizeof(char));

  /* shell initialization */
  if (signal(SIGINT, sig) == SIG_ERR) PrintPError("SIGINT");
  if (signal(SIGTSTP, sig) == SIG_ERR) PrintPError("SIGTSTP");
  if (signal(SIGCHLD, sig) == SIG_ERR) PrintPError("SIGCHLD");

  // printPrompt();
 
     
  while (!forceExit) /* repeat forever */
  {
    //printPrompt();
    /* read command line */
    getCommandLine(&cmdLine, BUFSIZE);

    //cmdLine  = strdup(checkAlias2(cmdLine));

    //printf("The new is %s\n", cmdLine);
    if(strcmp(cmdLine, "exit") == 0 )
    {
      forceExit=TRUE;
      continue;
    }
    else if (feof(stdin)){
  //printf("\n");
  forceExit = TRUE;
        break;
  } 
    fgpid = 0;
    /* checks the status of background jobs */
    CheckJobs();

    /* interpret command and line
     * includes executing of commands */
    Interpret(cmdLine);
    //fflush(stdout);
    fgpid = 0;
  }

  /* shell termination */
  free(cmdLine);
  free(fgcommands);
  return 0;
} /* end main */
Exemple #10
0
int main (int argc, char *argv[])
{
    /* Initialize command buffer */
    char* cmdLine = malloc(sizeof(char*)*BUFSIZE);

    /* shell initialization */
    if (signal(SIGINT, sig_handler) == SIG_ERR) PrintPError("SIGINT");
    if (signal(SIGTSTP, sig_handler) == SIG_ERR) PrintPError("SIGTSTP");

    while (TRUE) /* repeat forever */
    {
        /* print prompt */
        printf("%%");
        //printf("my status: %d", waitpid(getpid(), &status, WNOHANG));
        //printf("%%");
        /* read command line */
        getCommandLine(&cmdLine, BUFSIZE);

        if(strcmp(cmdLine, "exit") == 0 || feof(stdin))
        {
            forceExit=TRUE;
            break;
        } else {
            // If we juse printf(cmdLine), compiler gives a warning because the cmdLine can contain things like  %s
            // and the program will try to find some string that does not exist. This could be exploited to run virus.
            //fprintf(stderr, "%s", cmdLine);
        }

        /* checks the status of background jobs */
        CheckJobs();

        /* interpret command and line
         * includes executing of commands */
        Interpret(cmdLine);
    }

    // make sure all the shell's child processes are terminated
    if (forceExit == TRUE) {
        while (bgjobs != NULL) {
            kill(bgjobs->pid, SIGINT);
            bgjobs = bgjobs->next;
        }
    }

    /* shell termination */
    free(cmdLine);
    return 0;
} /* end main */
Exemple #11
0
bool Load(const char *filename)
{
  static char fileName[stringsize] = "";
  if(filename) strncat(strcpy(fileName, ""), filename, stringsize-1);
  if(strlen(fileName) == 0)
    return False;
  else if(seterror()==0)
  {
    initstack();
    unlockmem();
    inithashtable();
    lockmem();
    initlex();
    initlib();
    initsyslib();
    initmodify();
    parsefile(inipath);
    parsefile(fileName);
    checkdefinitions();
    modify_definitions();
    lockmem();
    if (gettemplate("main")->tag == FUNC)
    {
      Interpret("main");
    }
    return True;
  }
  else
  {
    initstack();
    unlockmem();
    inithashtable();
    lockmem();
    initlex();
    initlib();
    initsyslib();
    initmodify();
    parsefile(inipath);
    checkdefinitions();
    modify_definitions();
    lockmem();
    return False;
  }
}
Exemple #12
0
/*
 * main
 *
 * arguments:
 *   int argc: the number of arguments provided on the command line
 *   char *argv[]: array of strings provided on the command line
 *
 * returns: int: 0 = OK, else error
 *
 * This sets up signal handling and implements the main loop of tsh.
 */
int
main(int argc, char *argv[])
{
  /* Initialize command buffer */
  char* cmdLine = malloc(sizeof(char*) * BUFSIZE);

  /* shell initialization */
  if (signal(SIGINT, sig) == SIG_ERR)
    PrintPError("SIGINT");
  if (signal(SIGTSTP, sig) == SIG_ERR)
    PrintPError("SIGTSTP");
    /* Terminated or stopped child */
  
  while (!forceExit) /* repeat forever */
    {
      /*Insert tsh$ prompt*/
      printPrompt();
      
      /* read command line */
      getCommandLine(&cmdLine, BUFSIZE);

      if (strcmp(cmdLine, "exit") == 0)
        forceExit = TRUE;
      
      /* checks the status of background jobs */
      if(!forceExit){
	CheckJobs();
	fflush(NULL);
      }
      /* interpret command and line
       * includes executing of commands */
      Interpret(cmdLine);
      fflush(NULL);
      //getPath();


    }

  /* shell termination */
  free(cmdLine);
  return 0;
} /* main */
Exemple #13
0
int main (int argc, char *argv[])
{
  /* Initialize command buffer */
  char* cmdLine = malloc(sizeof(char*)*BUFSIZE);

  /* shell initialization */
  if (signal(SIGINT, sig) == SIG_ERR) PrintPError("SIGINT");
  if (signal(SIGTSTP, sig) == SIG_ERR) PrintPError("SIGTSTP");
  if (signal(SIGCONT, sig) == SIG_ERR) PrintPError("SIGCONT");
  if (signal(SIGCHLD, sigHandler) == SIG_ERR) PrintPError("SIGCHLD");

  while (!forceExit) /* repeat forever */
  {
	printPrompt();
    /* read command line */
    getCommandLine(&cmdLine, BUFSIZE);

	// strcmp: string compare
    if(strcmp(cmdLine, "exit") == 0)
    {
      forceExit=TRUE;
      continue;
    }

    /* checks the status of background jobs */
    CheckJobs();

    /* interpret command and line
     * includes executing of commands */
    Interpret(cmdLine);

  }

  /* shell termination */
  free(cmdLine);
  releaseAlias(aliasList);
  /* print all lists and check 
  printf("\n\n ---------TERMINATE SHELL--------\n");
  printf("Alias:\n");
  printAlias();*/
  return 0;
} /* end main */
Exemple #14
0
/**************Implementation***********************************************/
void RunCmd(commandT** cmd, int n, int fd_in, int fd_out) {
  int i;
  int fd[2];
  fd[0] = fd_in;
  for (i = 0; i < n; i++) {
    cmd[i]->fd_in = fd[0];
    if (i != n-1) {
      if (pipe(fd) == -1) {
        perror("pipe error in RunCmd");
      }
      cmd[i]->fd_out = fd[1];
    } else {
      cmd[i]->fd_out = fd_out;
    }
    if (cmd[i]->argc > 0) {
      if (InterpretAlias(alist, cmd[i]->argv[0])) {
        int j;
        char* rcmd = NULL;
        char* realcmd = (char*)malloc(sizeof(char) * 1024);
        for (j = 0; j < cmd[i]->argc; j++) {
          rcmd = InterpretAlias(alist, cmd[i]->argv[j]);
          strcat(realcmd, " ");
          if (rcmd) {
            strcat(realcmd, rcmd);
          } else {
            strcat(realcmd, cmd[i]->argv[j]);
          }
        }
        int taskNum = 0;
        commandT** aliasCmd = Interpret(realcmd, &taskNum);
        RunCmd(aliasCmd, taskNum, cmd[i]->fd_in, cmd[i]->fd_out);
      } else if (IsBuiltIn(cmd[i]->argv[0])) {
        RunBuiltInCmd(cmd[i]);
      } else {
        RunExternalCmd(cmd[i], TRUE);
      }
    }
    ReleaseCmdT(&cmd[i]);
  }
  free(cmd);
}
Exemple #15
0
void main(int argc, char *argv[])
{
  initgetstring();
  if(argc > 1 && strcmp(argv[1], "-proc") == 0) 
  {
    amaproc(argv[0]);
    return;
  }
  if(argc > 2 && strcmp(argv[1], "-obj") == 0) 
  {
    amaobj(argv[0], argv[2]);
    return;
  }
  InitOptions(True, argv[0]);
  CreateInterpreter();
  if(argc > 1 && !Load(argv[1])) WriteString("\n");
  for(;;)
  {
    char expr[stringsize] = "";
    getstring(GetOption("ConPrompt"), expr);
    Interpret(expr);
  }
}
Exemple #16
0
void RunAlias(commandT* cmd){
  
  int i=1;
  char* commandLine = " ";
  aliasNode* current = aliasHead;
  
  
  while (current != NULL){
  	if (strcmp(cmd->argv[0],current->name)==0){
  		commandLine = current->cmdLine;
  	}
  	current = current->next;
  }
  
  while (cmd->argv[i] != NULL)
  {
  	
  	current = aliasHead;
  	
    while (current != NULL)
    {
      if (strcmp(cmd->argv[i],current->name)==0){
    		//append to command line to execute
    		strcat(commandLine, current->cmdLine);
        
      }
      current = current->next;
    }
    i++;
  }
  
  Interpret(commandLine);
  
  //it gets here when the interpreter has finished executing

}
Exemple #17
0
/**
 * Perform a strict interpretation from source code.
 */
Element Strine_::Interpret(std::istream& in)
{
    Element element = this->parser.Parse(in);
    element = ApplyOptimizations_(element);
    return Interpret(element);
}
Exemple #18
0
/**
 * Merely convert the program string into a stream and invoke the other 
 * interpret on it.
 */ 
strine::Element Strine_::Interpret(std::string const& program)
{
    std::stringstream ss;
    ss << program;
    return Interpret(ss);
}
Exemple #19
0
SCHEME_OBJECT
Re_Enter_Interpreter (void)
{
  Interpret (0);
  return (GET_VAL);
}
//bool secondRun stops the interpreter from recursing more than 1 level into itself
void Interpret(char* cmdLine,bool secondRun)
{
  int task = 1;
  int bg = 0, i,k,j = 0, quotation1 = 0, quotation2 = 0;
  commandT **command;

  if(cmdLine[0] == '\0') return;

  for(i = 0; i < strlen(cmdLine); i++){
    if(cmdLine[i] == '\''){
      if(quotation2) continue;
      else if(quotation1){
        quotation1 = 0;continue;
      }
      else quotation1 = 1;
    }
    if(cmdLine[i] == '"'){
      if(quotation1) continue;
      else if(quotation2){
        quotation2 = 0;continue;
      }
      else quotation2 = 1;
    }

    if(cmdLine[i] == '|' && quotation1 != 1 && quotation2 != 1){
      task ++;
    }
  }

  command = (commandT **) malloc(sizeof(commandT *) * task);
  i = strlen(cmdLine) - 1;
  while(i >= 0 && cmdLine[i] == ' ') i--;
  if(cmdLine[i] == '&'){
    if(i == 0) return;
    bg = 1;
    cmdLine[i] = '\0';
  }

  quotation1 = quotation2 = 0;
  task = 0;
  k = strlen(cmdLine);
  for(i = 0; i < k; i++, j++){
    if(cmdLine[i] == '\''){
      if(quotation2) continue;
      else if(quotation1){
        quotation1 = 0;continue;
      }
      else quotation1 = 1;
    }
    if(cmdLine[i] == '"'){
      if(quotation1) continue;
      else if(quotation2){
        quotation2 = 0;continue;
      }
      else quotation2 = 1;
    }
    if(cmdLine[i] == '|' && quotation1 != 1 && quotation2 != 1){
      parser_single(&(cmdLine[i-j]), j, &(command[task]),bg);
      task++;
      j = -1;
    }
  }
  parser_single(&(cmdLine[i-j]), j, &(command[task]),bg);

  //
  // TILDE EXPANSION
  //
  bool changed = FALSE;
  int idx =0;
    //look through all the args
  while(idx < command[0]->argc){
      //special case for "unalias x". ie dont expand x
    if(command[0]->argv[idx][0] == '~'){

      char* home = getenv("HOME");

          //get the part after the tilde and add it to home
      strcat(home,(command[0]->argv[idx])+2);
      command[0]->argv[idx] = home;
      changed = TRUE;

    }
    idx++;
  }




  //
  // ALIAS
  //


  //only expand aliases on the first run to stop aliases from recrusively expanding
  if(!secondRun){

    //look for aliases
    int idx =0;
    //look through all the args
    while(idx < command[0]->argc){
      //special case for "unalias x". ie dont expand x
      if(strcmp(command[0]->argv[0],"unalias") != 0) 
      {
        if(IsAlias(command[0]->argv[idx])){
          (command[0]->argv)[idx] = GetAliasCmd(command[0]->argv[idx]);
          changed = TRUE;
        //check for tilde expansion
        }
      }
      idx++;
    }

    //if we expanded something
    if(changed){

      int newSize = 0;//the new size of the expanded command line

      //figure out the new size
      int idx2 =0;
      while(idx2 < command[0]->argc){
        newSize = newSize + strlen(command[0]->argv[idx2]) + 1;
        idx2++;
      }

      //copy all ths args to a new cmdLine string
      char newCmdLine[newSize + 1];
      strcpy (newCmdLine, command[0]->argv[0]);

      int idx3 =1;
      while(idx3 < command[0]->argc){
        strcat(newCmdLine," ");//add space between args
        strcat(newCmdLine,command[0]->argv[idx3]);
        idx3++;
      }

      //rerun the interpreter
      Interpret(newCmdLine,TRUE);


    }
    else{
      RunCmd(command, task+1);
      free(command);
    }

  }else{
    RunCmd(command, task+1);
    free(command);
  }
}
Exemple #21
0
int CGCodeInterpreter::InvokeAction(int i, BOOL FlushBeforeUnbufferedOperation)
{
	MCODE_ACTION *p;
	char s[MAX_LINE];
	double value;
	int ivalue,ipersist;

	if (FlushBeforeUnbufferedOperation && CoordMotion->m_Simulate) return 0;

	// If we were called from a button and we had been previously aborted then clear the Abort and any Halt
	if (!FlushBeforeUnbufferedOperation && CoordMotion->GetAbort())
	{
		CoordMotion->ClearAbort();
		CoordMotion->ClearHalt();
	}
	
	if (i<MAX_MCODE_ACTIONS_M1+MAX_MCODE_ACTIONS_BUTTONS)
		p=&McodeActions[i];
	else if (i>=100)
		p=&McodeActions[i-100+MCODE_ACTIONS_M100_OFFSET];
	else
		p=&McodeActions[i-24+MCODE_ACTIONS_SPECIAL_OFFSET];

	switch (p->Action)
	{
	case M_Action_None:
		break;

	case M_Action_Setbit:
		if (FlushBeforeUnbufferedOperation)  // false for User button
		{
			sprintf(s, "SetStateBitBuf%d=%d",(int)p->dParams[0],(int)p->dParams[1]);
			if (CoordMotion->DoKMotionBufCmd(s,p_setup->sequence_number)) return 1;
		}
		else
		{
			sprintf(s, "SetStateBit%d=%d",(int)p->dParams[0],(int)p->dParams[1]);
			if (CoordMotion->DoKMotionCmd(s,FlushBeforeUnbufferedOperation)) return 1;
		}
		break;

	case M_Action_Waitbit:
		if (FlushBeforeUnbufferedOperation)  // false for User button (doesn't make sense for button)
		{
			if (p->dParams[1]==0)
				sprintf(s, "WaitNotBitBuf%d",(int)p->dParams[0]);
			else
				sprintf(s, "WaitBitBuf%d",(int)p->dParams[0]);

			if (CoordMotion->DoKMotionBufCmd(s)) return 1;
		}
		break;

	case M_Action_SetTwoBits:
		if (FlushBeforeUnbufferedOperation)  // false for User button
		{
			sprintf(s, "SetStateBitBuf%d=%d",(int)p->dParams[0],(int)p->dParams[1]);
			if (CoordMotion->DoKMotionBufCmd(s,p_setup->sequence_number)) return 1;
			sprintf(s, "SetStateBitBuf%d=%d",(int)p->dParams[2],(int)p->dParams[3]);
			if (CoordMotion->DoKMotionBufCmd(s,p_setup->sequence_number)) return 1;
		}
		else
		{
			sprintf(s, "SetStateBit%d=%d",(int)p->dParams[0],(int)p->dParams[1]);
			if (CoordMotion->DoKMotionCmd(s,FlushBeforeUnbufferedOperation)) return 1;
			sprintf(s, "SetStateBit%d=%d",(int)p->dParams[2],(int)p->dParams[3]);
			if (CoordMotion->DoKMotionCmd(s,FlushBeforeUnbufferedOperation)) return 1;
		}
		break;

	case M_Action_DAC:
		value = p_setup->speed * CoordMotion->GetSpindleRateOverride() * p->dParams[1] + p->dParams[2];   // scale and offset
		ivalue = (int)floor(value+0.5); 
		if (ivalue < (int)p->dParams[3]) ivalue = (int)p->dParams[3];
		if (ivalue > (int)p->dParams[4]) ivalue = (int)p->dParams[4];
		sprintf(s, "DAC%d=%d",(int)p->dParams[0],ivalue);
		if (CoordMotion->DoKMotionCmd(s,FlushBeforeUnbufferedOperation)) return 1;
		break;

	case M_Action_Program:
	case M_Action_Program_wait:
	case M_Action_Program_wait_sync:
		if (FlushBeforeUnbufferedOperation)
		{
			if (CoordMotion->FlushSegments()) {CoordMotion->SetAbort(); return 1;}  
			if (CoordMotion->WaitForSegmentsFinished()) {CoordMotion->SetAbort(); return 1;}
		}

		s[0] = '\0';
		if(strlen(p->String) >= 4){
			strcpy(s,p->String+ strlen(p->String) -4);
			_strlwr(s);
		}
		if(s[0] != '\0' && strcmp(s,".ngc")==0)
		{
			if (_setup.file_pointer!= NULL)
			{
				// A GCode file is currently running
				// don't allow the Interpreter to re-ener
				CoordMotion->KMotionDLL->DoErrMsg("Running a GCode file from a GCode file is not allowed.  Check if an MCode is assigned to a Gcode File and is also called from a GCode File");
				CoordMotion->SetAbort(); 
				return 1;
			}

			int BoardType=BOARD_TYPE_UNKNOWN;
			if (CoordMotion->m_Simulate==0)
				if (CoordMotion->KMotionDLL->CheckKMotionVersion(&BoardType)) return 1;

			InvokeInterpComplete=false;

			Interpret(BoardType,p->String,0,-1,false,InvokeStatusCallback,InvokeCompleteCallback);

			do
			{
				Sleep(10);
				if (CoordMotion->GetAbort()) return 1;
			}
			while (!InvokeInterpComplete);
		}
		else
		{
			ipersist = (int)p->dParams[1];
	
			// set a persist variable to either the Mcode value
			// or the related variable (normally speed)
			// if variable is -1 then don't set anything
	
			if (p->dParams[1] >= 0)
			{
				if (i==6)  // tool change
				{
					sprintf(s, "SetPersistHex %d %x",ipersist, p_setup->tool_table[p_setup->selected_tool_slot].slot);
					if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
					sprintf(s, "SetPersistHex %d %x",ipersist+1, p_setup->tool_table[p_setup->selected_tool_slot].id);
					if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
				}
				else if (i==10)  // set speed
				{
					float fspeed = (float)(p_setup->speed * CoordMotion->GetSpindleRateOverride());

					// if in CSS mode then S is not in RPM but rather in feet/min or meters/min
					// convert to standard units of inches/sec and download to KFLOP  
					if (p_setup->spindle_mode==CANON_SPINDLE_CSS)
					{
						if (p_setup->length_units == CANON_UNITS_MM)
							fspeed /= 60.0f * 0.0254f;
						else
							fspeed *= 12.0f/60.0f;
					}
					sprintf(s, "SetPersistHex %d %x",ipersist, *(int *)&fspeed);
					if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
				}
				else
				{
					int count=0;
					// for other M Codes check if P Q or R words are present on the same line
					// if so, download them into successive persist vars as floats
	
					if (p_setup->block1.p_flag)
					{
						float p = (float)p_setup->block1.p_number;
						sprintf(s, "SetPersistHex %d %x",ipersist, *(int *)&p);
						if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
						ipersist++;
						count++;
					}
	
					if (p_setup->block1.q_flag)
					{
						float q = (float)p_setup->block1.q_number;
						sprintf(s, "SetPersistHex %d %x",ipersist, *(int *)&q);
						if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
						ipersist++;
						count++;
					}
	
					if (p_setup->block1.r_flag)
					{
						float r = (float)p_setup->block1.r_number;
						sprintf(s, "SetPersistHex %d %x",ipersist, *(int *)&r);
						if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
						ipersist++;
						count++;
					}
	
					if (count==0)  // if no parameters just set the MCode number
					{
						sprintf(s, "SetPersistHex %d %x",ipersist,i);
						if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
					}
				}
			}
	
			// If a C File is specified then Compile and load it
	
			if (p->String[0])
			{
				char Err[500];
	
				if (CoordMotion->KMotionDLL->CompileAndLoadCoff(p->String, (int)p->dParams[0], Err, 499))
				{
					char message[1024];
					sprintf(message,"Error Compiling and Loading KMotion Program\r\r%s\r\r%s", p->String, Err );
					CoordMotion->KMotionDLL->DoErrMsg(message);
					return 1;
				}
			}
	
			// Now execute the thread!
	
			sprintf(s, "Execute%d",(int)p->dParams[0]);
			if (CoordMotion->KMotionDLL->WriteLine(s)) {CoordMotion->SetAbort(); return 1;}
	
			if (p->Action == M_Action_Program_wait || p->Action == M_Action_Program_wait_sync)
			{
				char response[MAX_LINE];
	
				int count=0;
	
				sprintf(s, "CheckThread%d",(int)p->dParams[0]);
				do
				{
					if (count++) Sleep(10);
					
					if (CoordMotion->KMotionDLL->WriteLineReadLine(s,response))
					{
						CoordMotion->SetAbort(); 
						return 1;
					}
	
					if (CoordMotion->GetAbort()) return 1;
				}
				while (strcmp(response,"0")!=0);
			}
	
			if (p->Action == M_Action_Program_wait_sync)
			{
				// don't sample positions until everything is stopped 
				if (CoordMotion->WaitForSegmentsFinished()) return 1;
				if (CoordMotion->WaitForMoveXYZABCFinished()) return 1;
	
				if (!CoordMotion->m_Simulate && ReadAndSyncCurPositions(&_setup.current_x,&_setup.current_y,&_setup.current_z,
					                                                               &_setup.AA_current,&_setup.BB_current,&_setup.CC_current))
				{
					if (CoordMotion->m_AxisDisabled)
					  strcpy(ErrorOutput,"Unable to read defined coordinate system axis positions - Axis Disabled ");
					else
					  strcpy(ErrorOutput,"Unable to read defined coordinate system axis positions ");
	
					return 1;
				}
			}
		}
		CoordMotion->RapidParamsDirty=true;
		break;

	case M_Action_Callback:
		if (GC->m_UserFnMCode)
		{
			if (CoordMotion->FlushSegments()) {CoordMotion->SetAbort(); return 1;}  
			if (CoordMotion->WaitForSegmentsFinished(TRUE)) {CoordMotion->SetAbort(); return 1;}
			
			// call back to the User Application and pass the MCode that caused the callback
			if (GC->m_UserFnMCode(i)){CoordMotion->SetAbort(); return 1;}

			// don't sample positions until everything is stopped 
			if (CoordMotion->WaitForSegmentsFinished()) return 1;
			if (CoordMotion->WaitForMoveXYZABCFinished()) return 1;

			if (!CoordMotion->m_Simulate && ReadAndSyncCurPositions(&_setup.current_x,&_setup.current_y,&_setup.current_z,
															   &_setup.AA_current,&_setup.BB_current,&_setup.CC_current))
				return 1;
		}
		break;

	case M_Action_Program_PC:
		// If running from GCode finish any motion first
		if (FlushBeforeUnbufferedOperation)
		{
			if (CoordMotion->FlushSegments()) {CoordMotion->SetAbort(); return 1;}  
			if (CoordMotion->WaitForSegmentsFinished(TRUE)) {CoordMotion->SetAbort(); return 1;}
		}

		// we will be executing a PC Program pass any related parameters
		//s="";
		s[0]='\0';
		char s0[32];
		if (i==6)  // tool change
		{
			sprintf(s, " %d",p_setup->selected_tool_slot);
		}
		else if (i==10)  // set speed
		{
			float fspeed = (float)(p_setup->speed * CoordMotion->GetSpindleRateOverride());
			sprintf(s, " %f",fspeed);
		}
		else
		{
			// for other M Codes check if P Q or R words are present on the same line
			// if so, download them into successive persist vars as floats

			if (p_setup->block1.p_flag)
			{
				sprintf(s0, " %f", p_setup->block1.p_number);
				strcat(s,s0);
			}

			if (p_setup->block1.q_flag)
			{
				sprintf(s0, " %f", p_setup->block1.q_number);
				strcat(s,s0);
			}

			if (p_setup->block1.r_flag)
			{
				sprintf(s0, " %f", p_setup->block1.r_number);
				strcat(s,s0);
			}
		}
		char pcCmd[MAX_LINE];
		sprintf(pcCmd,"%s%s",p->String,s);
		int result = ExecutePC(pcCmd);  // call the executable with parameters
		if (result)
		{
			char Err[350];

			sprintf(Err,"Error Executing PC Program:\r\r%s\r\r"
				"Return code = %d\r\rAbort?",p->String,result);

			if (AfxMessageBox(Err,MB_YESNO)==IDYES) Abort();
		};

		break;
	}

	// if not called from a button check for Halt
	if (FlushBeforeUnbufferedOperation && CoordMotion->CheckMotionHalt(true)) return 2;

	return 0;
}
Exemple #22
0
IMachine *VirtualBoxBridge::newVM(QString qName)
{
	nsresult rc = NS_OK;

	bool import_done = false;
	nsXPIDLString pszAbsFilePath; pszAbsFilePath.AssignWithConversion(GOLDEN_COPY_OVA_PATH);
	nsXPIDLString name; name.AssignWithConversion(qName.toStdString().c_str());
	IMachine *new_machine = nsnull;

	if(existVM(qName))
		return nsnull;

	nsXPIDLString settingsFile;
	virtualBox->ComposeMachineFilename(name, NULL, NULL, NULL, getter_Copies(settingsFile));
	std::cout << "Predicted settings file name: " << returnQStringValue(settingsFile).toStdString() << std::endl;

	QFile file(returnQStringValue(settingsFile));
	QFile file_prev(returnQStringValue(settingsFile).append("-prev"));

	if(file.exists())
	{
		if(file.remove())
			std::cerr  << "Deleted old settings file: " << file.fileName().toStdString() << std::endl;
		else
			std::cerr  << "Error while deleting old settings file: " << file.fileName().toStdString() << std::endl;
	}
	if(file_prev.exists())
	{
		if(file_prev.remove())
			std::cerr  << "Deleted old backup settings file: " << file_prev.fileName().toStdString() << std::endl;
		else
			std::cerr  << "Error while deleting old backup settings file: " << file_prev.fileName().toStdString() << std::endl;
	}

	do
	{
		ComPtr<IAppliance> pAppliance;
		ComPtr<IProgress> progressRead;

		NS_CHECK_AND_DEBUG_ERROR(virtualBox, CreateAppliance(pAppliance.asOutParam()), rc);
		NS_CHECK_AND_DEBUG_ERROR(pAppliance, Read(pszAbsFilePath, progressRead.asOutParam()), rc);

		QString label = QString::fromUtf8("Caricamento impostazioni macchina \"").append(qName).append("\"...");
		ProgressDialog p(label);
		p.ui->progressBar->setValue(0);
		p.ui->label->setText(label);
		p.open();

		int32_t resultCode;
		PRBool progress_completed;
		do
		{
			uint32_t percent;
			progressRead->GetCompleted(&progress_completed);
			progressRead->GetPercent(&percent);
			p.ui->progressBar->setValue(percent);
			p.refresh();
			usleep(750000);
		} while(!progress_completed);

		progressRead->GetResultCode(&resultCode);

		if(resultCode != 0)
		{
			std::cout << "Appliance read failed -> resultCode: " << resultCode << std::endl;
			break;
		}

		nsXPIDLString path; /* fetch the path, there is stuff like username/password removed if any */
		NS_CHECK_AND_DEBUG_ERROR(pAppliance, GetPath(getter_Copies(path)), rc);

		NS_CHECK_AND_DEBUG_ERROR(pAppliance, Interpret(), rc);
// 		com::ErrorInfo info0(pAppliance, COM_IIDOF(IAppliance));

		PRUnichar **aWarnings;
		uint32_t aWarnings_size;
		pAppliance->GetWarnings(&aWarnings_size, &aWarnings);

		if (NS_FAILED(rc))     // during interpret, after printing warnings
		{
			std::cerr << "Fail during interpret:" << std::endl;
			for(int i; i < aWarnings_size; i++)
				std::cerr << "Warning: " << aWarnings[i] << std::endl;
			break;
		}

		// fetch all disks
		PRUnichar **retDisks;
		uint32_t retDisks_size;
		NS_CHECK_AND_DEBUG_ERROR(pAppliance, GetDisks(&retDisks_size, &retDisks), rc);

		// fetch virtual system descriptions
		IVirtualSystemDescription **aVirtualSystemDescriptions;
		uint32_t aVirtualSystemDescriptions_size;
		NS_CHECK_AND_DEBUG_ERROR(pAppliance, GetVirtualSystemDescriptions(&aVirtualSystemDescriptions_size, &aVirtualSystemDescriptions), rc);

		// dump virtual system descriptions and match command-line arguments
		if (aVirtualSystemDescriptions_size > 0)
		{
			for (unsigned i = 0; i < aVirtualSystemDescriptions_size; ++i)
			{
				uint32_t *retTypes;             uint32_t retTypes_size;
				PRUnichar **aRefs;              uint32_t aRefs_size;
				PRUnichar **aOvfValues;         uint32_t aOvfValues_size;
				PRUnichar **aVBoxValues;        uint32_t aVBoxValues_size;
				PRUnichar **aExtraConfigValues; uint32_t aExtraConfigValues_size;

				NS_CHECK_AND_DEBUG_ERROR(aVirtualSystemDescriptions[i],
							 GetDescription(&retTypes_size, &retTypes,
									&aRefs_size, &aRefs,
									&aOvfValues_size, &aOvfValues,
									&aVBoxValues_size, &aVBoxValues,
									&aExtraConfigValues_size, &aExtraConfigValues),
							 rc);

				// this collects the final values for setFinalValues()
				PRBool aEnabled[retTypes_size];

				for (unsigned a = 0; a < retTypes_size; ++a)
				{
					aEnabled[a] = true;
					if(retTypes[a] == VirtualSystemDescriptionType::Name)
					{
						aVBoxValues[a] = (PRUnichar *)realloc(aVBoxValues[a], sizeof(PRUnichar*) * (qName.length() + 1));
						memset(aVBoxValues[a], 0, sizeof(PRUnichar*) * (qName.length() + 1));
						for(int i = 0; i < qName.length(); i++)
							aVBoxValues[a][i] = qName.toStdString().c_str()[i];
					}
					else if(retTypes[a] == VirtualSystemDescriptionType::HardDiskImage)
					{
						QString disk_image_path = returnQStringValue(settingsFile);

						int end_index = disk_image_path.lastIndexOf('/');
						disk_image_path = disk_image_path.mid(0, end_index).append("/").append(qName).append(".vmdk");

						std::cout << "disk_image_path: " << disk_image_path.toStdString() << std::endl;

						aVBoxValues[a] = (PRUnichar *)realloc(aVBoxValues[a], sizeof(PRUnichar*) * (disk_image_path.length() + 1));
						memset(aVBoxValues[a], 0, sizeof(PRUnichar*) * (disk_image_path.length() + 1));

						for(int i = 0; i < disk_image_path.length(); i++)
							aVBoxValues[a][i] = disk_image_path.toStdString().c_str()[i];
					}
				}

				NS_CHECK_AND_DEBUG_ERROR(aVirtualSystemDescriptions[i],
							 SetFinalValues(retTypes_size, aEnabled,
									aVBoxValues_size, const_cast<const PRUnichar**>(aVBoxValues),
									aExtraConfigValues_size, const_cast<const PRUnichar**>(aExtraConfigValues)),
							 rc);
			}

			// go!
			ComPtr<IProgress> progress;
			NS_CHECK_AND_DEBUG_ERROR(pAppliance, ImportMachines(0, NULL, progress.asOutParam()), rc);
			std::cout << "Wait for importing appliance" << std::endl;

			QString label = QString::fromUtf8("Creazione macchina \"").append(qName).append("\"...");
			p.ui->progressBar->setValue(0);
			p.ui->label->setText(label);
			p.open();

			int32_t resultCode;
			PRBool progress_completed;
			do
			{
				uint32_t percent;
				progress->GetCompleted(&progress_completed);
				progress->GetPercent(&percent);
				p.ui->progressBar->setValue(percent);
				p.refresh();
				usleep(750000);
			} while(!progress_completed);

			progress->GetResultCode(&resultCode);

			if(resultCode != 0)
			{
				std::cout << "Appliance import failed -> resultCode: " << resultCode << std::endl;
				break;
			}

			if (NS_SUCCEEDED(rc))
			{
				import_done = true;
				std::cout << "Successfully imported the appliance." << std::endl;
			}
		} // end if (aVirtualSystemDescriptions.size() > 0)
	} while (0);

	if(import_done)
		virtualBox->FindMachine(name, &new_machine);

	return new_machine;
}
static void RunBuiltInCmd(commandT* cmd)
{
  /* If applicable, reformat command with the aliases substituted */

  aliasL* node = aliases;
  while (node != NULL) {
    if (strcmp(cmd->argv[0], node->name) == 0) {
      char** argv = (char**) malloc(sizeof(char*) * cmd->argc); // store new argv for concatenating into a new command

      /* populate argv with aliased replacements as long as the alias's command is trailed by a space */

      int argi;
      int aliasNext = TRUE;
      size_t length = 0;

      for (argi = 0; argi < cmd->argc; argi++) {
        node = NULL;

        if (aliasNext) {
          node = aliases;
          while (node != NULL) {
            if (strcmp(cmd->argv[argi], node->name) == 0) {
              break;
            }
            node = node->next;
          }
        }

        if (node != NULL) {
          argv[argi] = strdup(node->cmdline);
          length += strlen(argv[argi]) + 1;
          if (node->cmdline[strlen(node->cmdline) - 1] != ' ') {
            aliasNext = FALSE;
          }
        } else {
          argv[argi] = strdup(cmd->argv[argi]);
          length += strlen(argv[argi]) + 1;
          aliasNext = FALSE;
        }
      }

      /* create new command string */

      char* cmdline = (char*) malloc(sizeof(char) * length);
      strcpy(cmdline, "");

      for (argi = 0; argi < cmd->argc; argi++) {
        strcat(cmdline, argv[argi]);
        strcat(cmdline, " ");
      }

      /* handle as any other command */

      Interpret(cmdline);

      return; // return to shell
    }
    node = node->next;
  }

  /* Builtin commands implemented here */

  if (strcmp(cmd->argv[0], "cd") == 0) {
    char* path;

    if (cmd->argc > 1) {
      path = cmd->argv[1];
    } else {
      path = getenv("HOME");
    }

    if (chdir(path) < 0) {
      printf("failed to change directory\n");
      fflush(stdout);
    }
  } else if (strcmp(cmd->argv[0], "jobs") == 0) {
    bgjobL* node = bgjobs;
    while (node != NULL) {
      if (IS_TERMINATED(node)) {
        printf("[%d]   Done                    %s\n", node->jid, node->cmdline);
      } else {
        if (IS_RUNNING(node)) {
          printf("[%d]   Running                 %s &\n", node->jid, node->cmdline);
        } else {
          printf("[%d]   Stopped                 %s\n", node->jid, node->cmdline);
        }
      }
      fflush(stdout);

      CleanupJob(&node, FALSE);

      if (node == NULL) {
        node = bgjobs;
      } else {
        node = node->next;
      }
    }
  } else if (strcmp(cmd->argv[0], "fg") == 0) {
    ContinueCmd(cmd->argv, cmd->argc, TRUE);
  } else if (strcmp(cmd->argv[0], "bg") == 0) {
    ContinueCmd(cmd->argv, cmd->argc, FALSE);
  } else if (strcmp(cmd->argv[0], "alias") == 0) {
    if (cmd->argc == 1) {
      /* Print Aliases */

      aliasL* node = aliases;
      while (node != NULL) {
        printf("alias %s='%s'\n", node->name, node->cmdline);
        fflush(stdout);
        node = node->next;
      }
    } else {
      /* Make Alias */

      size_t h = 0;
      while (cmd->cmdline[h] != 'a') { h++; }

      // assume that lias comes after 'a'
      h += 5;

      while (cmd->cmdline[h] == ' ') { h++; }

      size_t i = 0;

      while (cmd->cmdline[h + i] != '=') { i++; }

      char* name = (char*) malloc(sizeof(char) * (i + 1));
      strncpy(name, &(cmd->cmdline)[h], i);
      name[i] = '\0';

      while (cmd->cmdline[h + i] != '\'') { i++; }

      i++;

      size_t j = 0;

      while (cmd->cmdline[h + i + j] != '\'') { j++; }

      char* cmdline = (char*) malloc(sizeof(char) * (j + 1));
      strncpy(cmdline, &(cmd->cmdline)[h + i], j);
      cmdline[j] = '\0';

      /* find the sorted place for the alias */

      aliasL* found = NULL;
      aliasL* prev = NULL;
      aliasL* node = aliases;

      while (node != NULL && found == NULL) {
        int cmp = strcmp(name, node->name);
        if (cmp == 0) {
          found = node;
          break;
        } else if (cmp < 0) {
          found = (aliasL*) malloc(sizeof(aliasL));
          if (prev != NULL) {
            prev->next = found;
          } else {
            aliases = found;
          }
          found->next = node;
          break;
        }
        prev = node;
        node = node->next;
      }

      if (found == NULL) {
        found = (aliasL*) malloc(sizeof(aliasL));
        if (prev != NULL) {
          prev->next = found;
        } else {
          aliases = found;
        }
        found->next = NULL;
      }

      found->name = name;
      found->cmdline = cmdline;

    }
  } else if (strcmp(cmd->argv[0], "unalias") == 0) {
    aliasL* prev = NULL;
    aliasL* node = aliases;
    while (node != NULL) {
      if (strcmp(node->name, cmd->argv[1]) == 0) {
        if (prev != NULL) {
          prev->next = node->next;
        } else {
          aliases = node->next;
        }

        free(node->name);
        free(node->cmdline);
        free(node);

        node = NULL;
      } else {
        prev = node;
        node = node->next;
      }
    }
  }
}
Exemple #24
0
_BEGIN_SNACC_NAMESPACE


AsnLen PERGeneral::EncodeGeneral(AsnBufBits &b)const
{
	AsnLen len = 0;
	unsigned long l_64kFrag = l_16k * 4;
	unsigned long count = 0;
	unsigned long x = 0;
	unsigned long y = 0;
	unsigned long tempLen = lEncLen();
	unsigned char ch = 0x00;
	unsigned char *c = NULL;
	long offset = 0;
	
	

	if(tempLen >= l_16k)
	{	
		/*there is more than 16k bytes of data*/
		count = (tempLen / l_64kFrag);
		
		for(x=0; x < count; x++)
		{  
			len += b.OctetAlignWrite();
			
			len += PEncLen_16kFragment(b, 4);
			
			len += b.OctetAlignWrite();

			for(y = 0; y < l_64kFrag; y++)
			{
				len += Interpret(b, offset);
				offset++;
			}
			
		}

		tempLen -= count * l_64kFrag;

		count = tempLen / l_16k;

		if(count != 0)
		{  
			len += b.OctetAlignWrite();
			
			len += PEncLen_16kFragment(b, count);
		
			len += b.OctetAlignWrite();

			for(y = 0; y < (l_16k * count); y++)
			{
				len += Interpret(b, offset);
				offset++;
			}
		
		}
		
		tempLen -=  (l_16k * count);

		if(tempLen == 0)
		{
			ch = 0x00;
			c = &ch;
			
			len += b.OctetAlignWrite();

			len += b.PutBits(c, 8);
			
			return len;
		}

	}

	/*if there are less than 128 bytes of data*/
	if(tempLen < 128)
	{
		len += b.OctetAlignWrite();

		len += PEncDefLenTo127(b, tempLen);
		
		len += b.OctetAlignWrite();

		for(y = 0; y < tempLen; y++)
		{
			len += Interpret(b, offset);
			offset++;
		}
		
	}
	else if(tempLen >= 128 && tempLen < l_16k)
	{
		len += b.OctetAlignWrite();
		/*if there is less than 16k bytes of data*/
		/*and more than 127 bytes of data*/
		len += PEncLen_1to16k(b, tempLen);
		
		len += b.OctetAlignWrite();

	
		for(y = 0; y < tempLen; y++)
		{
			len += Interpret(b, offset);
			offset++;
		}
		
	}

	return len;
}