Esempio n. 1
0
void xyzsh_readline_interface_on_curses(char* cmdline, int cursor_point, char** argv, int argc, BOOL exit_in_spite_ofjob_exist, BOOL welcome_msg)
{
    gSigChld = FALSE;
    gSigWinch = FALSE;

    signal(SIGCHLD, handler);
    signal(SIGWINCH, handler);

    const int maxx = mgetmaxx();
    const int maxy = mgetmaxy();

    int temulator_y = 0;
    int temulator_x = 0;
    int temulator_height = maxy;
    int temulator_width = maxx;

    sTEmulator* temulator = temulator_init(temulator_height, temulator_width);

    struct sTEmulatorFunArg arg;

    arg.cmdline = cmdline;
    arg.cursor_point = cursor_point;
    arg.argv = argv;
    arg.argc = argc;
    arg.exit_in_spite_ofjob_exist = exit_in_spite_ofjob_exist;
    arg.welcome_msg = welcome_msg;

    temulator_open(temulator, temulator_fun, &arg);

    initscr();
    start_color();
    noecho();
    raw();
    nodelay(stdscr, TRUE);
    keypad(stdscr, TRUE);
    curs_set(0);
    ESCDELAY=50;

    temulator_init_colors();

    WINDOW* term_win = newwin(temulator_height, temulator_width, temulator_y, temulator_x);

    int pty = temulator->mFD;

    fd_set mask, read_ok;
    FD_ZERO(&mask);
    FD_SET(0, &mask);
    FD_SET(pty, &mask);

    int dirty = 0;
    struct timeval next;

    gettimeofday(&next, NULL);
    while(1) {
        struct timeval tv = { 0, 1000 * 1000 / 100 };
        read_ok = mask;

        if(select(pty+1, &read_ok, NULL, NULL, &tv) > 0) {
            if(FD_ISSET(pty, &read_ok)) {
                temulator_read(temulator);
                dirty = 1;
            }
        }

        int key;
        while((key = getch()) != ERR) {
            temulator_write(temulator, key);
            dirty = 1;
        }

        gettimeofday(&tv, NULL);
        if(dirty && is_expired(tv, next)) {
            temulator_draw_on_curses(temulator, term_win, temulator_y, temulator_x);
            wrefresh(term_win);
            dirty = 0;
            next = timeval_add(tv, slice);
        }

        if(gSigChld) {
            gSigChld = FALSE;
            break;
        }

        if(gSigWinch) {
            gSigWinch = 0;

            temulator_height = mgetmaxy();
            temulator_width = mgetmaxx();

            if(temulator_width >= 10 && temulator_height >= 10) {
                resizeterm(temulator_height, temulator_width);

                wresize(term_win, temulator_height, temulator_width);
                temulator_resize(temulator, temulator_height, temulator_width);

                dirty = 1;
            }
        }
    }

    endwin();

    temulator_final(temulator);
}
Esempio n. 2
0
void init_curses() {
	initscr();
	raw();
	keypad(stdscr, TRUE);
	noecho();
}
Esempio n. 3
0
void modify_display ( void )
{
	int i;
	int focus = 0;
	int c;
	int x,y;
	int maxx;
	int maxy __attribute((unused));
	int ll_focus_y = 0;
	int ll_focus_x = 0;
	WINDOW *mod_win;

	getmaxyx ( win, maxy, maxx );
	mod_win = newwin ( 8, maxx, 0, 0 );
	cbreak();
	raw();
	nonl();
	keypad ( mod_win, TRUE );
	while ( 1 )
	{
		werase( mod_win );
		wrefresh( mod_win );
		mvwprintw ( mod_win,  0, 0, "Use arrow keys (or vim cursor keys) to navigate;" );
		mvwprintw ( mod_win,  1, 0, "Set sort field (highlighted) with 's', order %s (change with 'r')", parametres.reversesort ? "ascending" : "descending" );
		mvwprintw ( mod_win,  2, 0, "go down or press enter to change a field, select with space key");
		mvwprintw ( mod_win,  3, 0, "'i' to insert a field, 'a' to append it, 'd' to delete");
		wmove ( mod_win, 6, 0 );
		for ( i = 0; i < MAX_DISPLAY_FIELDS; i++ )
		{
			wattron ( mod_win, A_REVERSE );
			if ( display_fields[i] == NULL )
			{
				break;
			}
			if ( display_fields[i]->identifier == parametres.sortby )
			{
				wattroff ( mod_win, A_REVERSE );
			}
			wprintw ( mod_win, display_fields[i]->header_format, display_fields[i]->fieldname );
			if ( i == focus )
			{
				wattroff ( mod_win, A_REVERSE );
				/* find out where to print the menu in case we need one */
				getyx ( mod_win, y, x );
				ll_focus_y = y + 1;
				ll_focus_x = x - display_fields[i]->field_length;
				/*
				  keep menu inside the current window - in case it would "fall
				  off" off the edge, move it inwards by the width of the menu
				*/
				if ( maxx < ( x + MENU_WIDTH ) )
				{
					ll_focus_x = maxx - MENU_WIDTH;
				}

				mvwaddch( mod_win, y - 1, x - display_fields[i]->field_length - 1 , ACS_ULCORNER);
				mvwaddch( mod_win, y + 1, x - display_fields[i]->field_length - 1 , ACS_LLCORNER);
				mvwaddch( mod_win, y + 1, x -1, ACS_LRCORNER);
				mvwaddch( mod_win, y - 1, x - 1 , ACS_URCORNER);
				mvwvline( mod_win, y , x - display_fields[i]->field_length - 1 , ACS_VLINE, 1 );
				mvwvline( mod_win, y , x - 1 , ACS_VLINE, 1 );
				mvwhline( mod_win, y - 1, x - display_fields[i]->field_length, ACS_HLINE, display_fields[i]->field_length - 1 );
				mvwhline( mod_win, y + 1, x - display_fields[i]->field_length, ACS_HLINE, display_fields[i]->field_length - 1 );
				wmove ( mod_win, y, x );
			}
		}
		wrefresh( mod_win );
		c = getch();
		switch ( c )
		{
			case 'h':
			case KEY_LEFT:
				if ( focus > 0 )
				{
					focus--;
				}
				break;
			case 'l':		
			case KEY_RIGHT:
				if ( display_fields[focus + 1] != NULL )
				{
					focus++;
				}
				break;
			case 's':
			case 'S':
				if (  display_fields[focus]->sortable == 1 )
				{
				 	parametres.sortby = display_fields[focus]->identifier;
					goto end;
				}
				else
				{
					printf ( "\a" );
					mvwprintw ( mod_win,  5, 0, "%-79s", "Sorry, can't sort by this field");
					wrefresh ( mod_win );
					sleep ( 1 );
				}
				break;
			case 'r':
			case 'R':
				parametres.reversesort ^= 1;
				break;
			case 'd':
					displayfield_shift_down ( focus );
				break;
			case 'i':		/* insert a field */
				if ( displayfield_shift_up ( focus + 1 ) != 0 )
				{
					ungetch ( 'j' );
				}
				break;
			case 'a':		/* append a field */
				focus++;
				if ( displayfield_shift_up ( focus ) != 0 )
				{
					ungetch ( 'j' );
				}
				else
				{
					focus--;
				}
				break;
			case 'j':
			case KEY_DOWN:
			case KEY_ENTER:
				display_fields[focus] = select_field ( ll_focus_y, ll_focus_x, display_fields[focus] );
				goto end;
				break;
			case 'q':
			case 27:	/* ESC key */
				goto end;
				break;
			default:
				printf ( "\a" );
				break;
		}
		wattroff ( mod_win, A_REVERSE );
	}
	end: ;
	keypad ( mod_win, FALSE );
	halfdelay ( 30 );
	werase( mod_win );
	delwin( mod_win );
	parametres.requested_fields = 0;
	for ( i = 0; i < MAX_DISPLAY_FIELDS; i++ )
	{
		if ( display_fields[i] == NULL )
		{
			break;
		}
		parametres.requested_fields |= 1 << display_fields[i]->identifier;
	}
}
Esempio n. 4
0
int main()
{
    // Allocate a BCH codec Galois order 8 (w/ 2^8-1 == 255 bit codeword size), and 2 bits of
    // correction capacity.  This results in a BCH( 255, 239, 2) codec: 255-bit codeword, 239-bit
    // data payload capacity, hence 255-239 == 16 bits of parity.  Define EZPWD_BCH_CLASSIC to use
    // classic Djelic Linux Kernel API.  Otherwise, uses <ezpwd/bch> 'bch<..>' or 'BCH<...>' classes.
    ezpwd::asserter		assert;
    try {
#if defined( EZPWD_BCH_CLASSIC )
        ezpwd::bch_control                 *bch     = ezpwd::init_bch( 8, 2, 0 );
        if ( ! bch )
    	throw std::logic_error( "Failed to allocate valid BCH codec" );
        ezpwd::bch_control                 &bch_codec( *bch );	// By Galois order, Correction capacity
#else
        //ezpwd::bch_base		bch_codec( 8, 2 );	// By Galois order, Correction capacity, flexibly
        ezpwd::BCH<255,239,2>		bch_codec;	// By Codeword, Payload and Correction capacities, exactly
#endif

#if defined( EZPWD_BCH_FIXED )
        typedef std::array<uint8_t,10>	codeword_t;		// Fixed (parity initialized to 0)
#else
        typedef std::vector<uint8_t>	codeword_t;		// Variable (parity added by encode)
#endif

	codeword_t				codeword= {
	    0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF	// 8 data
	};							// 2 ECC parity

#if defined( EZPWD_BCH_CLASSIC )
	// A BCH codeword's ECC must be zero-initialized for classic Djelic API, and
	// must be added to variable containers
#  if ! defined( EZPWD_BCH_FIXED )
	codeword.resize( 10 );
#  endif
	codeword[8] 				= 0;
	codeword[9] 				= 0;
	ezpwd::encode_bch( &bch_codec, &codeword[0], 8, &codeword[8] );
#else
	// A codeword in a fixed container will not be resized by API; assumes ECC on end. Will
	// initialize to 0.  A variable container will have parity appended by the API.
	bch_codec.encode( codeword );
#endif

	// Place random errors in the codeword and correct, up to the capacity of the BCH codec.
	for ( size_t t = 0; t < 5; ++t ) {
	    for ( size_t e = 0
#if defined( EZPWD_BCH_CLASSIC )
		      ; e < bch_codec.t
#else
		      ; e < bch_codec.t()
#endif
		      ; ++e ) {
		codeword_t		corrupted( codeword );
		// Randomly corrupt from 0 to bch->t bits
		for ( size_t be = 0; be < e; ++be ) {
		    unsigned int	bl	= random_80( randomizer );
		    corrupted[bl/8]	       ^= uint8_t( 1 ) << ( bl % 8 );
		}
		codeword_t		corrected( corrupted );
#if defined( EZPWD_BCH_CLASSIC )
		int corrections			= correct_bch( &bch_codec, &corrected[0], 8, &corrected[8] );
#else
		int corrections			= bch_codec.decode( corrected );
#endif

		if ( assert.ISEQUAL( corrections, int( e ),
				     std::string( "Failed decode of " ) << bch_codec
				     << " codeword w/ " << e << " bit errrors"
				     )) {
		    std::cout << assert << std::endl;
		    continue;
		}

		// Success; If differences were found, they better be in the parity data!
		for ( size_t i = 0; i < 8; ++i )
		    if ( assert.ISEQUAL( corrected[i], codeword[i], 
					 std::string( "Failed recovery of " ) << bch_codec
					 << " codeword w/ " << e << " bit errors" ))
			std::cout << assert << std::endl;
	    }
#if ! defined( EZPWD_BCH_CLASSIC )
	    // Try the inline versions (only available in C++ API)
	    std::string			raw( "abc" );
	    std::string			enc	= bch_codec.encoded( raw );
	    std::string			err	= enc;
	    err[0]			       ^= 0x40;
	    err[2]			       ^= 0x08;
	    std::string			dec	= bch_codec.decoded( err );
	    if ( assert.ISEQUAL( dec.substr( 0, 3 ), raw,
				 std::string( "decoded/encoded of " )	<< bch_codec
				 << " codeword failed, encoded '0x"	<< ezpwd::hexstr( raw )
				 << "' to '0x"				<< ezpwd::hexstr( enc )
				 << "', decoded '0x"			<< ezpwd::hexstr( err )
				 << "' to '0x"				<< ezpwd::hexstr( dec )
				 << "'" ))
		std::cout << assert << std::endl;
#endif
	}
	std::cout
	    << bch_codec << ": ";
    } catch( std::exception &exc ) {
	assert.FAILURE( "Exception", exc.what() );
	std::cout << assert << std::endl;
    }

    if ( assert.failures )
	std::cout
	    << assert.failures << " tests failed." << std::endl;
    else
	std::cout
	    << "All tests passed." << std::endl;
    return assert.failures ? 1 : 0;
}
Esempio n. 5
0
      bool Display::Open()
      {
        // Open curses
        screen=initscr();

        if (screen==NULL) {
          std::cerr << "Cannot initialize curses" << std::endl;
          return false;
        }


#ifdef NCURSES_MOUSE_VERSION
        mousemask(BUTTON1_PRESSED|
                  BUTTON1_RELEASED/*|
                  BUTTON1_CLICKED|
                  BUTTON1_DOUBLE_CLICKED|
                  BUTTON1_TRIPLE_CLICKED*/,NULL);
#endif

        // Check availibility of colors
        colorDepth=1;
        colorMode=colorModeMonochrome;

        if (has_colors() && start_color()!=ERR && COLORS>=8) {
          colorMode=colorModeColor;
          colorDepth=4;
        }

        // Basic curses initialisation
        curs_set(0);
        noecho();
        cbreak();
        nonl();
        raw();
        //Images::Factory::Set(OS::Factory::factory->CreateImageFactory(this));

        screenWidth=COLS;
        screenHeight=LINES;

        workAreaWidth=screenWidth;
        workAreaHeight=screenHeight;

        type=typeTextual;

        EvaluateDisplaySize();

        for (int c=1; c<COLOR_PAIRS; c++) {
          if (init_pair(c,c%COLORS,c/COLORS)==ERR) {
            std::cerr << c << " " << c%COLORS << " " << c/COLORS << std::endl;
            std::cerr << "Cannot initialize terminal color pairs" << std::endl;
            colorDepth=1;
            colorMode=colorModeMonochrome;
            break;
          }
        }

        propFont=driver->CreateFont();
        propFont=propFont->Load();
        propFontSize=1;

        fixedFont=driver->CreateFont();
        fixedFont=fixedFont->Load();
        fixedFontSize=1;

        theme=new Theme(this);

        for (size_t i=0; i<colorCount; i++) {
          color[i]=theme->GetColor((ColorIndex)i);
        }

        multiClickTime=200;

        eventLoop=new UnixEventLoop();
        eventLoop->AddSource(new CursesEventSource(this));

        return true;
      }
 inline /*-*/ uint64_t* raw64(word_t a) /*-*/ { assert(a==last_addr); return (uint64_t*) raw(a); }
Esempio n. 7
0
int main(int argc, char* argv[]) {
    char * enclave_path = argv[1];
    int vm_id = atoi(argv[2]);
    int ctrl_fd;
    int cons_fd;

    use_curses = 1;

    if (argc < 3) {
	printf("usage: v3_cons_sc <enclave_device> <vm_id>\n");
	return -1;
    }

    /* Check for minimum Terminal size at start */
    if (check_terminal_size() != 0) {
        printf ("Error: terminal too small!\n");
        return -1;
    }



    ctrl_fd = pet_ioctl_path(enclave_path, PISCES_ENCLAVE_CTRL_CONNECT, NULL);



    if (ctrl_fd < 0) {
	printf("Error opening enclave control channel\n");
	return -1;
    }

    cons_fd = pet_ioctl_fd(ctrl_fd, PISCES_CMD_VM_CONS_CONNECT, (void *)(uint64_t)vm_id); 

    close(ctrl_fd);

    if (cons_fd < 0) {
	printf("Error opening VM console\n");
	close(cons_fd);
	return -1;
    }

    tcgetattr(STDIN_FILENO, &console.termios_old);
    atexit(handle_exit);

    console.x = 0;
    console.y = 0;


    if (use_curses) {
	gettmode();
	console.win = initscr();
	
	if (console.win == NULL) {
	    fprintf(stderr, "Error initialization curses screen\n");
	    exit(-1);
	}

	scrollok(console.win, 1);

	erase();
    }

    /*
    termios = console.termios_old;
    termios.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | IGNPAR);
    termios.c_iflag &= ~(INLCR | INPCK | ISTRIP | IXOFF | IXON | PARMRK); 
    //termios.c_iflag &= ~(ICRNL | INLCR );    

    //  termios.c_iflag |= SCANCODES; 
    //    termios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); 
    //termios.c_lflag &= ~(ICANON | IEXTEN | ISIG | NOFLSH);
    termios.c_lflag &= ~(ICANON | ECHO);

    termios.c_cc[VMIN] = 1;
    termios.c_cc[VTIME] = 0;

    tcflush(STDIN_FILENO, TCIFLUSH);
    tcsetattr(STDIN_FILENO, TCSANOW, &termios);
    */    

    raw();
    cbreak();
    noecho();
    keypad(console.win, TRUE);

    //ioctl(STDIN_FILENO, KDSKBMODE, K_RAW);

    while (1) {
	int ret; 
	fd_set rset;

	FD_ZERO(&rset);
	FD_SET(cons_fd, &rset);
	FD_SET(STDIN_FILENO, &rset);

	ret = select(cons_fd + 1, &rset, NULL, NULL, NULL);
	
	//	printf("Returned from select...\n");

	if (ret == 0) {
	    continue;
	} else if (ret == -1) {
	    perror("Select returned error...\n");
	    return -1;
	}

	if (FD_ISSET(cons_fd, &rset)) {
	    if (handle_console_msg(cons_fd) == -1) {
		printf("Console Error\n");
		return -1;
	    }
	}

	if (FD_ISSET(STDIN_FILENO, &rset)) {
	    int key = getch();



	    if (key == 27) { // ESC
		int key2 = getch();

		if (key2 == '`') {
		    break;
		} else if (key2 == 27) {
		    unsigned char sc = 0;
		    sc = 0x01;
		    writeit(cons_fd, sc);
		    sc |= 0x80;
		    writeit(cons_fd, sc);
		} else {
		    unsigned char sc = 0;

		    sc = 0x1d;  // left ctrl down
		    writeit(cons_fd,sc);

		    if (send_char_to_palacios_as_scancodes(cons_fd, key2)) {
			printf("Error sending key to console\n");
			return -1;
		    }

		    sc = 0x1d | 0x80;   // left ctrl up
		    writeit(cons_fd,sc); 
		}
		


	  } else if (key == KEY_LEFT) { // LEFT ARROW
		unsigned char sc = 0;
		//	sc = 0xe0;
		//writeit(cons_fd, sc);
		sc = 0x4B;
		writeit(cons_fd, sc);
		sc = 0x4B | 0x80;;
		writeit(cons_fd, sc);
		//sc = 0xe0 | 0x80;
		//writeit(cons_fd, sc);
	    } else if (key == KEY_RIGHT) { // RIGHT ARROW
		unsigned char sc = 0;
		//sc = 0xe0;
		//writeit(cons_fd, sc);
		sc = 0x4D;
		writeit(cons_fd, sc);
		sc = 0x4d | 0x80;
		writeit(cons_fd, sc);
		//sc = 0xe0 | 0x80;
		//writeit(cons_fd, sc);
	    } else if (key == KEY_UP) { // UP ARROW
		unsigned char sc = 0;
		//sc = 0xe0;
		//writeit(cons_fd, sc);
		sc = 0x48;
		writeit(cons_fd, sc);
		sc = 0x48 | 0x80;
		writeit(cons_fd, sc);
		//sc = 0xe0 | 0x80;
		//writeit(cons_fd, sc);
	    } else if (key == KEY_DOWN) { // DOWN ARROW
		unsigned char sc = 0;
		//	sc = 0xe0;
		//writeit(cons_fd, sc);
		sc = 0x50;
		writeit(cons_fd, sc);
		sc = 0x50 | 0x80;
		writeit(cons_fd, sc);
		//sc = 0xe0 | 0x80;
		//writeit(cons_fd, sc);


            } else {
		if (send_char_to_palacios_as_scancodes(cons_fd,key)) {
		    printf("Error sending key to console\n");
		    return -1;
		}
	    }
	    
	}
    } 

    erase();

    printf("Console terminated\n");

    close(cons_fd);

    return 0; 
}
Esempio n. 8
0
int main(int argc, char *argv[])
{

    if (argc != 10 || !strncmp(argv[1],"-h",2))
    {
        puts("DrawLineSegment: Prints a line through two given points");
        puts("USAGE: ./DrawLineSegment x");
        return 0;
    }

    initscr();			/* Start curses mode 		*/
    raw();				/* Line buffering disabled	*/
    noecho();			/* Don't echo() while we do getch */

    start_color();			/* Start color 			*/
    init_pair(1, COLOR_RED, COLOR_RED);
    init_pair(2, COLOR_BLUE, COLOR_BLUE);
    attron(COLOR_PAIR(1));
    curs_set(0);

    double x1 = atof(argv[1]);
    double y1 = atof(argv[2]);

    double x2 = atof(argv[3]);
    double y2 = atof(argv[4]);

    double x3 = atof(argv[5]);
    double y3 = atof(argv[6]);

    double x4 = atof(argv[7]);
    double y4 = atof(argv[8]);

    Pair mid1 = midPoint(x1,y1,x2,y2);
    Pair mid2 = midPoint(x3,y3,x4,y4);
    Pair mid = midPoint(mid1.x,mid1.y,mid2.x,mid2.y);

    Pair rpoint1;
    Pair rpoint2;
    Pair rpoint3;
    Pair rpoint4;

    for (int i = 0; i < 1080; i++)
    {
        rpoint1 = rotateDPoint(mid.x,mid.y,x1,y1,i);
        rpoint2 = rotateDPoint(mid.x,mid.y,x2,y2,i);
        rpoint3 = rotateDPoint(mid.x,mid.y,x3,y3,i);
        rpoint4 = rotateDPoint(mid.x,mid.y,x4,y4,i);

        //draw the starting line

        //draw the midpoint
        attron(COLOR_PAIR(2));
        drawPair(mid);

        //draw rotated about the middle point
        attron(COLOR_PAIR(1));
        drawQuadrilateral(rpoint1.x,rpoint1.y,
                          rpoint2.x,rpoint2.y,
                          rpoint3.x,rpoint3.y,
                          rpoint4.x,rpoint4.y); //draw the shape

        refresh(); /* Print it on to the real screen */
        //sleep() wasn't working too well for me
        for (int j = 0; j <= atol(argv[5])*10000; j++);
        clear();
    }
    getch();			/* Wait for user input */
    endwin();			/* End curses mode		  */

    return 0;
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
  void (*old_hook)(const char *, long, const char *, va_list);
  int use_menu = 1, k_errno;
  char buf[BUFSIZ];

  if ((whoami = strrchr(argv[0], '/')) == NULL)
    whoami = argv[0];
  else
    whoami++;
  if (!(current_li = malloc(sizeof(List_info))))
    {
      sprintf(buf, ": allocating list info");
      goto punt;
    }
  else
    {
      current_li->acl_type = NULL;
      current_li->acl_name = NULL;
      current_li->desc = NULL;
      current_li->modtime = NULL;
      current_li->modby = NULL;
      current_li->modwith = NULL;
    }

  username = mrcl_krb_user();
  if (!username)
    exit(1);
  
  if (mrcl_connect(NULL, "mailmaint", 2, 1))
    exit(2);

  initscr();
  if ((LINES < 24) || (COLS < 60))
    {
      display_buff("Display window too small.\n\n");
      sprintf(buf, "Current window parameters are (%d lines, %d columns)\n",
	      LINES, COLS);
      display_buff(buf);
      display_buff("Please resize your window\n");
      display_buff("to at least 24 lines and 60 columns.\n");
      exit(0);
    }

  raw();
  noecho();
  old_hook = set_com_err_hook(menu_err_hook);
  position[0] = oldpos[0] = 1;
  level = 0;

  pack_main_menu();
  pack_help_menu();
  display_menu(main_menu);
  get_main_input();
  cls();
  endwin();
  set_com_err_hook(old_hook);

  free_menu(main_menu);
  free_menu(help_menu);

  if (current_li->acl_type)
    free(current_li->acl_type);
  if (current_li->acl_name)
    free(current_li->acl_name);
  if (current_li->desc)
    free(current_li->desc);
  if (current_li->modtime)
    free(current_li->modtime);
  if (current_li->modby)
    free(current_li->modby);
  if (current_li->modwith)
    free(current_li->modwith);
  free(current_li);

  mr_disconnect();

  exit(0);

punt:
  com_err(whoami, status, "%s", buf);
  exit(1);
}
Esempio n. 10
0
int
main(int argc, char *argv[])
{
	char *system = NOSTR;
	int i;
	char *p;
	char sbuf[15];

	gid = getgid();
	egid = getegid();
	uid = getuid();
	euid = geteuid();
	if (equal(sname(argv[0]), "cu")) {
		cumode = 1;
		cumain(argc, argv);
		goto cucommon;
	}

	if (argc > 4) {
		(void) fprintf(stderr,
		    "usage: tip [-v] [-speed] [system-name]\n");
		return (1);
	}
	if (!isatty(0)) {
		(void) fprintf(stderr, "tip: must be interactive\n");
		return (1);
	}

	for (; argc > 1; argv++, argc--) {
		if (argv[1][0] != '-')
			system = argv[1];
		else switch (argv[1][1]) {

		case 'v':
			vflag++;
			break;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			BR = atoi(&argv[1][1]);
			break;

		default:
			(void) fprintf(stderr, "tip: %s, unknown option\n",
			    argv[1]);
			break;
		}
	}

	(void) setlocale(LC_CTYPE, "");

	if (system == NOSTR)
		goto notnumber;
	for (p = system; *p; p++)
		if (isalpha(*p))
			goto notnumber;
	/*
	 * System name is really a phone number...
	 * Copy the number then stomp on the original (in case the number
	 *	is private, we don't want 'ps' or 'w' to find it).
	 */
	if (strlen(system) > sizeof (PNbuf) - 1) {
		(void) fprintf(stderr,
		    "tip: phone number too long (max = %d bytes)\n",
		    sizeof (PNbuf) - 1);
		return (1);
	}
	(void) strncpy(PNbuf, system, sizeof (PNbuf) - 1);
	for (p = system; *p; p++)
		*p = '\0';
	PN = PNbuf;
	(void) snprintf(sbuf, sizeof (sbuf), "tip%d", BR);
	system = sbuf;

notnumber:
	(void) signal(SIGINT, (sig_handler_t)cleanup);
	(void) signal(SIGQUIT, (sig_handler_t)cleanup);
	(void) signal(SIGHUP, (sig_handler_t)cleanup);
	(void) signal(SIGTERM, (sig_handler_t)cleanup);

	if ((i = hunt(system)) == 0) {
		(void) printf("all ports busy\n");
		return (3);
	}
	if (i == -1) {
		(void) printf("link down\n");
		delock(uucplock);
		return (3);
	}
	setbuf(stdout, NULL);
	loginit();

	/*
	 * Now that we have the logfile and the ACU open
	 *  return to the real uid and gid.  These things will
	 *  be closed on exit.  The saved-setuid uid and gid
	 *  allows us to get the original setuid permissions back
	 *  for removing the uucp lock.
	 */
	userperm();

	/*
	 * Kludge, there's no easy way to get the initialization
	 *   in the right order, so force it here.
	 * Do the open here, before we change back to real uid.
	 * We will check whether the open succeeded later, when
	 * (and if) we actually go to use the file.
	 */
	if ((PH = getenv("PHONES")) == NOSTR) {
		myperm();
		PH = "/etc/phones";
	}
	phfd = fopen(PH, "r");

	userperm();

	vinit();				/* init variables */
	setparity("none");			/* set the parity table */
	if ((i = speed(number(value(BAUDRATE)))) == NULL) {
		(void) printf("tip: bad baud rate %d\n",
		    number(value(BAUDRATE)));
		myperm();
		delock(uucplock);
		return (3);
	}


	/*
	 * Hardwired connections require the
	 *  line speed set before they make any transmissions
	 *  (this is particularly true of things like a DF03-AC)
	 */
	if (HW)
		ttysetup(i);
	if (p = connect()) {
		(void) printf("\07%s\n[EOT]\n", p);
		myperm();
		delock(uucplock);
		return (1);
	}

	/*
	 * Always setup the tty again here in case hardware flow
	 *  control was selected, which can only be set after the
	 *  connection is made, or in case this is not a hardwired
	 *  modem (rare these days) that likewise can only be setup
	 *  after the connection is made.
	 */
	ttysetup(i);
cucommon:
	/*
	 * From here down the code is shared with
	 * the "cu" version of tip.
	 */

	(void) ioctl(0, TCGETS, (char *)&defarg);
	arg = defarg;
	/* turn off input processing */
	arg.c_lflag &= ~(ICANON|ISIG|ECHO|IEXTEN);
	arg.c_cc[VMIN] = 1;
	arg.c_cc[VTIME] = 0;
	arg.c_iflag &= ~(INPCK|IXON|IXOFF|ICRNL);
	arg.c_oflag = 0;		/* turn off all output processing */
	/* handle tandem mode in case was set in remote file */
	if (boolean(value(TAND)))
		tandem("on");
	else
		tandem("off");
	raw();

	(void) pipe(fildes); (void) pipe(repdes);
	(void) signal(SIGALRM, (sig_handler_t)timeout);

	/*
	 * Everything's set up now:
	 *	connection established (hardwired or dialup)
	 *	line conditioned (baud rate, mode, etc.)
	 *	internal data structures (variables)
	 * so, fork one process for local side and one for remote.
	 */
	if (CM != NOSTR) {
		(void) sleep(2);	/* let line settle */
		parwrite(FD, (unsigned char *)CM, strlen(CM));
	}
	(void) printf(cumode ? "Connected\r\n" : "\07connected\r\n");
	(void) signal(SIGCHLD, (sig_handler_t)deadkid);
	if (pid = fork())
		tipin();
	else
		tipout();
	/*NOTREACHED*/
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
    RedditUserLogged *user = NULL;
    char *subreddit = NULL;
    char *password = NULL, *username = NULL;
    optParser parser;

    DEBUG_START(DEBUG_FILE, DEBUG_FILENAME);

    memset(&parser, 0, sizeof(optParser));

    parser.argc = argc;
    parser.argv = argv;

    optAddOptions (&parser, mainOptions, MOPT_ARG_COUNT);

    handleArguments(&parser);

    if (mainOptions[MOPT_HELP].isSet) {
        displayHelp(&parser);
        return 0;
    }

    optClearParser(&parser);

    setlocale(LC_CTYPE, "");


    initscr();
    raw();//We want character for character input
    keypad(stdscr,1);//Enable extra keys like arrowkeys
    noecho();
    start_color();
    use_default_colors();
    init_pair(1, -1, -1);
    init_pair(2, COLOR_BLACK, COLOR_WHITE);

    DEBUG_PRINT(L"Starting...\n");

    /* Start libreddit */
    redditGlobalInit();

    globalState = redditStateNew();

    globalState->userAgent = redditCopyString("cReddit/0.0.1");

    redditStateSet(globalState);

    if (mainOptions[MOPT_USERNAME].isSet) {
        username = mainOptions[MOPT_USERNAME].svalue;
        if (!mainOptions[MOPT_PASSWORD].isSet)
            password = getPassword();
        else
            password = mainOptions[MOPT_PASSWORD].svalue;

        user = redditUserLoggedNew();
        redditUserLoggedLogin(user, username, password);

        /* Don't want to leave that important Reddit password in memory */
        memset(password, 0, strlen(password));
        if (!mainOptions[MOPT_PASSWORD].isSet)
            free(password);
    }
    if (mainOptions[MOPT_SUBREDDIT].isSet) {
        subreddit = mainOptions[MOPT_SUBREDDIT].svalue;
        if (!startsWith("/r/", subreddit) && strcmp("/", subreddit) != 0)
            prepend("/r/", subreddit);

    } else {
        subreddit = "/";
    }
    showSubreddit(subreddit);

    redditUserLoggedFree(user);
    redditStateFree(globalState);
    redditGlobalCleanup();
    endwin();

    DEBUG_END(DEBUG_FILE);
    return 0;
}
Esempio n. 12
0
static int ncurses_init_graphics(caca_display_t *dp)
{
    static int curses_colors[] =
    {
        /* Standard curses colours */
        COLOR_BLACK,
        COLOR_BLUE,
        COLOR_GREEN,
        COLOR_CYAN,
        COLOR_RED,
        COLOR_MAGENTA,
        COLOR_YELLOW,
        COLOR_WHITE,
        /* Extra values for xterm-16color */
        COLOR_BLACK + 8,
        COLOR_BLUE + 8,
        COLOR_GREEN + 8,
        COLOR_CYAN + 8,
        COLOR_RED + 8,
        COLOR_MAGENTA + 8,
        COLOR_YELLOW + 8,
        COLOR_WHITE + 8
    };

    mmask_t newmask;
    int fg, bg, max;

    dp->drv.p = malloc(sizeof(struct driver_private));

#if defined HAVE_GETENV && defined HAVE_PUTENV
    ncurses_install_terminal(dp);
#endif

#if defined HAVE_SIGNAL
    sigwinch_d = dp;
    signal(SIGWINCH, sigwinch_handler);
#endif

#if defined HAVE_LOCALE_H
    setlocale(LC_ALL, "");
#endif

    _caca_set_term_title("caca for ncurses");

    initscr();
    keypad(stdscr, TRUE);
    nonl();
    raw();
    noecho();
    nodelay(stdscr, TRUE);
    curs_set(0);

    /* Activate mouse */
    newmask = REPORT_MOUSE_POSITION | ALL_MOUSE_EVENTS;
    mousemask(newmask, &dp->drv.p->oldmask);
    mouseinterval(-1); /* No click emulation */

    /* Set the escape delay to a ridiculously low value */
    ESCDELAY = 10;

    /* Activate colour */
    start_color();

    /* If COLORS == 16, it means the terminal supports full bright colours
     * using setab and setaf (will use \e[90m \e[91m etc. for colours >= 8),
     * we can build 16*16 colour pairs.
     * If COLORS == 8, it means the terminal does not know about bright
     * colours and we need to get them through A_BOLD and A_BLINK (\e[1m
     * and \e[5m). We can only build 8*8 colour pairs. */
    max = COLORS >= 16 ? 16 : 8;

    for(bg = 0; bg < max; bg++)
        for(fg = 0; fg < max; fg++)
        {
            /* Use ((max + 7 - fg) % max) instead of fg so that colour 0
             * is light gray on black. Some terminals don't like this
             * colour pair to be redefined. */
            int col = ((max + 7 - fg) % max) + max * bg;
            init_pair(col, curses_colors[fg], curses_colors[bg]);
            dp->drv.p->attr[fg + 16 * bg] = COLOR_PAIR(col);

            if(max == 8)
            {
                /* Bright fg on simple bg */
                dp->drv.p->attr[fg + 8 + 16 * bg] = A_BOLD | COLOR_PAIR(col);
                /* Simple fg on bright bg */
                dp->drv.p->attr[fg + 16 * (bg + 8)] = A_BLINK
                                                    | COLOR_PAIR(col);
                /* Bright fg on bright bg */
                dp->drv.p->attr[fg + 8 + 16 * (bg + 8)] = A_BLINK | A_BOLD
                                                        | COLOR_PAIR(col);
            }
        }

    caca_add_dirty_rect(dp->cv, 0, 0, dp->cv->width, dp->cv->height);
    dp->resize.allow = 1;
    caca_set_canvas_size(dp->cv, COLS, LINES);
    dp->resize.allow = 0;

    return 0;
}
Esempio n. 13
0
char *Buffer::current() const {
    return raw(_cur);
}
Esempio n. 14
0
char *Buffer::alloc(size_t sz) {
    grow(sz);
    char *p = raw(_end);
    _end += sz;
    return p;
}
Esempio n. 15
0
void
gui_main_get_password (const char **prompt, char *password, int size)
{
    int line, i, ch;

    initscr ();
    cbreak ();
    noecho ();
    raw ();

    clear();

    line = 0;

    while (prompt[line])
    {
        mvaddstr (line, 0, prompt[line]);
        line++;
    }

    mvaddstr (line, 0, "=> ");
    refresh ();

    memset (password, '\0', size);
    i = 0;
    while (i < size - 1)
    {
        ch = getch ();
        /* enter */
        if (ch == '\n')
            break;
        /* ctrl-C */
        if (ch == 3)
        {
            password[0] = 3;
            i = 1;
            break;
        }
        if (ch == 127)
        {
            if (i > 0)
            {
                i--;
                password[i] = '\0';
                mvaddstr (line, 3 + i, " ");
                move (line, 3 + i);
            }
        }
        else
        {
            password[i] = ch;
            mvaddstr (line, 3 + i, "*");
            i++;
        }
        refresh ();
    }
    password[i] = '\0';

    refresh ();
    endwin ();
}
Esempio n. 16
0
// function to test threads
// This function will run concurrently.
void* avatar(void* ptr) {

    // Initial variables
    int sockfd = 0;
    struct sockaddr_in servaddr;
    avatarInfo a = *((avatarInfo *) ptr);
    fprintf(a.pLog, "\n\nTHREAD FOR %i", a.avID);

    ///////////////////////// create socket

    //Create a socket for the client
    //If sockfd<0 there was an error in the creation of the socket
    if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
        perror("Problem in creating the socket");
        exit(2);
    }

    //Creation of the socket
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr= inet_addr(a.ip);
    servaddr.sin_port =  htons(a.MazePort); //convert to big-endian order

    //Connection of the client to the socket
    int connected = connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    if (connected <0) {
        perror("Problem in connecting to the server");
        exit(3);
    }
    fprintf(a.pLog, "Avatar %d connected to socket: %i\n", a.avID, connected);


    //////////////////////////// send initial message

    AM_Message *ready = calloc(1, sizeof(AM_Message));
    if (!ready) {
        perror("No memory\n");
        exit(4);
    }

    ready->type = htonl(AM_AVATAR_READY);
    ready->avatar_ready.AvatarId = htonl(a.avID);

    //send ready message to server
    int sent = send(sockfd, ready, sizeof(AM_Message), 0);
    fprintf(a.pLog, "Avatar ready message sent: %i, for av %i\n", sent, a.avID);
    free(ready);
    sleep(1);

    ////////////////////////// initialize a move message and a rec message

    AM_Message *rec_message = calloc(1, sizeof(AM_Message));
    if(!rec_message) {
        perror("\nNo memory");
        exit(4);
    }

    ////////////////////////////////// listen to server

    while (1) {
        memset(rec_message, 0, sizeof(AM_Message));
        //printf("\n thread %i, socket %i", a.avID, sockfd);
        int x = recv(sockfd, rec_message, sizeof(AM_Message), 0);
        if ( x== 0) {
            //error: server terminated prematurely
            //printf("\n server error");
            return NULL;
        }

        ///////////////////////////////////////// if turnID matches avID, make a move
        if(ntohl(rec_message->type) == AM_AVATAR_TURN) {
            pthread_mutex_lock(&turn_lock);
            // if turn id is my id
            int move = -1;
            if(ntohl(rec_message->avatar_turn.TurnId) == a.avID) {
                // write board to the log
                fprintf(a.pLog, "\n\nits my turn: %i", a.avID);
                fprintf(a.pLog, "\nCurrent board:");
                XYPos pos;
                //look through the positions received from the server and add them to the Avatars, if they aren't there, or use them to update the maze based on the last move
                for(int b = 0; b < a.nAvatars; b++) {
                    pos.x = ntohl(rec_message->avatar_turn.Pos[b].x);
                    pos.y = ntohl(rec_message->avatar_turn.Pos[b].y);
                    fprintf(a.pLog, "\nPosition of avatar %i - x: %i y: %i", b,pos.x, pos.y);
                    //printf("\nCurrent position of avatar %i - x: %i y: %i", b,pos.x, pos.y);
                    //printf("\nAvatar %d: pos.x: %i, pos.y: %i, direction: %d, last_move: %d \n", b, Avatars[b].pos.x, Avatars[b].pos.y, Avatars[b].direction, Avatars[b].last_move);
                    if (Avatars[b].last_move == -1) { //if the avatar doesn't have a position yet
                        Avatars[b].pos = pos;
                        Avatars[b].last_move = M_NULL_MOVE;
                    }
                    else if (Avatars[b].last_move != M_NULL_MOVE) {
                        if ((pos.x == Avatars[b].pos.x) && (pos.y == Avatars[b].pos.y)) {
                            fprintf(a.pLog, "Avatar %d encountered a wall and did not move.", b);
                            AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 1);
                            Avatars[b].last_move = M_NULL_MOVE;
                        }
                        else {
                            fprintf(a.pLog, "Avatar %d moved successfully.", b);
                            switch(Avatars[b].last_move) {
                            case M_NORTH:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].north_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_SOUTH:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].south_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_EAST:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].east_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_WEST:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].west_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            default:
                                AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                break;
                            }
                            Avatars[b].pos = pos;
                            Avatars[b].direction = Avatars[b].last_move;
                            Avatars[b].last_move = M_NULL_MOVE;
                        }
                    }

                }

                ////////////////graphics////////////////
                //initscr();
                clear();
                raw();
                //start_color();
                create_border(maze->num_col, maze->num_row);
                draw_inside(maze);
                //draw_fakes(maze);
                int f;
                for (f = 0; f<a.nAvatars; f++) {
                    draw_avatar(2*Avatars[f].pos.y+1, 2*Avatars[f].pos.x+1);
                }
                //unsigned int microseconds;
                //microseconds = 200;
                //usleep(microseconds);
                refresh();

                /* Determine the direction of the move for the current Avatar */

                /* Avatar 0 has a fixed location - it never moves */
                if (a.avID == 0) {
                    if(!final_destination) {
                        final_destination = (XYPos *) calloc(1, sizeof(XYPos));
                        final_destination->x = Avatars[a.avID].pos.x;
                        final_destination->y = Avatars[a.avID].pos.y;
                    }
                    move = M_NULL_MOVE;
                }
                // if(!final_destination){
                //   for(int i = 0; i < a.nAvatars; i++){
                //     if (i == a.avID) continue;
                //     //if the Avatar is in the same place as another Avatar, save position as final_destination
                //     if((Avatars[i].pos.x == Avatars[a.avID].pos.x) && (Avatars[i].pos.y == Avatars[a.avID].pos.y)){
                //       final_destination = (XYPos *) calloc(1, sizeof(XYPos));
                //       final_destination->x = Avatars[a.avID].pos.x;
                //       final_destination->y = Avatars[a.avID].pos.y;
                //       move = M_NULL_MOVE;
                //       break;
                //     }
                //   }
                // }
                /* Determine the direction of the move for Avatars that aren't Avatar 0 */
                //if Avatar is at final_destination, it should not move
                if((final_destination) && (Avatars[a.avID].pos.x == final_destination->x) && (Avatars[a.avID].pos.y == final_destination ->y)) {
                    move = M_NULL_MOVE;
                }
                else { //if the Avatar is alone, use the rightHandRule to determine the next move
                    move = rightHandRule(Avatars[a.avID]);
                }

                //temporary fix to diagnose the initial -1 rightHandRule return
                if(move == -1) {
                    ClearFakeWalls(Avatars[a.avID].pos.y, Avatars[a.avID].pos.x);
                    move = rightHandRule(Avatars[a.avID]);
                    move = (move == -1) ? M_NULL_MOVE : move;
                }
                Avatars[a.avID].last_move = move;
                //int move = rand() % 4;
                // write move to the log
                fprintf(a.pLog, "\nMove: %i", move);
                //printf("\nMove: %i", move);

                //send a move message for the current avatar
                AM_Message *ready = calloc(1, sizeof(AM_Message));
                if (!ready) {
                    perror("No memory\n");
                    exit(4);
                }
                ready->type = htonl(AM_AVATAR_MOVE);
                ready->avatar_move.AvatarId = htonl(a.avID);
                ready->avatar_move.Direction =htonl(move);

                //send ready message to server
                int sent = send(sockfd, ready, sizeof(AM_Message), 0);
                fprintf(a.pLog, "\nAvatar move message sent: %i, for av %i", sent, a.avID);
                free(ready);
                //sleep(1);
            }
            pthread_mutex_unlock(&turn_lock);
        }

        // else if the message is success, break
        else if(ntohl(rec_message->type) == AM_MAZE_SOLVED) {
            pthread_mutex_lock(&solved_lock);
            if(!thread_return) {
                time_t myTime;
                char buff[100];
                thread_return = (char *) calloc(100, sizeof(char));
                myTime = time(NULL);
                strftime(buff, 100, "%a %d %Y, %H:%M", localtime(&myTime));
                //printf("%s\n", buff);
                sprintf(thread_return, "\nMaze Solved on %s!\n", buff);
                //printf("\nSolved!\n");
                //free(rec_message);
                //free(ptr);
            }

            //stop at solution, wait for an input to end graphics
            //refresh();
            //sleep(1);
            //clear();
            //printw("Maze solved!");
            //getch();
            //clear();
            //endwin();
            //delwin(stdscr);

            if(a.avID == 0) {
                //stop at solution, wait for an input to end graphics
                refresh();
                sleep(1);
                clear();
                printw("Maze solved!");
                getch();
                clear();
                //endwin();
            }
            pthread_mutex_unlock(&solved_lock);
            break;
        }

        else if(ntohl(rec_message->type) == AM_TOO_MANY_MOVES) {
            pthread_mutex_lock(&too_many_moves_lock);
            printf("\nToo many moves! You lose.\n");
            //fprintf(a.pLog,"\nToo many moves! You lose.\n");
            thread_return = "\nToo many moves! You lose.\n";
            //free(rec_message);
            //free(ptr);
            pthread_mutex_unlock(&too_many_moves_lock);
            break;
        }

        else if(IS_AM_ERROR(ntohl(rec_message->type))) {
            pthread_mutex_lock(&error_lock);
            thread_return = (char *) calloc(100, sizeof(char));
            printf("\nReceived Error code\n");
            sprintf(thread_return, "\nReceived Error code: %u\n", ntohl(rec_message->type));
            //free(rec_message);
            //free(ptr);
            pthread_mutex_unlock(&error_lock);
            break;
        }
    }
    //CleanupMaze();
    free(rec_message);
    free(ptr);
    pthread_exit(thread_return);
}
Esempio n. 17
0
/*! Tries to write the image object to the given fileName.
    Returns true on success.
*/
bool DATImageFileType::write(const Image *image,
                             const Char8 *fileName)
{
    initTypeMap();

    // ok we write always in big endian.
#if BYTE_ORDER == LITTLE_ENDIAN
    Image *pSwapImage = const_cast<Image *>(&(*image));

    pSwapImage->swapDataEndian();
#endif

    std::ofstream dat(fileName, std::ios::binary);

    if(!dat)
    {
        SWARNING << "DATImageFileType::write : Can not open output stream "
                 << "for file '"
                 << fileName
                 << "'!"
                 << std::endl;

        return false;
    }

    Real64 sT[3];
    sT[0] = sT[1] = sT[2] = 1.0;

    const std::string *attr = image->findAttachmentField("SliceThickness");

    if(attr != NULL)
        sscanf(attr->c_str(), "%lf %lf %lf", &sT[0], &sT[1], &sT[2]);

    std::string format = "UCHAR";

    for(std::map<std::string, FormatDesc>::iterator it = _formatStrMap.begin();
        it != _formatStrMap.end();
        ++it)
    {
        if((*it).second.type == image->getDataType())
        {
            format = (*it).first;
            break;
        }
    }

    std::string basename = fileName;
    std::string::size_type i = basename.rfind(".");

    if(i != std::string::npos)
        basename = basename.substr(0, i);

    basename += ".raw";

    std::string name = basename;

    i = name.rfind("/");

    // on windows also a / is possible!
#if defined(WIN32)
    if(i == std::string::npos)
        i = name.rfind("\\");
#endif

    if(i != std::string::npos)
        name = name.substr(i+1);

    dat << "ObjectFileName: " << name << "\n";
    dat << "TaggedFileName: ---\n";
    dat << "Resolution:     " << image->getWidth() << " " << image->getHeight()
        << " "                << image->getDepth() << "\n";
    dat << "SliceThickness: " << sT[0] << " " << sT[1] << " " << sT[2] << "\n";
    dat << "Format:         " << format << "\n";
    dat << "NbrTags:        0\n";
    dat << "ObjectType:     TEXTURE_VOLUME_OBJECT\n";
    dat << "ObjectModel:    DENSITY\n";
    dat << "GridType:       EQUIDISTANT\n";

    if(image->getBpp() > 1)
      dat << "Channel: " << image->getBpp() << "\n";

    dat.close();

    std::ofstream raw(basename.c_str(), std::ios::binary);

    if(!raw)
    {
        SWARNING << "DATImageFileType::write : Can not open output stream "
                 << "for file '"
                 << basename
                 << "'!"
                 << std::endl;

        return false;
    }

    raw.write (reinterpret_cast<const char *>(image->getData()), 
               image->getSize());
    raw.close();

    // restore to original endian
#if BYTE_ORDER == LITTLE_ENDIAN
    pSwapImage->swapDataEndian();
#endif

    /*
    ofstream out(fileName);
    Head head;
    const void *headData = (void*)(&head);
    unsigned dataSize = image.getSize(), headSize = sizeof(Head);

    head.pixelFormat  = image.getPixelFormat();
    head.width        = image.getWidth();
    head.height       = image.getHeight();
    head.depth        = image.getDepth();
    head.mipmapCount  = image.getMipMapCount();
    head.frameCount   = image.getFrameCount();
    head.frameDelay   = short(image.getFrameDelay() * 1000.0);
    head.hostToNet();

    if ( out && out.write(static_cast<const char *>(headData), headSize) &&
         dataSize &&
             out.write((char *)(image.getData()), dataSize) )
            retCode = true;
    else
        retCode = false;
    */

    return true;
}
Esempio n. 18
0
	pointer_wrapper<T>::operator typename pointer_wrapper<T>::pointer()
	{
		return raw();
	}
 inline const uint64_t* raw64(word_t a) const { assert(a==last_addr); return (uint64_t*) raw(a); }
Esempio n. 20
0
	pointer_wrapper<T>::operator typename pointer_wrapper<T>::const_pointer() const
	{
		return raw();
	}
Esempio n. 21
0
File: menus.c Progetto: aspacsa/vlp
void main_menu(const char *curr_path) {
  const char *menu_title = "Main Menu";
  int choice;
  char curr_menu_path[BUFSIZ];
  sprintf(curr_menu_path, "%s > %s", curr_path, menu_title );

  void (*farray[])(const char*) = { cases_menu,
                                    summons_menu,
                                    actions_menu,
                                    reports_menu,
                                    setup_menu,
                                    dbutils_menu
                                  }; 
  initscr();
  raw();
  while(choice != 7) {
    choice = 0;
    noecho();
    curs_set(0);
    clear();
    mvprintw(0, 0, curr_menu_path);
    mvprintw(4, 10, "1. Cases");
    mvprintw(6, 10, "2. Summons");
    mvprintw(8, 10, "3. Actions");
    mvprintw(10, 10, "4. Reports");
    mvprintw(12, 10, "5. Setup");
    mvprintw(14, 10, "6. DB Utils");
    mvprintw(16, 10, "7. Exit");
    mvprintw(18, 10, "Select an option from the above menu, use only the numbers for selection.");
    refresh();
    choice = getch();
    switch(choice) {
      case '1':
        choice = 0;
        break;  
      case '2':
        choice = 1;
        break;
      case '3':
        choice = 2;
        break;
      case '4':
        choice = 3;
        break;
      case '5':
        choice = 4;
        break;
      case '6':
        choice = 5;
        break;
      case '7':
        choice = 7;
        break;
      default:
        beep();
        break;
    }
    if (choice < 7)
      farray[choice](curr_menu_path);
  }
  endwin();
  return;
}
Esempio n. 22
0
static void
do_curses(struct VSM_data *vd)
{
	pthread_t thr;
	int ch;

	if (pthread_create(&thr, NULL, accumulate_thread, vd) != 0) {
		fprintf(stderr, "pthread_create(): %s\n", strerror(errno));
		exit(1);
	}

	initscr();
	raw();
	noecho();
	nonl();
	intrflush(stdscr, FALSE);
	curs_set(0);
	erase();
	for (;;) {
		pthread_mutex_lock(&mtx);
		update(vd);
		pthread_mutex_unlock(&mtx);

		timeout(delay * 1000);
		switch ((ch = getch())) {
		case ERR:
			break;
#ifdef KEY_RESIZE
		case KEY_RESIZE:
			erase();
			break;
#endif
		case '\014': /* Ctrl-L */
		case '\024': /* Ctrl-T */
			redrawwin(stdscr);
			refresh();
			break;
		case '\003': /* Ctrl-C */
			raise(SIGINT);
			break;
		case '\032': /* Ctrl-Z */
			endwin();
			raise(SIGTSTP);
			break;
		case '\021': /* Ctrl-Q */
		case 'Q':
		case 'q':
			endwin();
			return;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			delay = 1 << (ch - '0');
			break;
		default:
			beep();
			break;
		}
	}
}
Esempio n. 23
0
 std::string MoveSplineFlag::ToString() const
 {
     std::string str;
     print_flags(raw(),g_SplineFlag_names,str);
     return str;
 }
Esempio n. 24
0
void config_read(void)
{
	uint8_t choice=0;
	
	if(read_from_EEPROM(1) != 48)
	{
		while(1)
		{
			choice = uart_getchar();
			putchar('\n');
			putchar('\r');
			
			if(choice=='1')
			{
				while(!(UCSR0A & (1 << RXC0)))print_adxl345();
				config_menu();
			}
			else if(choice=='2')
			{
				while(!(UCSR0A & (1 << RXC0)))
				{
					print_hmc5883();
					delay_ms(100);//at least 100ms interval between measurements
				}
				config_menu();
			}
			else if(choice=='3')
			{
				while(!(UCSR0A & (1 << RXC0)))print_itg3200();
				config_menu();
			}
			else if(choice=='4')
			{
				while(!(UCSR0A & (1 << RXC0)))raw();
				config_menu();
			}
			else if(choice=='5')
			{
				baud_menu();
				config_menu();
			}
			else if(choice==0x10) //if ctrl-p
			{
				self_test();
			}
			else if(choice==0x1A) //if ctrl-z
			{
				write_to_EEPROM(1,48);
				auto_raw();
			}
			else if(choice==0x3F) //if ?
			{
				help();
				while(!(UCSR0A & (1 << RXC0)));
				config_menu();
			}
			else if(choice==0xFF) config_read();
		}
	}else auto_raw();

}
Esempio n. 25
0
void
tty_raw_mode (void)
{
    raw ();                     /* FIXME: uneeded? */
    cbreak ();
}
Esempio n. 26
0
void * user_interface(void *q)
{
    char line[100];
    int i, index;
	int height = 6;
	int width = 40;
	int starty;
	int startx;
	int int_value;
	WINDOW *login_window, *info_window, *help_window;

	initscr();
	raw();
	cbreak();
	keypad(stdscr, TRUE);

    box(stdscr, 0, 0);

    attron(A_BOLD);
    mvaddstr(1, COLS/2-6, "Gopiggy! 0.2");
    refresh();
    attroff(A_BOLD);

    sleep(1);
	starty = (LINES - height) / 2;	/* Calculating for a center placement */
	startx = (COLS - width) / 2;	/* of the window		*/
    login_window = newwin(height, width, starty, startx);
    box(login_window, 0, 0);
    wrefresh(login_window);

    mvwprintw(login_window, 1, 2, "Num of piggy in a race (max: 10): ");
    f_num_pigs = wgetch(login_window) - 48;
    wrefresh(login_window);
    mvwprintw(login_window, 2, 2, "Name of your piggy: ");
    wgetstr(login_window, line);

	piggy_assign_names(line);

    sleep(1);

    for (i = 0; i < height; i++)
    {
    	for (index = 0; index < width; index++)
    	{
    		mvwprintw(login_window, i, index, "	");/*It's not a space but a tab. */
    	}
    }
    wrefresh(login_window);
    delwin(login_window);

    info_window = newwin(f_num_pigs+2, 50, LINES-(f_num_pigs+2), 2);
    wprintw(info_window, "Rank - Name - Position - Speed - Status");
	for (i = 0; i < f_num_pigs; ++i)
	{
		mvwprintw(info_window, i+1, 0, "%c      %s      %d         %d     %s", ' ', f_pigs[i].name, f_pigs[i].current_position, f_pigs[i].current_speed, "Ready");
	}
    wrefresh(info_window);

    help_window = newwin(3, 36, LINES-5, COLS-37);
    wprintw(help_window, "What's happening?");
    mvwprintw(help_window, 0, 0, "GoPiggy! Copyright@Murphy Meng 2012");
    mvwprintw(help_window, 1, 0, "    'g' - go piggy!");
    mvwprintw(help_window, 2, 0, "    'q' - quit the game.");
    wrefresh(help_window);

    noecho();

    while(1)
    {
    	if (true != f_game_started)
    	{
			int_value = getch();
			if ('q' == int_value)
			{
				break;
			}
			else if ('g' == int_value)
			{
				(void)sem_post(&sem_game_start);
				f_game_started = true;
			}
    		else
    		{
				/* Do nothing. */
    		}
    	}
    	else
    	{
    		rank_piggy();

    		pthread_mutex_lock(&window_refresh_lock);
    		for (i = 0; i < f_num_pigs; i++)
    		{
    			index = f_ranked_pigs[i];
    			mvwprintw(info_window, i+1, 0, " %d     %s       %d      %d     %s", i, f_pigs[index].name, f_pigs[index].current_position, f_pigs[index].current_speed, f_pigs[index].status);
    		}
    		wrefresh(info_window);

    		pthread_mutex_unlock(&window_refresh_lock);
    	}

    	sleep(1);
    }

    getch();
    endwin();
    pthread_exit(NULL);
}
Esempio n. 27
0
void RecipesView::onFilterSettingsChanged() {
	//PbListMutex().MutexOn();


	sqlite::ITablePtr pIDs;
	g_DBManager.Lock();
	unsigned int charid = m_recipePanel.getCharId();
	std::list<unsigned int> refs = m_recipePanel.getDesiredItemRefs();
	if (refs.size() == 0)
		return;

	// RecipePanel.getIds
	{
		bool first = true;
		std::tstringstream sql;
		sql << _T("SELECT keyhigh, ql, stack FROM tItems WHERE keyhigh in (");
		for (auto it : refs) {
			if (!first)
				sql << _T(",") << it;
			else  {
				sql << it;
				first = false;
			}
			
		}
		sql <<_T(") ");
		if (charid > 0)
			sql << _T(" AND owner = ") << charid;

		pIDs = m_db->ExecTable(sql.str());
	}
	g_DBManager.UnLock();

	if (pIDs == NULL) {
		return;
	}

	std::list<Item> items;
	// Loop all the pattern pieces and searches for recorded items.
	for (unsigned int idIdx = 0; idIdx < pIDs->Rows(); idIdx++) {
		
		std::tstring id = from_ascii_copy(pIDs->Data(idIdx, 0));
		std::tstring ql = from_ascii_copy(pIDs->Data(idIdx, 1));
		std::tstring stack = from_ascii_copy(pIDs->Data(idIdx, 2));

		Item item(boost::lexical_cast<unsigned int>(id));
		item.minql = boost::lexical_cast<unsigned int>(ql);
		item.maxql = boost::lexical_cast<unsigned int>(ql);
		item.count = boost::lexical_cast<unsigned int>(stack);
		items.push_back(item);
	}

	std::set<Item> itemsToShow = m_recipePanel.getItemList(items);


	// Update view


	std::tstringstream out;
	out << _T("<tr><th>QL</th><th>Item</th><th>Comments</th><th>Count</th><th>Required</th></tr>\n");
	for (Item item : itemsToShow) {
			if (item.nCountInDb >= item.count) out << _T("<tr style=\"color:red;\">");
			else out << _T("<tr>");
			out << _T("<th>") << item.minql << "-" << item.maxql 
			<< _T("</th><th>") << item.name
			<< _T("</th><th>") << item.comments
			<< _T("</th><th>") << item.nCountInDb
			<< _T("</th><th>") << item.count
			<< _T("</th></tr>\n");
	}
	HRSRC hrsrc = ::FindResource(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_HTML3), RT_HTML);
	DWORD size = ::SizeofResource(_Module.GetResourceInstance(), hrsrc);
	HGLOBAL hGlobal = ::LoadResource(_Module.GetResourceInstance(), hrsrc);
	void* pData = ::LockResource(hGlobal);
	if (pData != NULL) {
		std::string raw((char*)pData, size);
		std::tstring html = from_ascii_copy(raw);
		boost::algorithm::replace_all(html, _T("%RESULT_TABLE%"), out.str());
		boost::algorithm::replace_all(html, _T("%TITLE%"), m_recipePanel.getRecipeName());
		m_webview.SetHTML(html);
	}

	//PbListMutex().MutexOff();
}
Esempio n. 28
0
File: ui.c Progetto: kotobot/vifm
int
setup_ncurses_interface()
{
    int screen_x, screen_y;
    int i, x, y;

    initscr();
    noecho();
    nonl();
    raw();

    getmaxyx(stdscr, screen_y, screen_x);
    /* screen is too small to be useful*/
    if(screen_y < 10)
        finish("Terminal is too small to run vifm\n");
    if(screen_x < 30)
        finish("Terminal is too small to run vifm\n");

    if(! has_colors())
        finish("Vifm requires a console that can support color.\n");

    start_color();
    // Changed for pdcurses
    use_default_colors();

    x = 0;

    for (i = 0; i < cfg.color_scheme_num; i++)
    {
        for(x = 0; x < 12; x++)
            init_pair(col_schemes[i].color[x].name,
                      col_schemes[i].color[x].fg, col_schemes[i].color[x].bg);
    }

    werase(stdscr);

    menu_win = newwin(screen_y - 1, screen_x , 0, 0);
    wbkgdset(menu_win, COLOR_PAIR(WIN_COLOR));
    werase(menu_win);

    sort_win = newwin(14, 30, (screen_y -12)/2, (screen_x -30)/2);
    wbkgdset(sort_win, COLOR_PAIR(WIN_COLOR));
    werase(sort_win);

    change_win = newwin(20, 30, (screen_y -20)/2, (screen_x -30)/2);
    wbkgdset(change_win, COLOR_PAIR(WIN_COLOR));
    werase(change_win);

    error_win = newwin(10, screen_x -2, (screen_y -10)/2, 1);
    wbkgdset(error_win, COLOR_PAIR(WIN_COLOR));
    werase(error_win);

    lborder = newwin(screen_y - 2, 1, 0, 0);

    wbkgdset(lborder, COLOR_PAIR(BORDER_COLOR));

    werase(lborder);

    if (curr_stats.number_of_windows == 1)
        lwin.title = newwin(0, screen_x -2, 0, 1);
    else
        lwin.title = newwin(0, screen_x/2 -1, 0, 1);

    wattrset(lwin.title, A_BOLD);
    wbkgdset(lwin.title, COLOR_PAIR(BORDER_COLOR));

    werase(lwin.title);

    if (curr_stats.number_of_windows == 1)
        lwin.win = newwin(screen_y - 3, screen_x -2, 1, 1);
    else
        lwin.win = newwin(screen_y - 3, screen_x/2 -2, 1, 1);

    keypad(lwin.win, TRUE);
    wbkgdset(lwin.win, COLOR_PAIR(WIN_COLOR));
    wattrset(lwin.win, A_BOLD);
    wattron(lwin.win, A_BOLD);
    werase(lwin.win);
    getmaxyx(lwin.win, y, x);
    lwin.window_rows = y -1;
    lwin.window_width = x -1;

    mborder = newwin(screen_y, 2, 0, screen_x/2 -1);

    wbkgdset(mborder, COLOR_PAIR(BORDER_COLOR));

    werase(mborder);

    if (curr_stats.number_of_windows == 1)
        rwin.title = newwin(0, screen_x -2  , 0, 1);
    else
        rwin.title = newwin(1, screen_x/2 -1  , 0, screen_x/2 +1);

    wbkgdset(rwin.title, COLOR_PAIR(BORDER_COLOR));
    wattrset(rwin.title, A_BOLD);
    wattroff(rwin.title, A_BOLD);

    werase(rwin.title);

    if (curr_stats.number_of_windows == 1)
        rwin.win = newwin(screen_y - 3, screen_x -2 , 1, 1);
    else
        rwin.win = newwin(screen_y - 3, screen_x/2 -2 , 1, screen_x/2 +1);

    keypad(rwin.win, TRUE);
    wattrset(rwin.win, A_BOLD);
    wattron(rwin.win, A_BOLD);
    wbkgdset(rwin.win, COLOR_PAIR(WIN_COLOR));
    werase(rwin.win);
    getmaxyx(rwin.win, y, x);
    rwin.window_rows = y - 1;
    rwin.window_width = x -1;

    rborder = newwin(screen_y - 2, 1, 0, screen_x -1);

    wbkgdset(rborder, COLOR_PAIR(BORDER_COLOR));

    werase(rborder);

    stat_win = newwin(1, screen_x, screen_y -2, 0);

    wbkgdset(stat_win, COLOR_PAIR(BORDER_COLOR));

    werase(stat_win);

    status_bar = newwin(1, screen_x - 19, screen_y -1, 0);
    keypad(status_bar, TRUE);
    wattrset(status_bar, A_BOLD);
    wattron(status_bar, A_BOLD);
    wbkgdset(status_bar, COLOR_PAIR(STATUS_BAR_COLOR));
    werase(status_bar);

    pos_win = newwin(1, 13, screen_y - 1, screen_x -13);
    wattrset(pos_win, A_BOLD);
    wattron(pos_win, A_BOLD);
    wbkgdset(pos_win, COLOR_PAIR(STATUS_BAR_COLOR));
    werase(pos_win);

    num_win = newwin(1, 6, screen_y - 1, screen_x -19);
    wattrset(num_win, A_BOLD);
    wattron(num_win, A_BOLD);
    wbkgdset(num_win, COLOR_PAIR(STATUS_BAR_COLOR));
    werase(num_win);


    wnoutrefresh(lwin.title);
    wnoutrefresh(lwin.win);
    wnoutrefresh(rwin.win);
    wnoutrefresh(rwin.title);
    wnoutrefresh(stat_win);
    wnoutrefresh(status_bar);
    wnoutrefresh(pos_win);
    wnoutrefresh(num_win);
    wnoutrefresh(lborder);
    wnoutrefresh(mborder);
    wnoutrefresh(rborder);

    return 1;
}
Esempio n. 29
0
void
gui_main_init ()
{
    struct t_gui_buffer *ptr_buffer;
    struct t_gui_bar *ptr_bar;
    struct t_gui_bar_window *ptr_bar_win;
    char title[256];

    initscr ();

    if (CONFIG_BOOLEAN(config_look_eat_newline_glitch))
        gui_term_set_eat_newline_glitch (0);

    curs_set (1);
    noecho ();
    nodelay (stdscr, TRUE);
    raw ();

    gui_color_init ();

    /* build prefixes according to configuration */
    gui_chat_prefix_build ();

    refresh ();

    gui_term_cols  = COLS;
    gui_term_lines = LINES;

    gui_window_read_terminal_size ();

    /* init clipboard buffer */
    gui_input_clipboard = NULL;

    /* get time length */
    gui_chat_time_length = gui_chat_get_time_length ();

    /* init bar items */
    gui_bar_item_init ();

    gui_init_ok = 0;

    /* create core buffer */
    ptr_buffer = gui_buffer_new (NULL, GUI_BUFFER_MAIN,
                                 NULL, NULL, NULL, NULL);
    if (ptr_buffer)
    {
        gui_init_ok = 1;

        ptr_buffer->num_displayed = 1;

        /* set short name */
        if (!ptr_buffer->short_name)
            ptr_buffer->short_name = strdup (GUI_BUFFER_MAIN);

        /* set title for core buffer */
        snprintf (title, sizeof (title), "WeeChat %s %s - %s",
                  version_get_version (),
                  WEECHAT_COPYRIGHT_DATE,
                  WEECHAT_WEBSITE);
        gui_buffer_set_title (ptr_buffer, title);

        /* create main window (using full space) */
        if (gui_window_new (NULL, ptr_buffer, 0, 0,
                            gui_term_cols, gui_term_lines, 100, 100))
        {
            gui_current_window = gui_windows;

            if (CONFIG_STRING(config_look_window_title)
                && CONFIG_STRING(config_look_window_title)[0])
            {
                gui_window_set_title (CONFIG_STRING(config_look_window_title));
            }
        }

        /*
         * create bar windows for root bars (they were read from config,
         * but no window was created, GUI was not initialized)
         */
        for (ptr_bar = gui_bars; ptr_bar; ptr_bar = ptr_bar->next_bar)
        {
            if ((CONFIG_INTEGER(ptr_bar->options[GUI_BAR_OPTION_TYPE]) == GUI_BAR_TYPE_ROOT)
                && (!ptr_bar->bar_window))
            {
                gui_bar_window_new (ptr_bar, NULL);
            }
        }
        for (ptr_bar_win = gui_windows->bar_windows;
             ptr_bar_win; ptr_bar_win = ptr_bar_win->next_bar_window)
        {
            gui_bar_window_calculate_pos_size (ptr_bar_win, gui_windows);
            gui_bar_window_create_win (ptr_bar_win);
        }
    }

    if (CONFIG_BOOLEAN(config_look_mouse))
        gui_mouse_enable ();
    else
        gui_mouse_disable ();

    gui_window_set_bracketed_paste_mode (CONFIG_BOOLEAN(config_look_paste_bracketed));
}
Esempio n. 30
0
int main(int argc, char **argv)
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	node_info_msg_t *node_info_ptr = NULL;
	node_info_msg_t *new_node_ptr = NULL;
	int error_code;
	int height = 40;
	int width = 100;
	int startx = 0;
	int starty = 0;
	int end = 0;
	int i;
	int rc;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_DAEMON, NULL);
	parse_command_line(argc, argv);
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	if (params.cluster_dims == 4) {
		min_screen_width = 92;
	} else if (params.cluster_dims == 3)
		min_screen_width = 92;

	/* no need for this if you are resolving */
	while (slurm_load_node((time_t) NULL,
			       &new_node_ptr, SHOW_ALL)) {
		if (params.resolve || (params.display == COMMANDS)) {
			new_node_ptr = NULL;
			break;		/* just continue */
		}
		error_code = slurm_get_errno();
		printf("slurm_load_node: %s\n",
		       slurm_strerror(error_code));
		if (params.iterate == 0)
			exit(1);
		sleep(10);	/* keep trying to reconnect */
	}

	select_g_ba_init(new_node_ptr, 0);

	if (dim_size == NULL) {
		dim_size = get_cluster_dims(new_node_ptr);
		if ((dim_size == NULL) || (dim_size[0] < 1))
			fatal("Invalid system dimensions");
	}
	_init_colors();

	if (params.resolve) {
		char *ret_str = resolve_mp(params.resolve, new_node_ptr);
		if (ret_str) {
			printf("%s", ret_str);
			xfree(ret_str);
		}
		_smap_exit(0);	/* Calls exit(), no return */
	}
	if (!params.commandline) {
		int check_width = min_screen_width;

		initscr();
		init_grid(new_node_ptr, COLS);
		signal(SIGWINCH, (void (*)(int))_resize_handler);

		if (params.cluster_dims == 4) {
			height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
			width = (dim_size[1] + dim_size[3] + 1) * dim_size[0]
				 + 2;
			check_width += width;
		} else if (params.cluster_dims == 3) {
			height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
			width = dim_size[0] + dim_size[2] + 3;
			check_width += width;
		} else {
			height = 10;
			width = COLS;
		}

	        if ((COLS < check_width) || (LINES < height)) {
			endwin();
			error("Screen is too small make sure the screen "
			      "is at least %dx%d\n"
			      "Right now it is %dx%d\n",
			      check_width,
			      height,
			      COLS,
			      LINES);
			_smap_exit(1);	/* Calls exit(), no return */
		}

		raw();
		keypad(stdscr, true);
		noecho();
		cbreak();
		curs_set(0);
		nodelay(stdscr, true);
		start_color();
		_set_pairs();

		grid_win = newwin(height, width, starty, startx);
		max_display = (getmaxy(grid_win) - 1) * (getmaxx(grid_win) - 1);

		if (params.cluster_dims == 4) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else if (params.cluster_dims == 3) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else {
			startx = 0;
			starty = height;
			height = LINES - height;
		}

		text_win = newwin(height, width, starty, startx);
        }
	while (!end) {
		if (!params.commandline) {
			_get_option();
redraw:
			clear_window(text_win);
			clear_window(grid_win);
			move(0, 0);

			update_grid(new_node_ptr);
			main_xcord = 1;
			main_ycord = 1;
		}

		if (!params.no_header)
			print_date();

		clear_grid();
		switch (params.display) {
		case JOBS:
			get_job();
			break;
		case RESERVATIONS:
			get_reservation();
			break;
		case SLURMPART:
			get_slurm_part();
			break;
		case COMMANDS:
#ifdef HAVE_BG
			wclear(text_win);
			get_command();
#else
			error("Must be on a real BG SYSTEM to "
			      "run this command");
			if (!params.commandline)
				endwin();
			_smap_exit(1);	/* Calls exit(), no return */
#endif
			break;
		case BGPART:
			if (params.cluster_flags & CLUSTER_FLAG_BG)
				get_bg_part();
			else {
				error("Must be on a BG SYSTEM to "
				      "run this command");
				if (!params.commandline)
					endwin();
				_smap_exit(1);	/* Calls exit(), no return */
			}
			break;
		}

		if (!params.commandline) {
			box(text_win, 0, 0);
			wnoutrefresh(text_win);

			print_grid();
			box(grid_win, 0, 0);
			wnoutrefresh(grid_win);

			doupdate();

			node_info_ptr = new_node_ptr;
			if (node_info_ptr) {
				error_code = slurm_load_node(
					node_info_ptr->last_update,
					&new_node_ptr, SHOW_ALL);
				if (error_code == SLURM_SUCCESS)
					slurm_free_node_info_msg(
						node_info_ptr);
				else if (slurm_get_errno()
					 == SLURM_NO_CHANGE_IN_DATA) {
					error_code = SLURM_SUCCESS;
					new_node_ptr = node_info_ptr;
				}
			} else {
				error_code = slurm_load_node(
					(time_t) NULL,
					&new_node_ptr, SHOW_ALL);
			}
			if (error_code && (quiet_flag != 1)) {
				if (!params.commandline) {
					mvwprintw(
						text_win,
						main_ycord,
						1,
						"slurm_load_node: %s",
						slurm_strerror(
							slurm_get_errno()));
					main_ycord++;
				} else {
					printf("slurm_load_node: %s",
					       slurm_strerror(
						       slurm_get_errno()));
				}
			}
		}

		if (params.iterate) {
			for (i = 0; i < params.iterate; i++) {
				sleep(1);
				if (!params.commandline) {
					if ((rc = _get_option()) == 1)
						goto redraw;
					else if (resize_screen) {
						resize_screen = 0;
						goto redraw;
					}
				}
			}
		} else
			break;

	}

	if (!params.commandline) {
		nodelay(stdscr, false);
		getch();
		endwin();
	}

	_smap_exit(0);	/* Calls exit(), no return */
	exit(0);	/* Redundant, but eliminates compiler warning */
}