Ejemplo n.º 1
0
int main() {
	int key, menuitem, ent, id;
	menuitem = 0;
	initscr();
	drawmenu(menuitem);
	keypad(stdscr,TRUE);
	
	noecho();
	do {
		key = getch();
		switch(key) {
			case KEY_DOWN: menuitem++;
			if(menuitem > MENUMAX-1) 
				menuitem = 0;
			break;

			case KEY_UP: menuitem--;
			if(menuitem < 0) 
				menuitem = MENUMAX-1;
			break;

			default: 
			break;

		}

		drawmenu(menuitem);
		
		ent = getch();
	
		if(menuitem == 0 && ent == KEY_RIGHT) { 
			login();
			refresh();
		}
		else if(menuitem == 1 && ent == KEY_RIGHT) {
			register_id();
			refresh();
		}
		else if(menuitem == 2 && ent == KEY_RIGHT) { 
			findtrain();
			refresh();
		}
		else if(menuitem == 3 && ent == KEY_RIGHT) { 
			move(0,0);
			clrtobot();			
			printw("Enter train id\n");			
			scanw("%d", &id);
			CheckAvailibility(id);
			refresh();
		}	
		else if(menuitem == 4 && ent == KEY_RIGHT) { 
			cancelticket();
			refresh();
		}
		else if(menuitem == 5 && ent == KEY_RIGHT) { 
			DisplayQueueac();
			refresh();
		}
		else if(menuitem == 6 && ent == KEY_RIGHT) { 
			DisplayQueuesl();
			refresh();
		}
		else if(menuitem == 7 && ent == KEY_RIGHT) { 
			exit(1);
		}
	}	
	while(key != '\n');
		echo();      /*Shows the text*/
	
	endwin();
	return 0;

}
Ejemplo n.º 2
0
void drawStuff(int** cardToBeDrawn)
{
    WINDOW * mainwin;
    int n, x, y, m;
    int num = 0;

    /*  Initialize ncurses  */

    if ( (mainwin = initscr()) == NULL ) {
        fprintf(stderr, "Error initialising ncurses.\n");
        exit(EXIT_FAILURE);
    }
    
    resizeterm(100,56);
    
    keypad(mainwin, TRUE);
    (void) nonl();         /* tell curses not to do NL->CR/NL on output */
    (void) cbreak();       /* take input chars one at a time, no wait for \n */
    (void) echo();         /* echo input - in color */
    start_color();                    /*  Initialize colours  */

	

    if ( has_colors() && COLOR_PAIRS >= 13 ) {

        init_pair(1,  COLOR_RED,     COLOR_BLACK);
        init_pair(2,  COLOR_GREEN,   COLOR_BLACK);
        init_pair(3,  COLOR_YELLOW,  COLOR_BLACK);
        init_pair(4,  COLOR_BLUE,    COLOR_BLACK);
        init_pair(5,  COLOR_MAGENTA, COLOR_BLACK);
        init_pair(6,  COLOR_CYAN,    COLOR_BLACK);
        init_pair(7,  COLOR_BLUE,    COLOR_WHITE);
        init_pair(8,  COLOR_WHITE,   COLOR_RED);
        init_pair(9,  COLOR_BLACK,   COLOR_GREEN);
        init_pair(10, COLOR_BLUE,    COLOR_YELLOW);
        init_pair(11, COLOR_WHITE,   COLOR_BLUE);
        init_pair(12, COLOR_WHITE,   COLOR_MAGENTA);
        init_pair(13, COLOR_BLACK,   COLOR_BLACK);

        color_set(4, NULL);
        mvaddstr(0, 0,  "--------------------------------------------------------");
        mvaddstr(1, 0,  "|          |          |          |          |          |");
        mvaddstr(2, 0,  "|          |          |          |          |          |");
        mvaddstr(3, 0,  "|          |          |          |          |          |");
        mvaddstr(4, 0,  "|          |          |          |          |          |");
        mvaddstr(5, 0,  "|          |          |          |          |          |");
        mvaddstr(6, 0,  "________________________________________________________");

        mvaddstr(7, 0,  "|          |          |          |          |          |");
        mvaddstr(8, 0,  "|          |          |          |          |          |");
        mvaddstr(9, 0,  "|          |          |          |          |          |");
        mvaddstr(10, 0, "|          |          |          |          |          |");
        mvaddstr(11, 0, "|          |          |          |          |          |");
        mvaddstr(12, 0, "________________________________________________________");
		refresh();
        mvaddstr(13, 0, "|          |          |          |          |          |");
        mvaddstr(14, 0, "|          |          |          |          |          |");
        mvaddstr(15, 0, "|          |          |          |          |          |");
        mvaddstr(16, 0, "|          |          |          |          |          |");
        mvaddstr(17, 0, "|          |          |          |          |          |");
        mvaddstr(18, 0, "________________________________________________________");

        mvaddstr(19, 0, "|          |          |          |          |          |");
        mvaddstr(20, 0, "|          |          |          |          |          |");
        mvaddstr(21, 0, "|          |          |          |          |          |");
        mvaddstr(22, 0, "|          |          |          |          |          |");
        mvaddstr(23, 0, "|          |          |          |          |          |");
        mvaddstr(24, 0, "________________________________________________________");

        mvaddstr(25, 0, "|          |          |          |          |          |");
        mvaddstr(26, 0, "|          |          |          |          |          |");
        mvaddstr(27, 0, "|          |          |          |          |          |");
        mvaddstr(28, 0, "|          |          |          |          |          |");
        mvaddstr(29, 0, "|          |          |          |          |          |");
        mvaddstr(30, 0, "________________________________________________________");
		refresh();
        mvaddstr(31, 0, "|          |          |          |          |          |");
        mvaddstr(32, 0, "|          |          |          |          |          |");
        mvaddstr(33, 0, "|          |          |          |          |          |");
        mvaddstr(34, 0, "|          |          |          |          |          |");
        mvaddstr(35, 0, "|          |          |          |          |          |");
        mvaddstr(36, 0, "________________________________________________________");


        color_set(5, NULL);
        mvaddstr(1, 2,  " BBBBB");
        mvaddstr(2, 2,  " BB  BB");
        mvaddstr(3, 2,  " BBBBB");
        mvaddstr(4, 2,  " BB  BB");
        mvaddstr(5, 2,  " BBBBB");

        mvaddstr(1, 13, " IIIIII");
        mvaddstr(2, 13, "   II  ");
        mvaddstr(3, 13, "   II  ");
        mvaddstr(4, 13, "   II  ");
        mvaddstr(5, 13, " IIIIII");

        mvaddstr(1, 24, "NN    N");
        mvaddstr(2, 24, "N N   N");
        mvaddstr(3, 24, "N  N  N");
        mvaddstr(4, 24, "N   N N ");
        mvaddstr(5, 24, "N    NN");
		refresh();
        mvaddstr(1, 35, " GGGGGG");
        mvaddstr(2, 35, " G     ");
        mvaddstr(3, 35, " G  GGG");
        mvaddstr(4, 35, " G    G");
        mvaddstr(5, 35, " GGGGGG");

        mvaddstr(1, 46, " OOOOOO");
        mvaddstr(2, 46, " O    O");
        mvaddstr(3, 46, " O    O");
        mvaddstr(4, 46, " O    O");
        mvaddstr(5, 46, " OOOOOO");

        mvaddstr(20, 26, "FREE");
        mvaddstr(22, 25, "SPACE!");

 
		y=9;

    	for(m=0; m<=4; m++) {
                x = 5;
                for(n=0; n<=4; n++) {
                        if(y==21 && n==2) {
                                x+=11;
                                continue;
                        }
                        else if(n==0) {
                                mvprintw(y,x,"%d", cardToBeDrawn[n][m]);
                        }
                        else {
                                x+=11;
                                mvprintw(y,x,"%d", cardToBeDrawn[n][m]);
                        }
                }
	        y+=6;
        }
        color_set(13, NULL);
        mvaddstr(37, 0, "");
    }


    /*  Refresh the screen and sleep for a
        while to get the full screen effect  */

    refresh();
    int c;
    while(c!='\r')
    {
        c = getch();
       /* refresh, accept single keystroke of input */

        num++;

        /* process the command keystroke */
    }
    sleep(2);


    /*  Clean up after ourselves  */

    delwin(mainwin);
    endwin();
    refresh();

}
Ejemplo n.º 3
0
void judge_utility(char *command, char *args[], int size){
	pid_t pid;
	int i;
	char *argv[1000];
	char value[1050];
	extern char first[1000];

	if(command[0] == '$'){
		showenviron(&command, 1);
		return;
	}

	//若没有指输入,直接返回
	if(strlen(command) == 0) return;

	//若第一个字符串(即command)查询环境变量,调用查看环境变量的函数
	//根据bash的特点,此时只传入command
	if(command[0] == '$'){
		//show_pathname(command);
		return;
	}

	//cd指令
	if(strcmp(command, "cd") == 0){
		cd(args, size);
		return;
	}

	//quit指令
	if(strcmp(command, "quit") == 0){
		exit(0);
	}

	//echo指令
	if(strcmp(command, "echo") == 0){
		echo(args, size);
		return;
	}

	//clear指令
	if(strcmp(command, "clr") == 0){
		//输出一段转义序列清空屏幕
		printf( "\033[H""\033[2J");
		return;
	}

	//dir指令
	if(strcmp(command, "dir") == 0){
		dir(args, size);
		return;
	}

	//environ指令
	if(strcmp(command, "environ") == 0){
		showenviron(args, size);
		return;
	}

	//myshell命令
	if(strcmp(command, "myshell") == 0){
		myshell(args, size);
		return;
	}

	//help指令
	if(strcmp(command, "help") == 0){
		help(args, size);
		return;
	}

	//初始化execvp的第二个参数
	argv[0] = command;
	for(i = 0; i < size; i++)
		argv[i + 1] = args[i];
	argv[i + 1] = 0;

	pid = fork();
	if(pid < 0){
		printf("创建子进程失败!\n");
		return;
	}
	if(pid == 0){
		int ret;
		//增加parent环境变量
		strcpy(value, "parent=");
		strcat(value, first);
		strcat(value, "/myshell");
		putenv(value);
		//创建子进程调用外部指令
		ret = execvp(command, argv);
		if(ret == -1){
			//找不到指令
			printf("%s: 没有这个命令\n", command);
		}
		exit(0);
	}else{
		//等待子进程完成后返回
		int *status;
		wait(status);
		return;
	}
	
}
Ejemplo n.º 4
0
static void banner(void)
{
    delline();
    echo("Finit version " VERSION " (" WHOAMI ") " __DATE__ " " __TIME__);
}
Ejemplo n.º 5
0
void outputTest(WINDOW *win)
{
    WINDOW *win1;
    char Buffer[80];
    chtype ch;
    int by, bx;

    nl();
    wclear(win);
    mvwaddstr(win, 1, 1, "You should now have a screen in the upper "
              "left corner, and this text should have wrapped");
    waddstr(win,"\nThis text should be down\n");
    waddstr(win,  "and broken into two here ^");
    Continue(win);

    wclear(win);
    wattron(win, A_BOLD);
    mvwaddstr(win, 1, 1, "A new window will appear with this text in it");
    mvwaddstr(win, 8, 1, "Press any key to continue");
    wrefresh(win);
    wgetch(win);

    getbegyx(win, by, bx);

    if (LINES < 24 || COLS < 75)
    {
        mvwaddstr(win, 5, 1, "Some tests have been skipped as they require a");
        mvwaddstr(win, 6, 1, "display of at least 24 LINES by 75 COLUMNS");
        Continue(win);
    }
    else
    {
        win1 = newwin(10, 50, 14, 25);

        if (win1 == NULL)
        {
            endwin();
            return;
        }

#ifdef A_COLOR
        if (has_colors())
        {
            init_pair(3, COLOR_BLUE, COLOR_WHITE);
            wbkgd(win1, COLOR_PAIR(3));
        }
        else
#endif
            wbkgd(win1, A_NORMAL);

        wclear(win1);
        mvwaddstr(win1, 5, 1, "This text should appear; using overlay option");
        copywin(win, win1, 0, 0, 0, 0, 9, 49, TRUE);
        box(win1, ACS_VLINE, ACS_HLINE);
        wmove(win1, 8, 26);
        wrefresh(win1);
        wgetch(win1);

        wclear(win1);

        wattron(win1, A_BLINK);
        mvwaddstr(win1, 4, 1,
                  "This blinking text should appear in only the second window");
        wattroff(win1, A_BLINK);

        mvwin(win1, by, bx);
        overlay(win, win1);
        mvwin(win1, 14, 25);
        wmove(win1, 8, 26);
        wrefresh(win1);
        wgetch(win1);

        delwin(win1);
    }

    clear();
    wclear(win);
    wrefresh(win);
    mvwaddstr(win, 6, 2, "This line shouldn't appear");
    mvwaddstr(win, 4, 2, "Only half of the next line is visible");
    mvwaddstr(win, 5, 2, "Only half of the next line is visible");
    wmove(win, 6, 1);
    wclrtobot(win);
    wmove(win, 5, 20);
    wclrtoeol(win);
    mvwaddstr(win, 8, 2, "This line also shouldn't appear");
    wmove(win, 8, 1);
    winsdelln(win, -1);
    Continue(win);

    wmove(win, 5, 9);
    ch = winch(win);

    wclear(win);
    wmove(win, 6, 2);
    waddstr(win, "The next char should be l:  ");
    winsch(win, ch);
    Continue(win);

    mvwinsstr(win, 6, 2, "A1B2C3D4E5");
    Continue(win);

    wmove(win, 5, 1);
    winsdelln(win, 1);
    mvwaddstr(win, 5, 2, "The lines below should have moved down");
    Continue(win);

    wclear(win);
    wmove(win, 2, 2);
    wprintw(win, "This is a formatted string in a window: %d %s\n",
            42, "is it");
    mvwaddstr(win, 10, 1, "Enter a string: ");
    wrefresh(win);
    echo();
    wscanw(win, "%s", Buffer);

    printw("This is a formatted string in stdscr: %d %s\n", 42, "is it");
    mvaddstr(10, 1, "Enter a string: ");
    scanw("%s", Buffer);

    wclear(win);
    curs_set(2);
    mvwaddstr(win, 1, 1, "The cursor should be in high-visibility mode");
    Continue(win);

    wclear(win);
    curs_set(0);
    mvwaddstr(win, 1, 1, "The cursor should have disappeared");
    Continue(win);

    wclear(win);
    curs_set(1);
    mvwaddstr(win, 1, 1, "The cursor should be normal");
    Continue(win);

#ifdef A_COLOR
    if (has_colors())
    {
        wclear(win);
        mvwaddstr(win, 1, 1, "Colors should change after you press a key");
        Continue(win);

        init_pair(1, COLOR_RED, COLOR_WHITE);
        wrefresh(win);
    }
#endif
    werase(win);
    mvwaddstr(win, 1, 1, "Information About Your Terminal");
    mvwaddstr(win, 3, 1, termname());
    mvwaddstr(win, 4, 1, longname());

    if (termattrs() & A_BLINK)
        mvwaddstr(win, 5, 1, "This terminal claims to support blinking.");
    else
        mvwaddstr(win, 5, 1, "This terminal does NOT support blinking.");

    mvwaddnstr(win, 7, 5, "Have a nice day!ok", 16);
    wrefresh(win);

    mvwinnstr(win, 7, 5, Buffer, 18);
    mvaddstr(LINES - 2, 10, Buffer);
    refresh();
    Continue(win);
}
Ejemplo n.º 6
0
int ssl_init_info(int *server_fd,ssl_info *sslinfo)
{
    int ret;
    const char *pers = "ssl";
    mbedtls_x509_crt_init(&sslinfo->cacert );
    mbedtls_ctr_drbg_init(&sslinfo->ctr_drbg);
    mbedtls_entropy_init(&sslinfo->entropy );

    if( mbedtls_ctr_drbg_seed( &sslinfo->ctr_drbg, mbedtls_entropy_func, &sslinfo->entropy,
                       (const unsigned char *) pers, strlen( pers ) ) != 0 )
    {
        return  -1;

    }

    mbedtls_ssl_init( &sslinfo->ssl );
    mbedtls_ssl_config_init( &sslinfo->conf );
    if( ( ret = mbedtls_ssl_config_defaults( &sslinfo->conf,
                    MBEDTLS_SSL_IS_CLIENT,
                    MBEDTLS_SSL_TRANSPORT_STREAM,
                    MBEDTLS_SSL_PRESET_DEFAULT ) ) != 0 )
    {
        echo( " failed\n  ! mbedtls_ssl_config_defaults returned %d\n\n", ret );
       return -1;
    }



    mbedtls_ssl_conf_endpoint( &sslinfo->conf, MBEDTLS_SSL_IS_CLIENT );
    mbedtls_ssl_conf_authmode( &sslinfo->conf, MBEDTLS_SSL_VERIFY_OPTIONAL );
    mbedtls_ssl_conf_ca_chain( &sslinfo->conf, &sslinfo->cacert,NULL);
    mbedtls_ssl_conf_rng( &sslinfo->conf, mbedtls_ctr_drbg_random, &sslinfo->ctr_drbg );

    if( ( ret = mbedtls_ssl_setup( &sslinfo->ssl, &sslinfo->conf ) ) != 0 )
    {
        echo( " failed\n  ! mbedtls_ssl_setup returned %d\n\n", ret );
        return -1;
    }

    mbedtls_ssl_set_bio( &sslinfo->ssl, server_fd,mbedtls_net_send, mbedtls_net_recv,NULL );
    mbedtls_ssl_set_session(&sslinfo->ssl, &ssn);
    while((ret = mbedtls_ssl_handshake(&sslinfo->ssl))!=0)
    {
        if( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
        {
            echo( " failed\n  ! ssl_handshake returned -0x%x\n\n", -ret );
            return -1;
        }
        //CPU sleep
        sleeps(1);
    }



    if((ret = mbedtls_ssl_get_verify_result( &sslinfo->ssl ) ) != 0 )
    {
       // echo( "Verifying peer X.509 certificate...failed \r\n" );
    }
    else
    {
        echo( " ok\n" );
    }
    //保存session
    if( ( ret = mbedtls_ssl_get_session( &sslinfo->ssl, &ssn ) ) != 0 )
    {
        //失败初始化
        memset(&ssn, 0, sizeof(mbedtls_ssl_session));
    }
    return 0;
}
Ejemplo n.º 7
0
// recurs.c was included

#ifndef MY_INCLUDE_GUARD
#define MY_INCLUDE_GUARD
// recurs.c was evaluated


// including itself, how clever...
#include "recurs.c"


// This file shows the use of Include Guards.
// If you remove the guards, you'll get infinite recursion.
//
// Check how it is evaluated - let sdscp compile it and see the output.
moo()
{
	echo("MoOooOooOO!!")
}

#endif
Ejemplo n.º 8
0
Archivo: ui.c Proyecto: hahahafr/ziege
void
init_player_ui(jeu_s jeu, aff_s aff)
{
    char nomj1[TAILLE_NOM];
    char nomj2[TAILLE_NOM];
    char rolej1;
    char ai;
    int roleint;

    curs_set(1);
    echo();

    do {
    wattron(aff->etat, A_BOLD | A_REVERSE);
    mvwprintw(aff->etat, 1, 2, "Entrez le rôle du joueur 1");
    mvwprintw(aff->etat, 2, 2, "0 pour chèvre, 1 pour tigre :");
    wattroff(aff->etat, A_BOLD | A_REVERSE);
    wattron(aff->etat, A_BOLD);
    mvwscanw(aff->etat, 3, 2, "%c", &rolej1);
    wrefresh(aff->etat);
    wattroff(aff->etat, A_BOLD);

    wmove(aff->etat, 1, 2);
    wclrtoeol(aff->etat);
    wmove(aff->etat, 2, 2);
    wclrtoeol(aff->etat);
    wmove(aff->etat, 3, 2);
    wclrtoeol(aff->etat);
    wrefresh(aff->etat);
    } while ((rolej1 != '0') && (rolej1) != '1');

    if (rolej1 == '0')
        roleint = 0;
    else
        roleint = 1;


    do {
    wattron(aff->etat, A_BOLD | A_REVERSE);
    mvwprintw(aff->etat, 1, 2, "Jouer contre l'AI ?");
    mvwprintw(aff->etat, 2, 2, "0 pour NON, 1 pour OUI:");
    wattroff(aff->etat, A_BOLD | A_REVERSE);
    wattron(aff->etat, A_BOLD);
    mvwscanw(aff->etat, 3, 2, "%c", &ai);
    wrefresh(aff->etat);
    wattroff(aff->etat, A_BOLD);

    wmove(aff->etat, 1, 2);
    wclrtoeol(aff->etat);
    wmove(aff->etat, 2, 2);
    wclrtoeol(aff->etat);
    wmove(aff->etat, 3, 2);
    wclrtoeol(aff->etat);
    wrefresh(aff->etat);
    } while ((ai != '0') && (ai) != '1');

    if (ai == '0')
        init_player(jeu, roleint);
    else
        init_player_ai(jeu, roleint, !roleint);

    curs_set(0);
    noecho();
}
Ejemplo n.º 9
0
Variant invokeImpl(void *extra, CArrRef params) {
  const char *function = (const char*)extra;
  // for TestExtFunction
  if (strcasecmp(function, "test") == 0) {
    return params[0];
  }

  // for TestExtPreg::test_preg_replace_callback
  if (strcasecmp(function, "next_year") == 0) {
    Array matches = params[0].toArray();
    return matches[1].toString() + String(matches[2].toInt32() + 1);
  }

  // for TestExtArray::test_array_filter
  if (strcasecmp(function, "odd") == 0) {
    return params[0].toInt32() & 1;
  }
  if (strcasecmp(function, "even") == 0) {
    return !(params[0].toInt32() & 1);
  }

  // for TestExtArray::test_array_map
  if (strcasecmp(function, "cube") == 0) {
    int n = params[0].toInt32();
    return n * n * n;
  }

  // for TestExtArray::test_array_multisort
  if (strcasecmp(function, "strtolower") == 0) {
    return f_strtolower(params[0]);
  }

  // for TestExtArray::test_array_reduce
  if (strcasecmp(function, "rsum") == 0) {
    int v = params[0].toInt32();
    int w = params[1].toInt32();
    v += w;
    return v;
  }
  if (strcasecmp(function, "rmul") == 0) {
    int v = params[0].toInt32();
    int w = params[1].toInt32();
    v *= w;
    return v;
  }

  // for TestExtArray::test_array_walk_recursive
  if (strcasecmp(function, "test_print") == 0) {
    String item = params[0].toString();
    String key = params[1].toString();
    echo(key + ": " + item + "\n");
  }

  // for TestExtArray::test_array_walk
  if (strcasecmp(function, "test_alter") == 0) {
    Variant &item1 = lval(((Array&)params).lvalAt(0));
    String key = params[1];
    String prefix = params[2];
    item1 = prefix + ": " + item1;
  }

  // for TestExtArray::test_array_udiff
  if (strcasecmp(function, "comp_func") == 0) {
    int n1 = params[0].toInt32();
    int n2 = params[1].toInt32();
    if (n1 == n2) return 0;
    return n1 > n2 ? 1 : -1;
  }

  // for TestExtArray::test_usort
  if (strcasecmp(function, "reverse_comp_func") == 0) {
    int n1 = params[0].toInt32();
    int n2 = params[1].toInt32();
    if (n1 == n2) return 0;
    return n1 > n2 ? -1 : 1;
  }

  // for TestExtArray::test_array_uintersect
  if (strcasecmp(function, "strcasecmp") == 0) {
    String s1 = params[0].toString();
    String s2 = params[1].toString();
    return strcasecmp(s1.data(), s2.data());
  }

  // for TestExtArray::test_uasort
  if (strcasecmp(function, "reverse_strcasecmp") == 0) {
    String s1 = params[0].toString();
    String s2 = params[1].toString();
    return strcasecmp(s2.data(), s1.data());
  }

  // for TestExtFbml
  if (strcasecmp(function, "urltr") == 0) {
    String s1 = params[0].toString();
    String s2 = params[1].toString();
    return String("url:") + s1 + "=" + s2;
  }

  // for TestExtCurl::test_curl_exec
  if (strcasecmp(function, "curl_write_func") == 0) {
    print("curl_write_func called with ");
    print(params[1]);
    return params[1].toString().size();
  }

  // for TestExtPreg::test_preg_replace
  if (strcasecmp(function, "strtoupper") == 0) {
    return f_strtoupper(params[0].toString());
  }
  if (strcasecmp(function, "test_preg_rep") == 0) {
    return test_preg_rep(params[0].toString(), params[1].toString(),
                       params[2].toString());
  }
  if (strcasecmp(function, "sprintf") == 0) {
    return f_sprintf(params.size(), params[0],
                     params.slice(1, params.size() - 1, false));
  }

  // for TestExtSqlite3::test_sqlite3
  if (strcasecmp(function, "lower") == 0) {
    return f_strtolower(params[0]);
  }
  if (strcasecmp(function, "sumlen_step") == 0) {
    return params[0].toInt64() + f_strlen(params[2]);
  }
  if (strcasecmp(function, "sumlen_fini") == 0) {
    return params[0].toInt64();
  }

  // for TestExtSoap
  if (strcasecmp(function, "hello") == 0) {
    return "Hello World";
  }
  if (strcasecmp(function, "add") == 0) {
    return params[0].toInt32() + params[1].toInt32();
  }
  if (strcasecmp(function, "sub") == 0) {
    return params[0].toInt32() - params[1].toInt32();
  }
  if (strcasecmp(function, "sum") == 0) {
    int sum = 0;
    for (ArrayIter iter(params[0]); iter; ++iter) {
      sum += iter.second().toInt32();
    }
    return sum;
  }
  if (strcasecmp(function, "strlen") == 0) {
    return f_strlen(params[0]);
  }
  if (strcasecmp(function, "fault") == 0) {
    return Object((NEWOBJ(c_SoapFault)())->create("MyFault","My fault string"));
  }

  // for TestExtServer
  if (strcasecmp(function, "xbox_process_message") == 0) {
    return StringUtil::Reverse(params[0]);
  }

  return true;
}
Ejemplo n.º 10
0
void debugloop() {
    int key;
  a:
    if (!(debugds & 2))
        nextopcode();
    if (!(debugds & 1))
        nextspcopcode();

  b:
    // redrawing the display is always a good idea
    refresh();
    wrefresh(debugwin);

   key = getch();
   if (key >= 0 && key < 256)
       key = toupper(key);

   switch (key) {
   case KEY_F(1): // run
       execut = 1;
       return;

   case KEY_F(2): // debugsavestate
       statesaver();
       goto b;

   case KEY_F(4): // debugloadstate
       debugloadstate();
       goto a;

   case 27:       // exit
       return;

   case '\n':     // step
       goto e;


   /* Ported this but couldn't bring myself to commit it.
      pagefault said to remove it.
   case '-':      // skip opcode
   */

   case 'C':      // clear
       numinst = 0;
       goto a;

   case 'M':      // modify
   {
       WINDOW *w;
       unsigned addr, value, n;

       w = openwindow(7, 33, 11, 24, "    Enter Address : ");
       mvwaddstr(w, 3, 1,            "    Previous Value: ");
       mvwaddstr(w, 5, 1,            "    Enter Value   : ");

       wrefresh(w);

       echo();
       n = mvwscanw(w, 1, 21, "%x", &addr);
       noecho();

       if (n == 1) {
       mvwprintw(w, 3, 21, "%02x", memtabler8_wrapper(addr >> 16, addr));
       wrefresh(w);

       echo();
       n = mvwscanw(w, 5, 21, "%x", &value);
       noecho();

       if (n == 1) {
          memtablew8_wrapper(addr >> 16, addr, value);
       }}

       closewindow(w);
       goto b;
   }
Ejemplo n.º 11
0
void get_command(void)
{
	char com[255];

	int text_width, text_startx;
	allocated_block_t *allocated_block = NULL;
	int i = 0;
	int count = 0;

	WINDOW *command_win = NULL;
        List allocated_blocks = NULL;
	ListIterator results_i;

	if (params.commandline && !params.command) {
		printf("Configure won't work with commandline mode.\n");
		printf("Please remove the -c from the commandline.\n");
		bg_configure_ba_fini();
		exit(0);
	}

	if (working_cluster_rec) {
		char *cluster_name = slurm_get_cluster_name();
		if (strcmp(working_cluster_rec->name, cluster_name)) {
			xfree(cluster_name);
			endwin();
			printf("To use the configure option you must be on the "
			       "cluster the configure is for.\nCross cluster "
			       "support doesn't exist today.\nSorry for the "
			       "inconvenince.\n");
			bg_configure_ba_fini();
			exit(0);
		}
		xfree(cluster_name);
	}

	bg_configure_ba_setup_wires();

	color_count = 0;

	allocated_blocks = list_create(_destroy_allocated_block);

	if (params.commandline) {
		snprintf(com, sizeof(com), "%s", params.command);
		goto run_command;
	} else {
		/* make sure we don't get any noisy debug */
		ba_configure_set_ba_debug_flags(0);

		text_width = text_win->_maxx;
		text_startx = text_win->_begx;
		command_win = newwin(3, text_width - 1, LINES - 4,
				     text_startx + 1);
		curs_set(1);
		echo();
	}

	while (strcmp(com, "quit")) {
		clear_window(grid_win);
		print_grid();
		clear_window(text_win);
		box(text_win, 0, 0);
		box(grid_win, 0, 0);

		if (!params.no_header)
			_print_header_command();

		if (error_string != NULL) {
			i = 0;
			while (error_string[i] != '\0') {
				if (error_string[i] == '\n') {
					main_ycord++;
					main_xcord=1;
					i++;
				}
				mvwprintw(text_win,
					  main_ycord,
					  main_xcord,
					  "%c",
					  error_string[i++]);
				main_xcord++;
			}
			main_ycord++;
			main_xcord = 1;
			memset(error_string, 0, 255);
		}
		results_i = list_iterator_create(allocated_blocks);

		count = list_count(allocated_blocks)
			- (LINES-(main_ycord+5));

		if (count<0)
			count=0;
		i=0;
		while ((allocated_block = list_next(results_i)) != NULL) {
			if (i >= count)
				_print_text_command(allocated_block);
			i++;
		}
		list_iterator_destroy(results_i);

		wnoutrefresh(text_win);
		wnoutrefresh(grid_win);
		doupdate();
		clear_window(command_win);

		box(command_win, 0, 0);
		mvwprintw(command_win, 0, 3,
			  "Input Command: (type quit to change view, "
			  "exit to exit)");
		wmove(command_win, 1, 1);
		wgetstr(command_win, com);

		if (!strcmp(com, "exit")) {
			endwin();
			if (allocated_blocks)
				list_destroy(allocated_blocks);
			bg_configure_ba_fini();
			exit(0);
		}
	run_command:

		if (!strcmp(com, "quit") || !strcmp(com, "\\q")) {
			break;
		} else if (!strncasecmp(com, "layout", 6)) {
			_set_layout(com);
		} else if (!strncasecmp(com, "basepartition", 13)) {
			_set_base_part_cnt(com);
		} else if (!strncasecmp(com, "nodecard", 8)) {
			_set_nodecard_cnt(com);
		} else if (!strncasecmp(com, "resolve", 7) ||
			   !strncasecmp(com, "r ", 2)) {
			_resolve(com);
		} else if (!strncasecmp(com, "resume", 6)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "drain", 5)) {
			mvwprintw(text_win,
				main_ycord,
				main_xcord, "%s", com);
		} else if (!strncasecmp(com, "alldown", 7)) {
			_change_state_all_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "down", 4)) {
			_change_state_bps(com, NODE_STATE_DOWN);
		} else if (!strncasecmp(com, "allup", 5)) {
			_change_state_all_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "up", 2)) {
			_change_state_bps(com, NODE_STATE_IDLE);
		} else if (!strncasecmp(com, "remove", 6)
			|| !strncasecmp(com, "delete", 6)
			|| !strncasecmp(com, "drop", 4)) {
			_remove_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "create", 6)) {
			_create_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "copy", 4)
			|| !strncasecmp(com, "c ", 2)
			|| !strncasecmp(com, "c\0", 2)) {
			_copy_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "save", 4)) {
			_save_allocation(com, allocated_blocks);
		} else if (!strncasecmp(com, "load", 4)) {
			_load_configuration(com, allocated_blocks);
		} else if (!strncasecmp(com, "clear all", 9)
			|| !strncasecmp(com, "clear", 5)) {
			list_flush(allocated_blocks);
		} else {
			memset(error_string, 0, 255);
			sprintf(error_string, "Unknown command '%s'",com);
		}

		if (params.commandline) {
			bg_configure_ba_fini();
			exit(1);
		}
	}
	if (allocated_blocks)
		list_destroy(allocated_blocks);
	params.display = 0;
	noecho();

	clear_window(text_win);
	main_xcord = 1;
	main_ycord = 1;
	curs_set(0);
	print_date();
	get_job();
	return;
}
Ejemplo n.º 12
0
void curses_line_input_dialog(const char *prompt, char *answer, int buffer)
{
    int map_height, map_width, maxwidth, remaining_buf, winx, winy, count;
    WINDOW *askwin, *bwin;
    char input[buffer];
    char *tmpstr;
    int prompt_width = strlen(prompt) + buffer + 1;
    int prompt_height = 1;
    int height = prompt_height;

    maxwidth = term_cols - 2;

    if (iflags.window_inited) {
        curses_get_window_size(MAP_WIN, &map_height, &map_width);
        if ((prompt_width + 2) > map_width)
            maxwidth = map_width - 2;
    }

    if (prompt_width > maxwidth) {
        prompt_height = curses_num_lines(prompt, maxwidth);
        height = prompt_height;
        prompt_width = maxwidth;
        tmpstr = curses_break_str(prompt, maxwidth, prompt_height);
        remaining_buf = buffer - (strlen(tmpstr) - 1);
        if (remaining_buf > 0 ) {
            height += (remaining_buf / prompt_width);
            if ((remaining_buf % prompt_width) > 0) {
                height++;
            }
        }
    }

    if (iflags.window_inited) {
        bwin = curses_create_window(prompt_width, height, UP);
        wrefresh(bwin);
        getbegyx(bwin, winy, winx);
        askwin = newwin(height, prompt_width, winy + 1, winx + 1);
    } else {
        bwin = curses_create_window(prompt_width, height, CENTER);
        wrefresh(bwin);
        getbegyx(bwin, winy, winx);
        askwin = newwin(height, prompt_width, winy + 1, winx + 1);
    }
    for (count = 0; count < prompt_height; count++) {
        tmpstr = curses_break_str(prompt, maxwidth, count + 1);
        if (count == (prompt_height - 1)) {  /* Last line */
            mvwprintw(askwin, count, 0, "%s ", tmpstr);
        } else {
            mvwaddstr(askwin, count, 0, tmpstr);
        }
        free(tmpstr);
    }

    echo();
    curs_set(1);
    wgetnstr(askwin, input, buffer-1);
    curs_set(0);
    strcpy(answer, input);
    werase(bwin);
    delwin(bwin);
    curses_destroy_win(askwin);
    noecho();
}
Ejemplo n.º 13
0
/*
 * Erase a character or line
 * FIXME: Needs support for WERASE and ECHOPRT.
 * FIXME: Some of the tests should check for IEXTEN, too.
 */
static void
erase (struct rtems_termios_tty *tty, int lineFlag)
{
	if (tty->ccount == 0)
		return;
	if (lineFlag) {
		if (!(tty->termios.c_lflag & ECHO)) {
			tty->ccount = 0;
			return;
		}
		if (!(tty->termios.c_lflag & ECHOE)) {
			tty->ccount = 0;
			echo (tty->termios.c_cc[VKILL], tty);
			if (tty->termios.c_lflag & ECHOK)
				echo ('\n', tty);
			return;
		}
	}
	while (tty->ccount) {
		unsigned char c = tty->cbuf[--tty->ccount];

		if (tty->termios.c_lflag & ECHO) {
			if (!lineFlag && !(tty->termios.c_lflag & ECHOE)) {
				echo (tty->termios.c_cc[VERASE], tty);
			}
			else if (c == '\t') {
				int col = tty->read_start_column;
				int i = 0;

				/*
				 * Find the character before the tab
				 */
				while (i != tty->ccount) {
					c = tty->cbuf[i++];
					if (c == '\t') {
						col = (col | 7) + 1;
					}
					else if (iscntrl (c)) {
						if (tty->termios.c_lflag & ECHOCTL)
							col += 2;
					}
					else {
						col++;
					}
				}

				/*
				 * Back up over the tab
				 */
				while (tty->column > col) {
					rtems_termios_puts ("\b", 1, tty);
					tty->column--;
				}
			}
			else {
				if (iscntrl (c) && (tty->termios.c_lflag & ECHOCTL)) {
					rtems_termios_puts ("\b \b", 3, tty);
					if (tty->column)
						tty->column--;
				}
				if (!iscntrl (c) || (tty->termios.c_lflag & ECHOCTL)) {
					rtems_termios_puts ("\b \b", 3, tty);
					if (tty->column)
						tty->column--;
				}
			}
		}
		if (!lineFlag)
			break;
	}
}
Ejemplo n.º 14
0
main(){
	char *p;
	p = echo();
	printf("return: %s\n",p);
	return 0;
}
Ejemplo n.º 15
0
int mod_command(char *q, char *args)
{
        if( q==NULL )
        {
                ;
        }
        else if( strcmp(q, "edit")==0 )
        {
                editmode = editmode ? 0 : 1;
                v_center = editmode ? 0 : 1;
                return 0;
        }
        else if( strcmp(q, "model")==0 )
        {
                setmodel = safe_atoi(tok(args, " ")); // FIXME: lame hack
                return 0;
        }
        else if( strcmp(q, "bounds")==0 || strcmp(q, "blocksize")==0 )
        {
                size_t n = 0;
                int x = safe_atoi(tok(args, " "));
                int y = safe_atoi(tok(args, " "));
                int z = safe_atoi(tok(args, " "));
                char chr = strcmp(q, "bounds")==0 ? 'b' : 'z';

                if( !x || !y || !z )
                {
                        context *co = fr[hotfr%maxframes].objs[mycontext].data; // FIXME is mycontext always set here?
                        if( chr == 'b' )
                                echo("The current bounds are (X,Y,Z): %d %d %d", co->x, co->y, co->z);
                        else
                                echo("The current blocksize is (X,Y,Z): %d %d %d", co->bsx, co->bsy, co->bsz);
                        return 0;
                }

                memset(&magic_c, 0, sizeof magic_c);
                packbytes(magic_c.data, chr, &n, 1);
                packbytes(magic_c.data,   x, &n, 4);
                packbytes(magic_c.data,   y, &n, 4);
                packbytes(magic_c.data,   z, &n, 4);
                magic_c.datasz = n;
                magic_c.flags |= CMDF_DATA;
                magic_c.cmd = CMDT_0CON; // console command
                putcmd(-1, -1, -1);
                return 0;
        }
        else if( strcmp(q, "tilespacing")==0 )
        {
                size_t n = 0;
                int tileuw = safe_atoi(tok(args, " "));
                int tileuh = safe_atoi(tok(args, " "));

                if( !tileuw || !tileuh )
                {
                        context *co = fr[hotfr%maxframes].objs[mycontext].data;
                        echo("The current tilespacing is (W,H): %d %d", co->tileuw, co->tileuh);
                        return 0;
                }

                memset(&magic_c, 0, sizeof magic_c);
                packbytes(magic_c.data,    't', &n, 1);
                packbytes(magic_c.data, tileuw, &n, 4);
                packbytes(magic_c.data, tileuh, &n, 4);
                magic_c.datasz = n;
                magic_c.flags |= CMDF_DATA;
                magic_c.cmd = CMDT_0CON;
                putcmd(-1, -1, -1);
                return 0;
        }
        else if( strcmp(q, "orthographic")==0 || strcmp(q, "dimetric")==0 )
        {
                size_t n = 0;
                memset(&magic_c, 0, sizeof magic_c);
                packbytes(magic_c.data, q[0], &n, 1);
                magic_c.datasz = n;
                magic_c.flags |= CMDF_DATA;
                magic_c.cmd = CMDT_0CON;
                putcmd(-1, -1, -1);
                return 0;
        }
        else if( strcmp(q, "resprite")==0 )
        {
                reload_sprites();
                renumber_sprites();
                echo("Was %d sprites, now %d sprites.", old_spr_count, spr_count);
                unload_sprites(old_sprites, old_spr_count);
                return 0;
        }

        return 1;
}
Ejemplo n.º 16
0
// A function to create the "create new event" page.
// This function is the most crucial part in the program which is handling user inputs/data
void create_new_event(bool edit, int z_index ) {
	// This will enable the input to be shown to the user when type.
	resize_term(40, 80);
	echo();

	// Variables
	char rawday, rawname, rawloc, rawhour, rawminute;	// Raw variables used for pdcurses function
	int confirmation;
	bool eventloop = false;									// Indicator for the loop
	int n_day, n_hour, n_minute;							// Day variable which is to be selected by the user

	// Loop until get a data to be saved in data object
	while (eventloop == false) {
		// Empty the console, add titlebar and redraw all.
		erase();
		titlebar();
		refresh();
		raw();

		attron(COLOR_PAIR(3));
		if (edit == true) {
			mvprintw(2, 1, "Edit Event");
			mvprintw(3, 1, "----------");
		}
		else {
			mvprintw(2, 1, "Create New Event");
			mvprintw(3, 1, "----------------");
		}

		mvprintw(20, 1, "Date\t\t:");
		mvprintw(22, 1, "Time\t\t:");
		mvprintw(24, 1, "Event name\t:");
		mvprintw(26, 1, "Location\t:");
		//mvprintw(28, 1, "Description\t:");
		
		// Disabled due to BUG002
		// A small window for description to fit in the text in nice allignment.
		/*WINDOW *wdesc;
		wdesc = newwin(3, 60, 28, 18);
		wattron(wdesc, COLOR_PAIR(3));*/

		// Show calendar, without any inputs
		mvprintw(4, 36, "Calendar");
		show_calendar(false, 14, 6);

		// Show status window (used to deliver message to the user about error, etc.)
		statuswin();

		// Update text in status window
		update_status("Please select the day for the event...\n\nTo go back, press ESC and ENTER",6);
		//refresh();

		// Do this loop until the program obtained a valid day

		do {
			mvhline(20, 18, ' ', 3);											// Clear a small portion of the console
			mvprintw(20, 21, "%s %i", mon_name(selected_mon), selected_year);	// Print the month and year
			mvgetnstr(20, 18, &rawday, 2);										// User input of the day
			if (rawday == 27) menu();												// If user pressed esc and enter, the program will go back to main menu
			n_day = atoi(&rawday);
			//n_day = day;														// A C-function to convert char * to int
			if (n_day == 0 || n_day > max_day_in_month) { update_status("Invalid day. Please enter a valid DAY in the selected month.\n\nTo go back, press ESC and ENTER.",5); }			// Inform user if the day not valid
			refresh();															// Redraw
		} while (n_day == 0 || n_day > max_day_in_month);						// Check if the day valid or not

		// Got a nice and valid n_day and print again to the screen.
		mvhline(20, 18, ' ', 60);												// Refresh the line
		mvprintw(20, 18, "%i %s %i", n_day, mon_name(selected_mon), selected_year);

		// Update to the current status.
		update_status("Please enter the hour in 24 hours...\nIf you enter some string, the result will be 0.", 6);

		// A loop that handle the time input. Runs loop until it gets the valid time.
		do {

			mvhline(22, 18, ' ', 6);											// Clear the line
			mvgetnstr(22, 18, &rawhour, 2);										// Get hour from user
			if (rawhour == 27) menu();											// If user input is ESC then go back to menu
			n_hour = atoi(&rawhour);											// Convert from char to int
			if ( !(n_hour >= 0 && n_hour < 24) ) {								// Check for valid hour
				update_status("Invalid hour. Enter a number in between 0-23. Please try again...", 5);
				continue;
			}
			else {
				mvprintw(22, 20, ":");
				update_status("Please enter the minute...\nIf you enter some string, the result will be 0.", 6);
				do {
					mvhline(22, 21, ' ', 3);
					mvgetnstr(22, 21, &rawminute, 2);
					if (rawminute == 27) menu();
					n_minute = atoi(&rawminute);								// Convert from char to int
					if (!(n_minute >= 0 && n_minute < 60)) {					// Check for valid minutes
						update_status("Invalid minute. Type a number in between 0-59. Please try again...", 5);
						continue;
					}
					else break;
				} while (1);
				break;
			}
		} while (1);

		// Print the time nicely.
		mvhline(22, 18, ' ', 6);
		formatted_time(22, 18, n_hour, n_minute);		// Print time in formatted form xx:yy

		// Update the status
		update_status("Now fill the name, location and description of the event.");

		// Get event name, location and description		// BUG001
		mvgetnstr(24, 18, &rawname, 28);				// First program bug detected here (Read below for more)
		data.save_name(&rawname);						// This function is used to copy rawname char * to another variable in normal char type. It copy the data to a more reliable variable.
														// This is because to prevent memory leak or maybe something else that causes the data in other the pointer (this is bad due to it affect other variable as well) overwritten by the typed data. Approximate more than 11 characters will cause the memory leak -- TESTED)
		mvgetnstr(26, 18, &rawloc, 28);					// Also, to prevent this bug, this function data.save_*** is called right after the user input the data.
		data.save_loc(&rawloc);							// This problem maybe related to the pdcurses library bug that cause the memory leak which affect other variables too.

		//mvwgetnstr(wdesc, 0, 0, &rawdesc, 28);		// BUG002
		//data.save_desc(&rawdesc);						// The program will crash when number of characters more than 28 chars. The cause still unknown. To fix whether to create another custom function to handle input (which is long) or decrease the numbers of characters (which is the quickest way to solve).

		refresh();

		// Clear status
		werase(wstatus);
		wrefresh(wstatus);

		// User confirmation
		mvprintw(32, 1, "Are you sure? (Y/N): ");
		refresh();

		// A loop to check only y/Y/n/N are allowed as a user input
		while (1) {
			mvhline(32, 22, ' ', 1);
			confirmation = getch();
			if (confirmation == 780 || confirmation == 110 || confirmation == 121 || confirmation == 891) { break; }
		}

		// If user type y/Y, the the loop ends
		if (confirmation == 121 || confirmation == 891){
			eventloop = true;								// To ensure that this will break the loop and will not continue anymore
			data.day = n_day;								// Save user inputs
			data.year = selected_year;
			data.nmon = selected_mon;

			// LAB-2
			data.hour = n_hour;
			data.min = n_minute;

			if (edit == true) {
				myVector.erase(myVector.begin() + z_index);
				myVector.insert(myVector.begin() + z_index, data);
				list_events();
			}
			else {
				myVector.push_back(data);
				event_saved = true;								// Tells the program about the saved data
				break;
			}
		}
	}

	if (edit == false) menu();
}
Ejemplo n.º 17
0
void mod_setup(unsigned int setupfr)
{
        //default key bindings
        exec_commands("defaults");

        //make the mother object
        fr[setupfr].objs[0] = (object){ mother_type, 0, 0, sizeof(mother), malloc(sizeof(mother)) };
        memset( fr[setupfr].objs[0].data, 0, sizeof(mother) );

        //make default context object (map)
        fr[setupfr].objs[1] = (object){ context_type, OBJF_REFC, 0, sizeof(context), malloc(sizeof(context)) };
        context *co = fr[setupfr].objs[1].data;
        co->bsx = co->bsy = co->bsz = 16;
        co->x   = co->y   = co->z   = 15;
        co->tileuw = 48;
        co->tileuh = 24;
        co->projection = DIMETRIC;
        int volume = co->x * co->y * co->z;
        co->map  = hack_map  = malloc( (sizeof *co->map ) * volume ); //FIXME remove hack
        co->dmap = hack_dmap = malloc( (sizeof *co->dmap) * volume );
        memset( co->map,  0, (sizeof *co->map ) * volume );
        memset( co->dmap, 0, (sizeof *co->dmap) * volume );
        int i;
        for( i=0; i<volume; i++ )
        {
                co->map[ i].spr   = 0;
                co->dmap[i].flags = CBF_NULL;
        }
        load_context("noise", 1, setupfr); //load a default map

        //make some dummys
        #define MAYBE_A_DUMMY(i,x,y,w,h) {                                                               \
                dummy *du;                                                                               \
                fr[setupfr].objs[i+20].type = dummy_type;                                                \
                fr[setupfr].objs[i+20].flags = OBJF_POS|OBJF_VEL|OBJF_HULL|OBJF_VIS|OBJF_PLAT|OBJF_CLIP| \
                                               OBJF_BNDX|OBJF_BNDZ|OBJF_BNDB;                            \
                fr[setupfr].objs[i+20].context = 1;                                                      \
                fr[setupfr].objs[i+20].size = sizeof *du;                                                \
                du = fr[setupfr].objs[i+20].data = malloc(sizeof *du);                                   \
                du->pos = (V){x*8,y*8,0};                                                                \
                du->vel = (V){0,0,0};                                                                    \
                du->hull[0] = (V){-w*8,-h*8,-8};                                                         \
                du->hull[1] = (V){ w*8, h*8, 8};                                                         \
                du->model = 0;                                                                           }
        MAYBE_A_DUMMY(20,  3,-25,1,1);
        MAYBE_A_DUMMY(21,  3,-20,1,1);
        MAYBE_A_DUMMY(22,  3,-15,1,1);
        MAYBE_A_DUMMY(23,  3,-10,1,1);
        MAYBE_A_DUMMY(24,  5,-15,1,1);
        MAYBE_A_DUMMY(25,  9,-15,1,1);
        MAYBE_A_DUMMY(26, 43,-20,1,1);
        MAYBE_A_DUMMY(27, 43,-15,1,1);
        MAYBE_A_DUMMY(28, 45,-25,1,1);
        MAYBE_A_DUMMY(29, 45,-20,1,1);
        MAYBE_A_DUMMY(30, 45,-15,1,1);
        #undef MAYBE_A_DUMMY

        fr[setupfr+1].cmds[0].flags |= CMDF_NEW; //server is a client

        echo("Default controls: \\#F80A, S, Numpad Arrows, F11");
}
Ejemplo n.º 18
0
/*!
  Outputs a escaped string of the HTML attribute \a attr to
  a view template.
*/
QString TActionView::eh(const THtmlAttribute &attr)
{
    return echo(THttpUtility::htmlEscape(attr.toString().trimmed()));
}
Ejemplo n.º 19
0
void f_debug_print_backtrace(int64_t options /* = 0 */,
                             int64_t limit /* = 0 */) {
  bool ignore_args = options & DEBUG_BACKTRACE_IGNORE_ARGS;
  echo(debug_string_backtrace(true, ignore_args, limit));
}
Ejemplo n.º 20
0
static void
rmclass(char *aclass, int rm_remote, char *a_zoneName)
{
	struct cfent	*ept;
	FILE	*fp;
	char	tmpfile[PATH_MAX];
	char	script[PATH_MAX];
	int	i;
	char	*tmp_path;
	char	*save_path = NULL;
	struct stat st;

	if (aclass == NULL) {
		for (i = 0; i < eptnum; i++) {
			if (eptlist[i] != NULL) {
				rmclass(eptlist[i]->pkg_class,
				    rm_remote, a_zoneName);
			}
		}
		return;
	}

	/* locate class action script to execute */
	(void) snprintf(script, sizeof (script), "%s/r.%s", pkgbin, aclass);
	if (access(script, F_OK) != 0) {
		(void) snprintf(script, sizeof (script), "%s/r.%s",
		    PKGSCR, aclass);
		if (access(script, F_OK) != 0)
			script[0] = '\0';
	}
	if (script[0] != '\0') {
		int td;

		(void) snprintf(tmpfile, sizeof (tmpfile), "%s/RMLISTXXXXXX",
		    tmpdir);
		td = mkstemp(tmpfile);
		if (td == -1) {
			progerr(ERR_TMPFILE);
			quit(99);
		}
		if ((fp = fdopen(td, "w")) == NULL) {
			progerr(ERR_WTMPFILE, tmpfile);
			quit(99);
		}
	}

	if (a_zoneName == (char *)NULL) {
		echo(MSG_PKGREMOVE_REMPATHCLASS_GZ, aclass);
	} else {
		echo(MSG_PKGREMOVE_REMPATHCLASS_LZ, aclass, a_zoneName);
	}

	/* process paths in reverse order */
	i = eptnum;
	while (--i >= 0) {
		ept = eptlist[i];

		if ((ept == NULL) || strcmp(aclass, ept->pkg_class)) {
			continue;
		}

		/* save the path, and prepend the ir */
		if (is_an_inst_root()) {
			save_path = ept->path;
			tmp_path = fixpath(ept->path);
			ept->path = tmp_path;
		}

		if (!ept->ftype || (ept->ftype == '^' && !script[0])) {
			/*
			 * A path owned by more than one package is marked with
			 * a NULL ftype (seems odd, but that's how it's
			 * done). Such files are sacro sanct. Shared editable
			 * files are a special case, and are marked with an
			 * ftype of '^'. These files should only be ignored if
			 * no class action script is present. It is the CAS's
			 * responsibility to not remove the editable object.
			 */
			echo(MSG_SHARED, ept->path);
		} else if (ept->pinfo->status == SERVED_FILE && !rm_remote) {
			/*
			 * If the path is provided to the client from a
			 * server, don't remove anything unless explicitly
			 * requested through the "-f" option.
			 */
			echo(MSG_SERVER, ept->path);
		} else if (script[0]) {
			/*
			 * If there's a class action script, just put the
			 * path name into the list.
			 */
			(void) fprintf(fp, "%s\n", ept->path);
		} else if (strchr("dx", ept->ftype) != NULL ||
		    (lstat(ept->path, &st) == 0 && S_ISDIR(st.st_mode))) {
			/* Directories are rmdir()'d. */

			if (rmdir(ept->path)) {
				if (errno == EBUSY) {
					echo(MSG_DIRBUSY, ept->path);
				} else if (errno == EEXIST) {
					echo(MSG_NOTEMPTY, ept->path);
				} else if (errno != ENOENT) {
					progerr(ERR_RMDIR, ept->path);
					warnflag++;
				}
			} else {
				if (ept->pinfo->status == SERVED_FILE) {
					echo(MSG_RMSRVR, ept->path);
				} else {
					echo("%s", ept->path);
				}
			}

		} else {
			/*
			 * Before removing this object one more
			 * check should be done to assure that a
			 * shared object is not removed.
			 * This can happen if the original object
			 * was incorrectly updated with the
			 * incorrect class identifier.
			 * This handles pathologcal cases that
			 * weren't handled above.
			 */
			if (ept->npkgs > 1) {
				echo(MSG_SHARED, ept->path);
				continue;
			}

			/* Regular files are unlink()'d. */

			if (unlink(ept->path)) {
				if (errno != ENOENT) {
					progerr(ERR_RMPATH, ept->path);
					warnflag++;
				}
			} else {
				if (ept->pinfo->status == SERVED_FILE) {
					echo(MSG_RMSRVR, ept->path);
				} else {
					echo("%s", ept->path);
				}
			}
		}

		/* restore the original path */

		if (is_an_inst_root()) {
			ept->path = save_path;
		}

		/*
		 * free memory allocated for this entry memory used for
		 * pathnames will be freed later by a call to pathdup()
		 */

		if (eptlist[i]) {
			free(eptlist[i]);
		}
		eptlist[i] = NULL;
	}
	if (script[0]) {
		(void) fclose(fp);
		set_ulimit(script, ERR_CASFAIL);
		if (pkgverbose)
			ckreturn(pkgexecl(tmpfile, CAS_STDOUT, CAS_USER,
			    CAS_GRP, SHELL, "-x", script, NULL),
			    ERR_CASFAIL);
		else
			ckreturn(pkgexecl(tmpfile, CAS_STDOUT, CAS_USER,
			    CAS_GRP, SHELL, script, NULL),
			    ERR_CASFAIL);
		clr_ulimit();
		if (isfile(NULL, tmpfile) == 0) {
			if (unlink(tmpfile) == -1)
				progerr(ERR_RMPATH, tmpfile);
		}
	}
}
Ejemplo n.º 21
0
int main()
{
    echo();

    return 0;
}
Ejemplo n.º 22
0
int
main(int argc, char *argv[])
{
	FILE		*fp;
	char		*abi_comp_ptr;
	char		*abi_sym_ptr;
	char		*p;
	char		*prog_full_name = NULL;
	char		*pt;
	char		*value;
	char		*vfstab_file = NULL;
	char		*zoneName = (char *)NULL;
	char		cmdbin[PATH_MAX];
	char		param[MAX_PKG_PARAM_LENGTH];
	char		path[PATH_MAX];
	char		script[PATH_MAX];
	int		c;
	int		err;
	int		fd;
	int		i;
	int		map_client = 1;
	int		n;
	int		nodelete = 0; 	/* do not delete file or run scripts */
	int		pkgrmremote = 0;	/* dont remove remote objects */
	struct sigaction	nact;
	struct sigaction	oact;
	PKGserver	pkgserver = NULL;
	VFP_T		*tmpfp;

	/* reset contents of all default paths */

	(void) memset(cmdbin, '\0', sizeof (cmdbin));

	/* initialize locale environment */

	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	/* initialize program name */

	prog_full_name = argv[0];
	(void) set_prog_name(argv[0]);

	/* tell spmi zones interface how to access package output functions */

	z_set_output_functions(echo, echoDebug, progerr);

	/* exit if not root */

	if (getuid()) {
		progerr(ERR_NOT_ROOT, get_prog_name());
		exit(1);
		/* NOTREACHED */
	}

	/* Read PKG_INSTALL_ROOT from the environment, if it's there. */

	if (!set_inst_root(getenv("PKG_INSTALL_ROOT"))) {
		progerr(ERR_ROOT_SET);
		exit(1);
	}

	pkgserversetmode(DEFAULTMODE);

	/* parse command line options */

	while ((c = getopt(argc, argv, "?Aa:b:FMN:nO:oR:V:vy")) != EOF) {
		switch (c) {
		/*
		 * Same as pkgrm: Allow admin to remove package objects from
		 * a shared area from a reference client.
		 */
		case 'A':
			pkgrmremote++;
			break;

		/*
		 * Same as pkgrm: Use the installation
		 * administration file, admin, in place of the
		 * default admin file. pkgrm first looks in the
		 * current working directory for the administration
		 * file.  If the specified administration file is not
		 * in the current working directory, pkgrm looks in
		 * the /var/sadm/install/admin directory for the
		 * administration file.
		 */
		case 'a':
			admnfile = flex_device(optarg, 0);
			break;

		/*
		 * Same as pkgrm: location where package executables
		 * can be found - default is /usr/sadm/install/bin.
		 */
		case 'b':
			if (!path_valid(optarg)) {
				progerr(ERR_PATH, optarg);
				exit(1);
			}
			if (isdir(optarg) != 0) {
				char *p = strerror(errno);
				progerr(ERR_CANNOT_USE_DIR, optarg, p);
				exit(1);
			}
			(void) strlcpy(cmdbin, optarg, sizeof (cmdbin));
			break;

		/*
		 * Same as pkgrm: suppresses the removal of any
		 * files and any class action scripts, and suppresses
		 * the running of any class action scripts.  The
		 * package files remain but the package looks like it
		 * is not installed. This is mainly for use by the
		 * upgrade process.
		 */
		case 'F':
			nodelete++;
			break;

		/*
		 * Same as pkgrm: Instruct pkgrm not to use the
		 * $root_path/etc/vfstab file for determining the
		 * client's mount points. This option assumes the
		 * mount points are correct on the server and it
		 * behaves consistently with Solaris 2.5 and earlier
		 * releases.
		 */
		case 'M':
			map_client = 0;
			break;

		/*
		 * Different from pkgrm: specify program name to use
		 * for messages.
		 */
		case 'N':
			(void) set_prog_name(optarg);
			break;

		/*
		 * Same as pkgrm: package removal occurs in
		 * non-interactive mode.  Suppress output of the list of
		 * removed files. The default mode is interactive.
		 */
		case 'n':
			nointeract++;
			(void) echoSetFlag(B_FALSE);
			break;

		/*
		 * Almost same as pkgrm: the -O option allows the behavior
		 * of the package tools to be modified. Recognized options:
		 * -> debug
		 * ---> enable debugging output
		 * -> preremovecheck
		 * ---> perform a "pre removal" check of the specified
		 * ---> package - suppress all regular output and cause a
		 * ---> series of one or more "name=value" pair format lines
		 * ---> to be output that describes the "removability" of
		 * ---> the specified package
		 * -> enable-hollow-package-support
		 * --> Enable hollow package support. When specified, for any
		 * --> package that has SUNW_PKG_HOLLOW=true:
		 * --> Do not calculate and verify package size against target
		 * --> Do not run any package procedure or class action scripts
		 * --> Do not create or remove any target directories
		 * --> Do not perform any script locking
		 * --> Do not install or uninstall any components of any package
		 * --> Do not output any status or database update messages
		 */
		case 'O':
			for (p = strtok(optarg, ","); p != (char *)NULL;
			    p = strtok(NULL, ",")) {

				/* process debug option */

				if (strcmp(p, "debug") == 0) {
					/* set debug flag/enable debug output */
					debugFlag = B_TRUE;
					(void) echoDebugSetFlag(debugFlag);

					/* debug info on arguments to pkgadd */
					for (n = 0; n < argc && argv[n]; n++) {
						echoDebug(DBG_ARG, n, argv[n]);
					}

					continue;
				}

				/* process enable-hollow-package-support opt */

				if (strcmp(p,
				    "enable-hollow-package-support") == 0) {
					set_depend_pkginfo_DB(B_TRUE);
					continue;
				}

				/* process preremovecheck option */

				if (strcmp(p, "preremovecheck") == 0) {
					preremoveCheck = B_TRUE;
					nointeract++;	/* -n */
					nodelete++;	/* -F */
					quitSetSilentExit(B_TRUE);
					continue;
				}

				/* process addzonename option */

				if (strcmp(p, "addzonename") == 0) {
					zoneName = z_get_zonename();
					quitSetZoneName(zoneName);
					continue;
				}

				/* process parent-zone-name option */

				if (strncmp(p, PARENTZONENAME,
				    PARENTZONENAME_LEN) == 0) {
					parentZoneName = p+PARENTZONENAME_LEN;
					continue;
				}

				/* process parent-zone-type option */

				if (strncmp(p, PARENTZONETYPE,
				    PARENTZONETYPE_LEN) == 0) {
					parentZoneType = p+PARENTZONETYPE_LEN;
					continue;
				}

				if (strncmp(p, PKGSERV_MODE,
				    PKGSERV_MODE_LEN) == 0) {
					pkgserversetmode(pkgparsemode(p +
					    PKGSERV_MODE_LEN));
					continue;
				}
				/* option not recognized - issue warning */

				progerr(ERR_INVALID_O_OPTION, p);
				continue;
			}
			break;

		/*
		 * Different from pkgrm: This is an old non-ABI package
		 */

		case 'o':
			script_in = PROC_XSTDIN;
			break;

		/*
		 * Same as pkgrm: defines the full path name of a
		 * directory to use as the root_path.  All files,
		 * including package system information files, are
		 * relocated to a directory tree starting in the
		 * specified root_path.
		 */
		case 'R':
			if (!set_inst_root(optarg)) {
				progerr(ERR_ROOT_CMD);
				exit(1);
			}
			break;

		/*
		 * Same as pkgrm: allow admin to establish the client
		 * filesystem using a vfstab-like file of stable format.
		 */
		case 'V':
			vfstab_file = flex_device(optarg, 2);
			map_client = 1;
			break;

		/*
		 * Same as pkgrm: trace all of the scripts that
		 * get executed by pkgrm, located in the
		 * pkginst/install directory. This option is used for
		 * debugging the procedural and non-procedural
		 * scripts.
		 */
		case 'v':
			pkgverbose++;
			break;

		/*
		 * Different from pkgrm: process this package using
		 * old non-ABI symlinks
		 */
		case 'y':
			set_nonABI_symlinks();
			break;

		default:
			usage();
			/*NOTREACHED*/
			/*
			 * Although usage() calls a noreturn function,
			 * needed to add return (1);  so that main() would
			 * pass compilation checks. The statement below
			 * should never be executed.
			 */
			return (1);
		}
	}

	/*
	 * ********************************************************************
	 * validate command line options
	 * ********************************************************************
	 */

	(void) echoDebugSetFlag(debugFlag);
	(void) log_set_verbose(debugFlag);

	if (z_running_in_global_zone()) {
		echoDebug(DBG_ENTRY_IN_GZ, prog_full_name);
	} else {
		echoDebug(DBG_ENTRY_IN_LZ, prog_full_name, getzoneid(),
		    z_get_zonename());
	}

	/* establish cmdbin path */

	if (cmdbin[0] == '\0') {
		(void) strlcpy(cmdbin, PKGBIN, sizeof (cmdbin));
	}

	/* Read the mount table */

	if (get_mntinfo(map_client, vfstab_file)) {
		quit(99);
	}

	/*
	 * This function defines the standard /var/... directories used later
	 * to construct the paths to the various databases.
	 */

	set_PKGpaths(get_inst_root());

	/*
	 * If this is being removed from a client whose /var filesystem is
	 * mounted in some odd way, remap the administrative paths to the
	 * real filesystem. This could be avoided by simply mounting up the
	 * client now; but we aren't yet to the point in the process where
	 * modification of the filesystem is permitted.
	 */
	if (is_an_inst_root()) {
		int fsys_value;

		fsys_value = fsys(get_PKGLOC());
		if (use_srvr_map_n(fsys_value))
			set_PKGLOC(server_map(get_PKGLOC(), fsys_value));

		fsys_value = fsys(get_PKGADM());
		if (use_srvr_map_n(fsys_value))
			set_PKGADM(server_map(get_PKGADM(), fsys_value));
	} else {
		pkgrmremote = 0;	/* Makes no sense on local host. */
	}

	/*
	 * hook SIGINT and SIGHUP interrupts into quit.c's trap handler
	 */

	/* hold SIGINT/SIGHUP interrupts */

	(void) sighold(SIGHUP);
	(void) sighold(SIGINT);

	/* connect quit.c:trap() to SIGINT */

	nact.sa_handler = quitGetTrapHandler();
	nact.sa_flags = SA_RESTART;
	(void) sigemptyset(&nact.sa_mask);

	(void) sigaction(SIGINT, &nact, &oact);

	/* connect quit.c:trap() to SIGHUP */

	nact.sa_handler = quitGetTrapHandler();
	nact.sa_flags = SA_RESTART;
	(void) sigemptyset(&nact.sa_mask);

	(void) sigaction(SIGHUP, &nact, &oact);

	/* release hold on signals */

	(void) sigrelse(SIGHUP);
	(void) sigrelse(SIGINT);

	pkginst = argv[optind++];
	if (optind != argc) {
		usage();
	}

	/* validate package software database (contents) file */

	if (vcfile() == 0) {
		quit(99);
	}

	/*
	 * Acquire the package lock - currently at "remove initialization"
	 */

	if (!lockinst(get_prog_name(), pkginst, "remove-initial")) {
		quit(99);
	}

	/* establish temporary directory to use */

	tmpdir = getenv("TMPDIR");
	if (tmpdir == NULL) {
		tmpdir = P_tmpdir;
	}

	echoDebug(DBG_PKGREMOVE_TMPDIR, tmpdir);

	/*
	 * Initialize installation admin parameters by reading
	 * the adminfile.
	 */

	echoDebug(DBG_PKGREMOVE_ADMINFILE, admnfile ? admnfile : "");
	setadminFile(admnfile);

	/*
	 * about to perform first operation that could be modified by the
	 * preremove check option - if preremove check is selected (that is,
	 * only gathering dependencies), then output a debug message to
	 * indicate that the check is beginning. Also turn echo() output
	 * off and set various other flags.
	 */

	if (preremoveCheck == B_TRUE) {
		(void) echoSetFlag(B_FALSE);
		echoDebug(DBG_PKGREMOVE_PRERMCHK, pkginst ? pkginst : "",
		    zoneName ? zoneName : "global");
		rcksetPreremoveCheck(B_TRUE);
		rcksetZoneName(zoneName);
	}

	(void) snprintf(pkgloc, sizeof (pkgloc), "%s/%s", get_PKGLOC(),
	    pkginst);
	(void) snprintf(pkgbin, sizeof (pkgbin), "%s/install", pkgloc);
	(void) snprintf(rlockfile, sizeof (rlockfile), "%s/!R-Lock!", pkgloc);

	if (chdir(pkgbin)) {
		progerr(ERR_CHDIR, pkgbin);
		quit(99);
	}

	echo(MSG_PREREMOVE_REMINST, pkginst);

	/*
	 * if a lock file is present, then a previous attempt to remove this
	 * package may have been unsuccessful.
	 */

	if (access(rlockfile, F_OK) == 0) {
		echo(ERR_UNSUCC);
		echoDebug(DBG_PKGINSTALL_HAS_LOCKFILE, pkginst, rlockfile,
		    zoneName ? zoneName : "global");
	}

	/*
	 * Process all parameters from the pkginfo file
	 * and place them in the execution environment
	 */

	/* Add DB retreival of the pkginfo parameters here */
	(void) snprintf(path, sizeof (path), "%s/pkginfo", pkgloc);
	if ((fp = fopen(path, "r")) == NULL) {
		progerr(ERR_PKGINFO, path);
		quit(99);
	}

	/* Mount up the client if necessary. */
	if (map_client && !mount_client()) {
		logerr(MSG_MANMOUNT);
	}

	/* Get mount point of client */
	client_mntdir = getenv("CLIENT_MNTDIR");

	getuserlocale();

	/*
	 * current environment has been read; clear environment out
	 * so putparam() can be used to populate the new environment
	 * to be passed to any executables/scripts.
	 */

	environ = NULL;

	if (nonABI_symlinks()) {
		putparam("PKG_NONABI_SYMLINKS", "TRUE");
	}

	/*
	 * read the pkginfo file and fix any PKGSAV path - the correct
	 * install_root will be prepended to the existing path.
	 */

	param[0] = '\0';
	while (value = fpkgparam(fp, param)) {
		int validx = 0;
		char *newvalue;

		/* strip out any setting of PATH */

		if (strcmp(param, "PATH") == 0) {
			free(value);
			param[0] = '\0';
			continue;
		}

		/* if not PKGSAV then write out unchanged */

		if (strcmp(param, "PKGSAV") != 0) {
			putparam(param, value);
			free(value);
			param[0] = '\0';
			continue;
		}

		/*
		 * PKGSAV parameter found - interpret the directory:
		 * If in host:path format or marked with the leading "//",
		 * then there is no client-relative translation - take it
		 * literally later rather than use fixpath().
		 */

		if (strstr(value, ":/")) {
			/* no modification needed */
			validx = 0;
		} else if (strstr(value, "//") == value) {
			validx = 1;
		} else if (is_an_inst_root()) {
			/* This PKGSAV needs to be made client-relative. */
			newvalue = fixpath(value);
			free(value);
			value = newvalue;
		}
		putparam(param, value+validx);
		free(value);
		param[0] = '\0';
	}

	(void) fclose(fp);

	/* write parent condition information to environment */

	putConditionInfo(parentZoneName, parentZoneType);

	putuserlocale();

	/*
	 * Now do all the various setups based on ABI compliance
	 */

	/* Read the environment provided by the pkginfo file */
	abi_comp_ptr = getenv("NONABI_SCRIPTS");

	/* if not ABI compliant set global flag */
	abi_sym_ptr = getenv("PKG_NONABI_SYMLINKS");
	if (abi_sym_ptr && strncasecmp(abi_sym_ptr, "TRUE", 4) == 0) {
		set_nonABI_symlinks();
	}

	/*
	 * If pkginfo says it's not compliant then set non_abi_scripts.
	 */
	if (abi_comp_ptr && strncmp(abi_comp_ptr, "TRUE", 4) == 0) {
		script_in = PROC_XSTDIN;
	}

	/*
	 * Since this is a removal, we can tell whether it's absolute or
	 * not from the resident pkginfo file read above.
	 */
	if ((err = set_basedirs((getenv("BASEDIR") != NULL), adm.basedir,
	    pkginst, nointeract)) != 0) {
		quit(err);
	}

	/*
	 * See if were are removing a package that only wants to update
	 * the database or only remove files associated with CAS's. We
	 * only check the PKG_HOLLOW_VARIABLE variable if told to do so by
	 * the caller.
	 */

	if (is_depend_pkginfo_DB()) {
		pt = getenv(PKG_HOLLOW_VARIABLE);

		if ((pt != NULL) && (strncasecmp(pt, "true", 4) == 0)) {
			echoDebug(DBG_PKGREMOVE_HOLLOW_ENABLED);

			/*
			 * this is a hollow package and hollow package support
			 * is enabled -- override admin settings to suppress
			 * checks that do not make sense since no scripts will
			 * be executed and no files will be removed.
			 */

			setadminSetting("conflict", "nocheck");
			setadminSetting("setuid", "nocheck");
			setadminSetting("action", "nocheck");
			setadminSetting("partial", "nocheck");
			setadminSetting("space", "nocheck");
			setadminSetting("authentication", "nocheck");
		} else {
			echoDebug(DBG_PKGREMOVE_HOLLOW_DISABLED);
			set_depend_pkginfo_DB(B_FALSE);
		}
	}

	put_path_params();

	/* If client mount point, add it to pkgremove environment */

	if (client_mntdir != NULL) {
		putparam("CLIENT_MNTDIR", client_mntdir);
	}

	/* Establish the class list and the class attributes. */

	if ((value = getenv("CLASSES")) != NULL) {
		cl_sets(qstrdup(value));
	} else {
		progerr(ERR_CLASSES, path);
		quit(99);
	}

	/* establish path and tmpdir */

	if (cmdbin[0] == '\0') {
		(void) strlcpy(cmdbin, PKGBIN, sizeof (cmdbin));
	}

	(void) snprintf(path, sizeof (path), "%s:%s", DEFPATH, cmdbin);
	putparam("PATH", path);

	putparam("TMPDIR", tmpdir);

	/*
	 * Check ulimit requirement (provided in pkginfo). The purpose of
	 * this limit is to terminate pathological file growth resulting from
	 * file edits in scripts. It does not apply to files in the pkgmap
	 * and it does not apply to any database files manipulated by the
	 * installation service.
	 */
	if (value = getenv("ULIMIT")) {
		if (assign_ulimit(value) == -1) {
			progerr(ERR_BADULIMIT, value);
			warnflag++;
		}
		putparam("PKG_ULIMIT", "TRUE");
	}

	/*
	 * If only gathering dependencies, check and output status of all
	 * remaining dependencies and exit.
	 */

	if (preremoveCheck == B_TRUE) {
		/*
		 * make sure current runlevel is appropriate
		 */

		(void) fprintf(stdout, "rckrunlevel=%d\n", rckrunlevel());

		/*
		 * determine if any packaging scripts provided with
		 * this package will execute as a priviledged user
		 */

		(void) fprintf(stdout, "rckpriv=%d\n", rckpriv());

		/*
		 * verify package dependencies
		 */

		(void) fprintf(stdout, "rckdepend=%d\n", rckdepend());

		/*
		 * ****** preremove check done - exit ******
		 */

		echoDebug(DBG_PKGREMOVE_PRERMCHK_OK);
		quit(0);
		/*NOTREACHED*/
	}

	/*
	 * Not gathering dependencies only, proceed to check dependencies
	 * and continue with the package removal operation.
	 */

	/*
	 * make sure current runlevel is appropriate
	 */

	n = rckrunlevel();

	if (n != 0) {
		quit(n);
		/* NOTREACHED */
	}

	/*
	 * determine if any packaging scripts provided with
	 * this package will execute as a priviledged user
	 */

	n = rckpriv();

	if (n != 0) {
		quit(n);
		/* NOTREACHED */
	}

	/*
	 * verify package dependencies
	 */
	n = rckdepend();

	if (n != 0) {
		quit(n);
		/* NOTREACHED */
	}

	/*
	 * *********************************************************************
	 * the actual removal of the package begins here
	 * *********************************************************************
	 */

	/*
	 * create lockfile to indicate start of removal
	 */
	started++;
	if ((fd = open(rlockfile, O_WRONLY|O_CREAT|O_TRUNC, 0644)) < 0) {
		progerr(ERR_LOCKFILE, rlockfile);
		quit(99);
	} else {
		(void) close(fd);
	}

	if (zoneName == (char *)NULL) {
		echo(MSG_PKGREMOVE_PROCPKG_GZ);
		echoDebug(DBG_PKGREMOVE_PROCPKG_GZ, pkginst, rlockfile);
	} else {
		echo(MSG_PKGREMOVE_PROCPKG_LZ, zoneName);
		echoDebug(DBG_PKGREMOVE_PROCPKG_LZ, pkginst, rlockfile,
		    zoneName);
	}
	if (delmap(0, pkginst, &pkgserver, &tmpfp) != 0) {
		progerr(ERR_DB_QUERY, pkginst);
		quit(99);
	}

	/*
	 * Run a preremove script if one is provided by the package.
	 * Don't execute preremove script if only updating the DB.
	 * Don't execute preremove script if files are not being deleted.
	 */

	/* update the lock - at the preremove script */
	lockupd("preremove");

	/* execute preremove script if one is provided */
	(void) snprintf(script, sizeof (script), "%s/preremove", pkgbin);
	if (access(script, F_OK) != 0) {
		/* no script present */
		echoDebug(DBG_PKGREMOVE_POC_NONE, pkginst,
		    zoneName ? zoneName : "global");
	} else if (nodelete) {
		/* not deleting files: skip preremove script */
		echoDebug(DBG_PKGREMOVE_POC_NODEL, pkginst, script,
		    zoneName ? zoneName : "global");
	} else if (is_depend_pkginfo_DB()) {
		/* updating db only: skip preremove script */
		echoDebug(DBG_PKGREMOVE_POC_DBUPD, pkginst, script,
		    zoneName ? zoneName : "global");
	} else {
		/* script present and ok to run: run the script */
		set_ulimit("preremove", ERR_PREREMOVE);
		if (zoneName == (char *)NULL) {
			echo(MSG_PKGREMOVE_EXEPOC_GZ);
			echoDebug(DBG_PKGREMOVE_EXEPOC_GZ, pkginst, script);
		} else {
			echo(MSG_PKGREMOVE_EXEPOC_LZ, zoneName);
			echoDebug(DBG_PKGREMOVE_EXEPOC_LZ, pkginst, script,
			    zoneName);
		}
		putparam("PKG_PROC_SCRIPT", "preremove");
		if (pkgverbose) {
			ckreturn(pkgexecl(script_in, PROC_STDOUT,
			    PROC_USER, PROC_GRP, SHELL, "-x",
			    script, NULL), ERR_PREREMOVE);
		} else {
			ckreturn(pkgexecl(script_in, PROC_STDOUT,
			    PROC_USER, PROC_GRP, SHELL, script,
			    NULL), ERR_PREREMOVE);
		}
		clr_ulimit();
	}

	/* update the lock - doing removal */

	lockupd("remove");

	/*
	 * Remove all components belonging to this package.
	 * Don't remove components if only updating the DB.
	 * Don't remove components if files are not being deleted.
	 */

	if (nodelete) {
		echoDebug(DBG_PKGREMOVE_REM_NODEL, pkginst,
		    zoneName ? zoneName : "global");
	} else if (is_depend_pkginfo_DB()) {
		echoDebug(DBG_PKGREMOVE_REM_DBUPD, pkginst,
		    zoneName ? zoneName : "global");
	} else {
		echoDebug(DBG_PKGREMOVE_REM, pkginst,
		    zoneName ? zoneName : "global");
		/*
		 * remove package one class at a time
		 */

		/* reverse order of classes */
		for (i = cl_getn() - 1; i >= 0; i--) {
			rmclass(cl_nam(i), pkgrmremote, zoneName);
		}

		rmclass(NULL, pkgrmremote, zoneName);
	}

	z_destroyMountTable();

	/*
	 * Execute postremove script, if any
	 * Don't execute postremove script if only updating the DB.
	 * Don't execute postremove script if files are not being deleted.
	 */

	/* update the lock - at the postremove script */
	lockupd("postremove");

	/* execute postremove script if one is provided */
	(void) snprintf(script, sizeof (script), "%s/postremove", pkgbin);
	if (access(script, F_OK) != 0) {
		/* no script present */
		echoDebug(DBG_PKGREMOVE_PIC_NONE, pkginst,
		    zoneName ? zoneName : "global");
	} else if (nodelete) {
		/* not deleting files: skip postremove script */
		echoDebug(DBG_PKGREMOVE_PIC_NODEL, pkginst, script,
		    zoneName ? zoneName : "global");
	} else if (is_depend_pkginfo_DB()) {
		/* updating db only: skip postremove script */
		echoDebug(DBG_PKGREMOVE_PIC_DBUPD, pkginst, script,
		    zoneName ? zoneName : "global");
	} else {
		/* script present and ok to run: run the script */
		set_ulimit("postremove", ERR_POSTREMOVE);
		if (zoneName == (char *)NULL) {
			echo(MSG_PKGREMOVE_EXEPIC_GZ);
			echoDebug(DBG_PKGREMOVE_EXEPIC_GZ, pkginst, script);
		} else {
			echo(MSG_PKGREMOVE_EXEPIC_LZ, zoneName);
			echoDebug(DBG_PKGREMOVE_EXEPIC_LZ, pkginst, script,
			    zoneName);
		}
		putparam("PKG_PROC_SCRIPT", "postremove");
		putparam("TMPDIR", tmpdir);
		if (pkgverbose) {
			ckreturn(pkgexecl(script_in, PROC_STDOUT, PROC_USER,
			    PROC_GRP, SHELL, "-x", script, NULL),
			    ERR_POSTREMOVE);
		} else {
			ckreturn(pkgexecl(script_in, PROC_STDOUT, PROC_USER,
			    PROC_GRP, SHELL, script, NULL),
			    ERR_POSTREMOVE);
		}
		clr_ulimit();
	}

	if (zoneName == (char *)NULL) {
		echo(MSG_PKGREMOVE_UPDINF_GZ);
	} else {
		echo(MSG_PKGREMOVE_UPDINF_LZ, zoneName);
	}

	if (delmap(1, pkginst, &pkgserver, &tmpfp) != 0) {
		progerr(ERR_DB_QUERY, pkginst);
		quit(99);
	}

	if (!warnflag && !failflag) {
		(void) chdir("/");
		if (rrmdir(pkgloc))
			warnflag++;
	}

	if ((z_running_in_global_zone() == B_TRUE) &&
	    (pkgIsPkgInGzOnly(get_inst_root(), pkginst) == B_TRUE)) {
		boolean_t	b;

		b = pkgRemovePackageFromGzonlyList(get_inst_root(), pkginst);
		if (b == B_FALSE) {
			progerr(ERR_PKGREMOVE_GZONLY_REMOVE, pkginst);
			ckreturn(1, NULL);
		}
	}

	/* release the generic package lock */

	(void) unlockinst();

	pkgcloseserver(pkgserver);

	quit(0);
	/* LINTED: no return */
}
Ejemplo n.º 23
0
void inputTest(WINDOW *win)
{
    int w, h, bx, by, sw, sh, i, c, num = 0;
    char buffer[80];
    WINDOW *subWin;
    static const char spinner[4] = "/-\\|";
    int spinner_count = 0;

    wclear(win);

    getmaxyx(win, h, w);
    getbegyx(win, by, bx);

    sw = w / 3;
    sh = h / 3;

    if ((subWin = subwin(win, sh, sw, by + h - sh - 2, bx + w - sw - 2))
            == NULL)
        return;

#ifdef A_COLOR
    if (has_colors())
    {
        init_pair(2, COLOR_WHITE, COLOR_RED);
        wbkgd(subWin, COLOR_PAIR(2) | A_BOLD);
    }
    else
#endif
        wbkgd(subWin, A_BOLD);

    box(subWin, ACS_VLINE, ACS_HLINE);
    wrefresh(win);

    nocbreak();

    wclear (win);
    mvwaddstr(win, 1, 1,
              "Press keys (or mouse buttons) to show their names");
    mvwaddstr(win, 2, 1, "Press spacebar to finish");
    wrefresh(win);

    keypad(win, TRUE);
    raw();
    noecho();

    wtimeout(win, 200);

#ifdef PDCURSES
    mouse_set(ALL_MOUSE_EVENTS);
    PDC_save_key_modifiers(TRUE);
    PDC_return_key_modifiers(TRUE);
#endif
    curs_set(0);        /* turn cursor off */

    while (1)
    {
        while (1)
        {
            c = wgetch(win);

            if (c == ERR)
            {
                spinner_count++;
                if (spinner_count == 4)
                    spinner_count = 0;
                mvwaddch(win, 3, 3, spinner[spinner_count]);
                wrefresh(win);
            }
            else
                break;
        }
#ifdef PDCURSES
        wmove(win, 4, 18);
        wclrtoeol(win);
#endif
        mvwaddstr(win, 3, 5, "Key Pressed: ");
        wclrtoeol(win);

        if (c >= KEY_MIN)
            wprintw(win, "%s", keyname(c));
        else if (isprint(c))
            wprintw(win, "%c", c);
        else
            wprintw(win, "%s", unctrl(c));
#ifdef PDCURSES
        if (c == KEY_MOUSE)
        {
            int button = 0;
            request_mouse_pos();

            if (BUTTON_CHANGED(1))
                button = 1;
            else if (BUTTON_CHANGED(2))
                button = 2;
            else if (BUTTON_CHANGED(3))
                button = 3;

            if (button && (BUTTON_STATUS(button) &
                           BUTTON_MODIFIER_MASK))
            {
                waddstr(win, " Modifier(s):");

                if (BUTTON_STATUS(button) & BUTTON_SHIFT)
                    waddstr(win, " SHIFT");

                if (BUTTON_STATUS(button) & BUTTON_CONTROL)
                    waddstr(win, " CONTROL");

                if (BUTTON_STATUS(button) & BUTTON_ALT)
                    waddstr(win, " ALT");
            }

            wmove(win, 4, 18);
            wclrtoeol(win);
            wprintw(win, "Button %d: ", button);

            if (MOUSE_MOVED)
                waddstr(win, "moved: ");
            else if (MOUSE_WHEEL_UP)
                waddstr(win, "wheel up: ");
            else if (MOUSE_WHEEL_DOWN)
                waddstr(win, "wheel dn: ");
            else if (MOUSE_WHEEL_LEFT)
                waddstr(win, "wheel lt: ");
            else if (MOUSE_WHEEL_RIGHT)
                waddstr(win, "wheel rt: ");
            else if ((BUTTON_STATUS(button) &
                      BUTTON_ACTION_MASK) == BUTTON_PRESSED)
                waddstr(win, "pressed: ");
            else if ((BUTTON_STATUS(button) &
                      BUTTON_ACTION_MASK) == BUTTON_CLICKED)
                waddstr(win, "clicked: ");
            else if ((BUTTON_STATUS(button) &
                      BUTTON_ACTION_MASK) == BUTTON_DOUBLE_CLICKED)
                waddstr(win, "double: ");
            else
                waddstr(win, "released: ");

            wprintw(win, "Position: Y: %d X: %d", MOUSE_Y_POS, MOUSE_X_POS);
        }
        else if (PDC_get_key_modifiers())
        {
            waddstr(win, " Modifier(s):");
            if (PDC_get_key_modifiers() & PDC_KEY_MODIFIER_SHIFT)
                waddstr(win, " SHIFT");

            if (PDC_get_key_modifiers() & PDC_KEY_MODIFIER_CONTROL)
                waddstr(win, " CONTROL");

            if (PDC_get_key_modifiers() & PDC_KEY_MODIFIER_ALT)
                waddstr(win, " ALT");

            if (PDC_get_key_modifiers() & PDC_KEY_MODIFIER_NUMLOCK)
                waddstr(win, " NUMLOCK");
        }
#endif
        wrefresh(win);

        if (c == ' ')
            break;
    }

    wtimeout(win, -1);  /* turn off timeout() */
    curs_set(1);        /* turn cursor back on */

#ifdef PDCURSES
    mouse_set(0L);
    PDC_save_key_modifiers(FALSE);
    PDC_return_key_modifiers(FALSE);
#endif
    wclear(win);
    mvwaddstr(win, 2, 1, "Press some keys for 5 seconds");
    mvwaddstr(win, 1, 1, "Pressing ^C should do nothing");
    wrefresh(win);

    werase(subWin);
    box(subWin, ACS_VLINE, ACS_HLINE);

    for (i = 0; i < 5; i++)
    {
        mvwprintw(subWin, 1, 1, "Time = %d", i);
        wrefresh(subWin);
        napms(1000);
        flushinp();
    }

    delwin(subWin);
    werase(win);
    flash();
    wrefresh(win);
    napms(500);
    flushinp();

    mvwaddstr(win, 2, 1, "Press a key, followed by ENTER");
    wmove(win, 9, 10);
    wrefresh(win);
    echo();

    keypad(win, TRUE);
    raw();
    wgetnstr(win, buffer, 3);
    flushinp();

    wmove(win, 9, 10);
    wdelch(win);
    mvwaddstr(win, 4, 1, "The character should now have been deleted");
    Continue(win);

    refresh();
    wclear(win);
    echo();
    buffer[0] = '\0';
    mvwaddstr(win, 3, 2, "The window should have moved");
    mvwaddstr(win, 4, 2,
              "This text should have appeared without you pressing a key");
    mvwaddstr(win, 6, 2, "Enter a number then a string seperated by space");
    mvwin(win, 2, 1);
    wrefresh(win);
    mvwscanw(win, 7, 6, "%d %s", &num, buffer);
    mvwprintw(win, 8, 6, "String: %s Number: %d", buffer, num);
    Continue(win);

    refresh();
    wclear(win);
    echo();
    mvwaddstr(win, 3, 2, "Enter a 5 character string: ");
    wgetnstr(win, buffer, 5);
    mvwprintw(win, 4, 2, "String: %s", buffer);
    Continue(win);
}
Ejemplo n.º 24
0
    bool AssimpModelImporter::Load(const std::string& Filename)
    {
        // Assimp Importer
        Assimp::Importer Importer;
        
        // Load Model
        assimp_model = Importer.ReadFile(Filename.c_str(),aiProcessPreset_TargetRealtime_Fast | aiProcess_OptimizeMeshes | aiProcess_JoinIdenticalVertices | aiProcess_LimitBoneWeights | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);

        // Path Relative to Model File
        std::string RelativePath = Filename.substr(0,Filename.find_last_of("/")+1);

        if (!assimp_model)
        {
            echo("Failed To Import Model: " + Filename + " ERROR: " + Importer.GetErrorString());
            return false;
        } else {
            
            // Build Skeleton
            // initial bone count
            boneCount = 0;
            // Get Skeleton
            GetBone(assimp_model->mRootNode);
            
            for (uint32 i=0;i<assimp_model->mNumMeshes;i++)
            {
                // loop through meshes
                const aiMesh* mesh = assimp_model->mMeshes[i];

                // create submesh
                SubMesh subMesh;
                
                // set submesh id
                subMesh.ID = i;
                
                // set name
                subMesh.Name = mesh->mName.data;
                
                for (uint32 t = 0; t < mesh->mNumFaces;t++) {
                    const aiFace* face = &mesh->mFaces[t];
                    subMesh.tIndex.push_back(face->mIndices[0]);
                    subMesh.tIndex.push_back(face->mIndices[1]);
                    subMesh.tIndex.push_back(face->mIndices[2]);
                }

                // get posisitons
                if (mesh->HasPositions())
                {
                    subMesh.hasVertex = true;
                    subMesh.tVertex.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tVertex[0],&mesh->mVertices[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasVertex = false;

                // get normals
                if (mesh->HasNormals())
                {                    
                    subMesh.hasNormal = true;
                    subMesh.tNormal.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tNormal[0],&mesh->mNormals[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasNormal = false;

                // get texcoords
                if (mesh->HasTextureCoords(0))
                {               
                    subMesh.hasTexcoord = true;
                    for (uint32 k = 0; k < mesh->mNumVertices;k++) 
                    {
                        subMesh.tTexcoord.push_back(Vec2(mesh->mTextureCoords[0][k].x,mesh->mTextureCoords[0][k].y));                            
                    }
                } else subMesh.hasTexcoord = false;

                // get tangent
                if (mesh->HasTangentsAndBitangents())
                {
                    subMesh.hasTangentBitangent = true;
                    subMesh.tTangent.resize(mesh->mNumVertices);
                    subMesh.tBitangent.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tTangent[0],&mesh->mTangents[0],mesh->mNumVertices*sizeof(Vec3));
                    memcpy(&subMesh.tBitangent[0],&mesh->mBitangents[0],mesh->mNumVertices*sizeof(Vec3));
                } else subMesh.hasTangentBitangent = false;

                // get vertex colors
                if (mesh->HasVertexColors(0))
                {
                    subMesh.hasVertexColor = true;
                    subMesh.tVertexColor.resize(mesh->mNumVertices);
                    memcpy(&subMesh.tVertexColor[0],&mesh->mColors[0],mesh->mNumVertices*sizeof(Vec4));
                } else subMesh.hasVertexColor = false;

                // get vertex weights
                if (mesh->HasBones())
                {
                    // Set Flag
                    subMesh.hasBones = true;
                    
                    // Create Bone's Sub Mesh Internal ID
                    uint32 count = 0;
                    for (uint32 k = 0; k < mesh->mNumBones; k++)
                    {
                        // Save Offset Matrix
                        Matrix _offsetMatrix;
                        _offsetMatrix.m[0]  = mesh->mBones[k]->mOffsetMatrix.a1; _offsetMatrix.m[1]  = mesh->mBones[k]->mOffsetMatrix.b1;  _offsetMatrix.m[2]   = mesh->mBones[k]->mOffsetMatrix.c1; _offsetMatrix.m[3]  = mesh->mBones[k]->mOffsetMatrix.d1;
                        _offsetMatrix.m[4]  = mesh->mBones[k]->mOffsetMatrix.a2; _offsetMatrix.m[5]  = mesh->mBones[k]->mOffsetMatrix.b2;  _offsetMatrix.m[6]   = mesh->mBones[k]->mOffsetMatrix.c2; _offsetMatrix.m[7]  = mesh->mBones[k]->mOffsetMatrix.d2;
                        _offsetMatrix.m[8]  = mesh->mBones[k]->mOffsetMatrix.a3; _offsetMatrix.m[9]  = mesh->mBones[k]->mOffsetMatrix.b3;  _offsetMatrix.m[10]  = mesh->mBones[k]->mOffsetMatrix.c3; _offsetMatrix.m[11] = mesh->mBones[k]->mOffsetMatrix.d3;
                        _offsetMatrix.m[12] = mesh->mBones[k]->mOffsetMatrix.a4; _offsetMatrix.m[13] = mesh->mBones[k]->mOffsetMatrix.b4;  _offsetMatrix.m[14]  = mesh->mBones[k]->mOffsetMatrix.c4; _offsetMatrix.m[15] = mesh->mBones[k]->mOffsetMatrix.d4;

                        uint32 boneID = GetBoneID(mesh->mBones[k]->mName.data);
                        subMesh.BoneOffsetMatrix[boneID] = _offsetMatrix;
                        subMesh.MapBoneIDs[boneID] = count;
                        count++;
                    }
                    
                    // Add Bones and Weights to SubMesh Structure, based on Internal IDs
                    for (uint32 j = 0; j < mesh->mNumVertices; j++)
                    {
                        // get values
                        std::vector<uint32> boneID(4,0);
                        std::vector<f32> weightValue(4,0.f);
                        
                        uint32 count = 0;
                        for (uint32 k = 0; k < mesh->mNumBones; k++) 
                        {
                            for (uint32 l = 0; l < mesh->mBones[k]->mNumWeights; l++)
                            {
                                if (mesh->mBones[k]->mWeights[l].mVertexId == j)
                                {
                                    // Convert Bone ID to Internal of the Sub Mesh
                                    boneID[count] = subMesh.MapBoneIDs[GetBoneID(mesh->mBones[k]->mName.data)];
                                    // Add Bone Weight
                                    weightValue[count] = mesh->mBones[k]->mWeights[l].mWeight;
                                    count++;
                                }
                            }
                        }
                        subMesh.tBonesID.push_back(Vec4((f32)boneID[0],(f32)boneID[1],(f32)boneID[2],(f32)boneID[3]));
                        subMesh.tBonesWeight.push_back(Vec4(weightValue[0],weightValue[1],weightValue[2],weightValue[3]));                        
                    }
                    
                } else subMesh.hasBones = false;
                
                // Get SubMesh Material ID
                subMesh.materialID = mesh->mMaterialIndex;
                
                // add to submeshes vector
                subMeshes.push_back(subMesh);
            }
            
            // Build Materials List
            for (uint32 i=0;i<assimp_model->mNumMaterials;++i)
            {
                MaterialProperties material;
                // Get Material
                const aiMaterial* pMaterial = assimp_model->mMaterials[i];
                material.id = i;
                
                aiString name;
                pMaterial->Get(AI_MATKEY_NAME, name);
                material.Name.resize(name.length);
                memcpy(&material.Name[0], name.data, name.length);
                
                aiColor3D color;
				material.haveColor = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, color)==AI_SUCCESS) 
                {
                    material.haveColor = true;
                    material.Color = Vec4(color.r, color.g, color.b, 1.0);                
                }
				material.haveAmbient = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_AMBIENT, color)==AI_SUCCESS) 
                {
                    material.haveAmbient = true;
                    material.Ambient = Vec4(color.r, color.g, color.b, 1.0);                                
                }
				material.haveSpecular = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_SPECULAR, color)==AI_SUCCESS) 
                {
                    material.haveSpecular = true;
                    material.Specular = Vec4(color.r, color.g, color.b, 1.0);
                }
                material.haveEmissive = false;
                if (pMaterial->Get(AI_MATKEY_COLOR_EMISSIVE, color)==AI_SUCCESS) 
                {
                    material.haveEmissive = true;
                    material.Emissive = Vec4(color.r, color.g, color.b, 1.0);
                }
                
                bool flag = false;
                pMaterial->Get(AI_MATKEY_ENABLE_WIREFRAME, flag);
                material.WireFrame = flag;

                flag = false;
                pMaterial->Get(AI_MATKEY_TWOSIDED, flag);
                material.Twosided = flag;
                
                f32 value = 1.0f;
                pMaterial->Get(AI_MATKEY_OPACITY, value);
                material.Opacity = value;
                
                value = 0.0f;
                pMaterial->Get(AI_MATKEY_SHININESS, value);
                material.Shininess = value;
                
                value = 0.0f;
                pMaterial->Get(AI_MATKEY_SHININESS_STRENGTH, value);
                material.ShininessStrength = value;                
                // Save Properties                
                
                aiString path;
                aiReturn texFound;

                // Diffuse
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_DIFFUSE, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveColorMap = true;
                    material.colorMap.resize(path.length);
                    memcpy(&material.colorMap[0],&path.data,path.length);
                    std::replace(material.colorMap.begin(), material.colorMap.end(),'\\','/');
                }
                
                // Bump Map
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_NORMALS, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveNormalMap = true;
                    material.normalMap.resize(path.length);
                    memcpy(&material.normalMap[0],&path.data,path.length);
                    std::replace(material.normalMap.begin(), material.normalMap.end(),'\\','/');
                } else {
                    // Height Map
                    texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_HEIGHT, 0, &path);
                    if (texFound==AI_SUCCESS)
                    {
                        material.haveNormalMap = true;
                        material.normalMap.resize(path.length);
                        memcpy(&material.normalMap[0],&path.data,path.length);
                        std::replace(material.normalMap.begin(), material.normalMap.end(),'\\','/');
                    }
                }
                // Specular
                texFound = assimp_model->mMaterials[i]->GetTexture(aiTextureType_SPECULAR, 0, &path);
                if (texFound==AI_SUCCESS)
                {
                    material.haveSpecularMap = true;
                    material.specularMap.resize(path.length);
                    memcpy(&material.specularMap[0],&path.data,path.length);
                    std::replace(material.specularMap.begin(), material.specularMap.end(),'\\','/');
                }
                // Add Material to List
                materials.push_back(material);
            }
        }
		Importer.FreeScene();

        return true;
    }
Ejemplo n.º 25
0
int message_change(int x)
{
    extern char backgrnd_str[];
    extern char message[][80];
    extern char sp_return[];
    extern char cq_return[];

    int j;
    int count;
    int mes_length;
    int bufnr = 0;
    char printbuf[80];

    clear_display();
    attron(COLOR_PAIR(C_LOG) | A_STANDOUT);

    for (j = 13; j <= 23; j++) {
	mvprintw(j, 0, backgrnd_str);
    }

    nicebox(14, 3, 2, 60, "Enter message (F1-12, C, S)");

    attron(COLOR_PAIR(C_LOG) | A_STANDOUT);

    while (1) {
	bufnr = toupper(key_get());

	if ((bufnr == 'C') || (bufnr == 'S'))
	    break;

	if (bufnr >= KEY_F(1) && bufnr <= KEY_F(12))
	    break;
    }

    if (bufnr == 'S') {
	bufnr = 12;
    } else if (bufnr == 'C') {
	bufnr = 13;
    } else {
	bufnr = bufnr - KEY_F(1);
    }

    printbuf[0] = '\0';
    strncat(printbuf, message[bufnr], strlen(message[bufnr]) - 1);
    mvprintw(15, 4, "%s", printbuf);
    refreshp();

    mvprintw(16, 4, "");
    message[bufnr][0] = '\0';

    echo();
    getnstr(message[bufnr], 60);
    noecho();

    strcat(message[bufnr], "\n");
    mes_length = strlen(message[bufnr]);

    if (mes_length < 2) {
	clear_display();
	attron(COLOR_PAIR(C_LOG) | A_STANDOUT);

	for (j = 13; j <= 23; j++) {
	    mvprintw(j, 0, backgrnd_str);
	}

	return (1);
    }

    for (count = 0; count <= mes_length; count++) {
	if ((message[bufnr][count] > 96)
	    && (message[bufnr][count] < 123))
	    message[bufnr][count] = message[bufnr][count] - 32;
    }

    mvprintw(12, 29, "");
    refreshp();
    clear_display();
    attron(COLOR_PAIR(C_LOG) | A_STANDOUT);

    for (j = 13; j <= 23; j++) {
	mvprintw(j, 0, backgrnd_str);
    }

    writeparas();

    strncpy(sp_return, message[SP_TU_MSG], 79);
    strncpy(cq_return, message[CQ_TU_MSG], 79);

    return (0);
}
Ejemplo n.º 26
0
int main(int argc, const char* argv[]) {
  // Get fractal renderer
  double (*renderer) (complex double, const char *[], int) = &in_mandlebrot;
  const char** frargv = &argv[1];
  int frargc = argc - 1;

  if(frargc > 0) {
    frargc --;

    for(unsigned int i = 0; i < sizeof(fractals) / sizeof(struct Fractal); i++) {
      if(strcmp(fractals[i].name, frargv[0]) == 0) {
        renderer = fractals[i].renderer;
        frargv++;

        if(frargc < fractals[i].args) {
          fprintf(stderr, "'%s' takes %d argument%s.\n",
                  fractals[i].name,
                  fractals[i].args,
                  (fractals[i].args == 1) ? "" : "s");
          return 1;
        }
      }
    }
  }

  MEVENT event;
  WINDOW * mainwin = initscr();
  start_color();
  cbreak();
  noecho();
  nonl();
  intrflush(stdscr, false);
  keypad(stdscr, true);
  curs_set(0);
  mousemask(ALL_MOUSE_EVENTS, NULL);

  // Initialise colours
  render_init(mainwin);

  bool looping = true;
  while(looping) {
    // Render the fractal
    render_fractal(renderer, frargv, frargc);

    // Get input
    int ch = getch();
    switch(ch) {
    case KEY_UP:
      scrollpixels(1, 0);
      break;

    case KEY_DOWN:
      scrollpixels(-1, 0);
      break;

    case KEY_LEFT:
      scrollpixels(0, 1);
      break;

    case KEY_RIGHT:
      scrollpixels(0, -1);
      break;

    case '+':
      zoom_in();
      break;

    case '-':
      zoom_out();
      break;

    case 'h':
      toggle_hide();
      break;

    case 'b':
      toggle_bright();
      break;

    case KEY_MOUSE:
      if(getmouse(&event) == OK) {
        if(event.bstate & BUTTON1_CLICKED) {
          centre(pixel_topleft(event.y, event.x));
        }
      }
      break;

    case 'r':
      reset();
      break;

    case 'q':
      looping = false;
      break;

    default:
      break;
    }
  }

  curs_set(1);
  nl();
  echo();
  nocbreak();
  delwin(mainwin);
  endwin();
}
Ejemplo n.º 27
0
/*
 * writer: write to remote: 0 -> line.
 * ~.				terminate
 * ~^Z				suspend rlogin process.
 * ~<delayed-suspend char>	suspend rlogin process, but leave reader alone.
 */
void
writer(void)
{
	int bol, local, n;
	char c;

	bol = 1;			/* beginning of line */
	local = 0;
	for (;;) {
		n = read(STDIN_FILENO, &c, 1);
		if (n <= 0) {
			if (n < 0 && errno == EINTR)
				continue;
			break;
		}
		/*
		 * If we're at the beginning of the line and recognize a
		 * command character, then we echo locally.  Otherwise,
		 * characters are echo'd remotely.  If the command character
		 * is doubled, this acts as a force and local echo is
		 * suppressed.
		 */
		if (bol) {
			bol = 0;
			if (!noescape && c == escapechar) {
				local = 1;
				continue;
			}
		} else if (local) {
			local = 0;
			if (c == '.' || c == deftc.t_eofc) {
				echo(c);
				break;
			}
			if (c == defltc.t_suspc || c == defltc.t_dsuspc) {
				bol = 1;
				echo(c);
				stop(c);
				continue;
			}
			if (c != escapechar)
#ifdef CRYPT
#ifdef KERBEROS
				if (doencrypt)
					(void)des_enc_write(rem,
					    (char *)&escapechar, 1,
						schedule, &cred.session);
				else
#endif
#endif
					(void)write(rem, &escapechar, 1);
		}

#ifdef CRYPT
#ifdef KERBEROS
		if (doencrypt) {
			if (des_enc_write(rem, &c, 1, schedule, &cred.session) == 0) {
				msg("line gone");
				break;
			}
		} else
#endif
#endif
			if (write(rem, &c, 1) == 0) {
				msg("line gone");
				break;
			}
		bol = c == defkill || c == deftc.t_eofc ||
		    c == deftc.t_intrc || c == defltc.t_suspc ||
		    c == '\r' || c == '\n';
	}
}
Ejemplo n.º 28
0
int main(int argc, char* argv[])
{
	struct sockaddr_in	saddr, caddr;
	int			fd1, fd2, len, id=0;
	const int 		on = 1;

	set_sighandler(SIGCHLD, wait_child);

	/* make server's socket */
	if ((fd1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
		perror("socket");
		return -1;
	}
	setsockopt(fd1, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family      = AF_INET;
	saddr.sin_port        = htons(argc>1?atoi(argv[1]):PORTNUM);
	saddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(fd1, (struct sockaddr*)&saddr, sizeof(saddr))) {
		perror("bind");
		return -1;
	}

	if(listen(fd1, 5)) {
		perror("listen");
		return -1;
	}

	while(1) {
		if((fd2 = accept(fd1, (struct sockaddr*)&caddr, &len)) < 0) {
			perror("accept");
			exit(1);
		}
		else
			id++;

		switch(fork()){
			case 0:
				close(fd1);

				fprintf(stdout,"Connect : [%02d]\n",id);
				echo(fd2);
				dprintf(fd2,"Bye!\n");
				fprintf(stdout,"Disconnect : [%02d]\n",id);
				shutdown(fd2, SHUT_RDWR);
				close(fd2);
				exit(0);
			case -1:
				perror("child process");
				break;
			default:
				close(fd2);	
		}
	}
	
	shutdown(fd1, SHUT_RDWR);
	close(fd1);	
	return 0;
}
Ejemplo n.º 29
0
Archivo: epoll.c Proyecto: 4179e1/misc
int main (int argc, char *argv[])
{
	int listenfd, connfd, port;
	struct sockaddr_in clientaddr;
	socklen_t clientlen = sizeof (struct sockaddr_in);
	struct epoll_event ev, events[MAX_EVENTS];
	int epfd, nfds, n;
	int i = 1;

	if (argc != 2)
	{
		wp_critical ("usage: %s <port>", argv[0]);
	}

	port = atoi (argv[1]);
	listenfd = wp_open_listenfd (port);
	if (listenfd < 0)
	{
		wp_critical ("open_listenfd failed");
	}

	epfd = wp_epoll_create (MAX_EVENTS);
	if (epfd == -1)
	{
		wp_critical ("epoll_create failed");
	}

	ev.events = EPOLLIN;
	ev.data.fd = listenfd;
	if (wp_epoll_ctl (epfd, EPOLL_CTL_ADD, listenfd, &ev) == -1)
	{
		wp_critical ("epoll_ctl failed");
	}

	while (1)
	{
		wp_debug ("loop %d", i++);
		nfds = epoll_wait (epfd, events, MAX_EVENTS, -1);
		if (nfds == -1)
		{
			wp_critical ("epoll_wait failed");
		}

		for (n = 0; n < nfds; ++n)
		{
			if (events[n].data.fd == listenfd)
			{
				wp_debug ("a new connection");
				connfd = wp_accept (listenfd, (struct sockaddr *)&clientaddr, &clientlen);
				if (connfd == -1)
				{
					wp_critical ("accept failed");
				}

				if (!setnonblocking (connfd))
				{
					wp_critical ("unbale to set fd nonblock");
				}

				ev.events = EPOLLIN | EPOLLET;
				ev.data.fd = connfd;
				if (wp_epoll_ctl (epfd, EPOLL_CTL_ADD, connfd, &ev) == -1)
				{
					wp_critical ("epoll_ctl failed");
				}
			}
			else if (events[n].events & EPOLLIN)
			{
				echo (events[n].data.fd);
			}
		}
	}
}
Ejemplo n.º 30
0
void show_block(int fd)
{
  unsigned char workspace[BLOCKSIZE];
  unsigned int choice;   // The block number to display.
  unsigned int offset;   // Offset into the block.
  unsigned int line_offset;  // Offset into the current line.
  unsigned int total;    // Total number of blocks.
  char printables[16+1]; // Printable version of the block's bytes.
  int row = 1;

  clear();
  
  struct gfs_super_block *my_super = (struct gfs_super_block *)workspace;

  lseek(fd, 0, SEEK_SET);
  read(fd, workspace, BLOCKSIZE);  

  total = my_super->total_blocks;
  printables[16] = '\0';   // Be sure this array is null terminated.

  // Ask the user for a block number.
  mvprintw(1, 1, "Enter block number (0 - %u): ", total - 1);
  echo(); scanw("%u", &choice); noecho();

  clear();

  // Do some error handling. (What an idea!)
  if (choice > total - 1) {
    mvprintw(1, 1, "Error: Block %u out of range. Maximum = %u\n", choice, total);
    CONTINUE_MESSAGE;
  }

  // Read the block in question.
  lseek(fd, choice * BLOCKSIZE, SEEK_SET);
  read(fd, workspace, BLOCKSIZE);

  // Loop over the entire block, printing bytes as we go.
  for (offset = 0; offset < BLOCKSIZE; offset += 16) {

    // Pause the display and give the user a chance to quit now.
    if (offset % (16*(LINES-2)) == 0) {
      mvprintw(LINES-1, 1, "Press Enter to continue; 'q' to quit... ");
      refresh();
      row = 1;
      if(getch() == 'q') {
        clear();
	break;
      }
      clear();
    }

    // Print a line header.
    mvprintw(row++, 1, "%03X:", offset);
    
    for (line_offset = 0; line_offset < 16; line_offset++) {

      // Put the printable version of this byte into the printables array.
      if (isprint(workspace[offset + line_offset])) {
	printables[line_offset] = workspace[offset + line_offset];
      }
      else {
	printables[line_offset] = '.';
      }

      // Display the hex version of the bytes.
      if (line_offset % 8 == 0) printw(" ");
      printw("%02X ", (unsigned char)workspace[offset + line_offset]);
    }

    // Display the ASCII version of the bytes.
    printw("|%s|\n", printables);
  }

  CONTINUE_MESSAGE;
}