Beispiel #1
0
int main(int argc, char *argv[])
{
    struct winsize Size;
    
    if(isatty(STDIN_FILENO)==0)
        exit(NO_FD_WITH_TERM);
    if(ioctl(STDIN_FILENO,TIOCGWINSZ,&Size)<0)
        exit(GET_WINDOW_SIZE_ERROR);
    //The size should be fixed.or it's hard to control
    ROWS=Size.ws_row+1;  //39
    COLUMNS=(Size.ws_col+1)*7/15; //70

    N=sizeof(char)*ROWS*COLUMNS;
    ScreenTable=(char*)malloc(N+4);
    memset(ScreenTable,0,N);

    OtherScreen=(char*)malloc(N+4);
    memset(OtherScreen,0,N);
    Move=(char*)malloc(N);
    memset(Move,0,N);
    
    initscr();
    move(ROWS/2,COLUMNS/2-5);
    printw("%s","Ready?Go!");
    refresh();
    sleep(1);

    clear();
    refresh();


    //create a thread to receive keyboard input
    int res;
    pthread_t keyb;
    res=pthread_create(&keyb,NULL,animation,NULL);
    if(res!=0)
    {
        perror("Thread 1 Creation failed");
        safe_exit(THREAD_CREATE_FAILED);
    }
    /*
    pthread_t anti;
    res=pthread_create(&anti,NULL,another_window,NULL);
    if(res!=0)
    {
        perror("Thread 2 Creation failed");
        safe_exit(THREAD_CREATE_FAILED);
    }
    */
    pthread_t info;
    res=pthread_create(&info,NULL,middle_window,NULL);
    if(res!=0)
    {
        perror("Thread 3 Creation failed");
        safe_exit(THREAD_CREATE_FAILED);
    }
    
    
    
    cbreak();
    noecho();
    while(1)
    {
        TYPINGCHAR=getch();
        while(TYPINGCHAR=='\n')
            break;
        isOld=0;
    }
    
    safe_exit(EXIT_SUCCESS);
}
int useradd()
{
	noecho();
	keypad(stdscr, TRUE);
	
	
	while(1) {
		DrawAddUserScreen();
	
			AddUserKey = getch();
			switch(AddUserKey)
			{
				/* Help */
				case KEY_F(1):
				break;
				
				/* Reset Fields */
				case KEY_F(2):
				sprintf(ui.username, "_");
				sprintf(ui.gecos, "_");
				sprintf(ui.user_id, "_");
				sprintf(ui.group_id, "_");
				sprintf(ui.shell, "_");
				sprintf(ui.homedir, "_");
				break;
				
				/* Username */
				case KEY_F(3):
				echo();
				attron(A_REVERSE);
				mvprintw(8,35,	"[_______________________]");
				mvwgetnstr(stdscr, 8,36, userinfobuf, 15);
				
				strcpy(ui.username, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				unamefield = 1;
				break;
				
				/* User Comment/Gecos */
				case KEY_F(4):
				echo();
				attron(A_REVERSE);
				mvprintw(9,35,	"[_______________________]");
				mvwgetnstr(stdscr, 9,36, userinfobuf, 20);
				
				strcpy(ui.gecos, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				break;
				
				/* User ID*/
				case KEY_F(5):
				echo();
				attron(A_REVERSE);
				mvprintw(10,35,	"[_______________________]");
				mvwgetnstr(stdscr, 10,36, userinfobuf, 20);
				
				strcpy(ui.user_id, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				uidfield = 1;
				break;
				
				/* Group ID*/
				case KEY_F(6):
				echo();
				attron(A_REVERSE);
				mvprintw(11,35,	"[_______________________]");
				mvwgetnstr(stdscr, 11,36, userinfobuf, 20);
				
				strcpy(ui.group_id, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				gidfield = 1;
				break;
				
				
				/* Login Shell */
				case KEY_F(7):
				echo();
				attron(A_REVERSE);
				mvprintw(12,35,	"[_______________________]");
				mvwgetnstr(stdscr, 12,36, userinfobuf, 23);
				
				strcpy(ui.shell, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				break;
				
				/* Home Dir */
				case KEY_F(8):
				echo();
				attron(A_REVERSE);
				mvprintw(13,35,	"[_______________________]");
				mvwgetnstr(stdscr, 13,36, userinfobuf, 23);
				
				strcpy(ui.homedir, userinfobuf);
				attroff(A_REVERSE);
				noecho();
				break;
				
				case KEY_F(9):
					execute_default_shell();
				break;
				
				/* Quit */
				case KEY_F(10):
				return 0;
				break;
				
				/* Commence Add */
				
				case KEY_F(11):
					add_user();
				break;
				
			};
		};
		
		
		
	
	
	return 0;
}
Beispiel #3
0
void run_timer(int seconds, std::string msg, bool quit)
{
    std::string timer;
    timer = secsToTime(seconds);
    
    (void) signal(SIGINT, finish_curses_and_quit);      /* arrange interrupts to terminate */

    (void) initscr();      /* initialize the curses library */
    keypad(stdscr, TRUE);  /* enable keyboard mapping */
    (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) noecho();       /* don't echo input */

    if (has_colors())
    {
        start_color();

        /*
         * Simple color assignment, often all we need.
         */
        init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
        init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
        init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
        init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
        init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
        init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
        init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
        init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
    }

    int row,col;                           /* to store the number of rows and *
                                            * the number of colums of the screen */
    initscr();                             /* start the curses mode */
    getmaxyx(stdscr,row,col);              /* get the number of rows and columns */
    mvprintw(row/2,(col-strlen(timer.c_str()))/2,"%s",timer.c_str());
                                            /* print the message at the center of the screen */
    mvprintw(row-1,0, msg.c_str());
    //printw("Try resizing your window(if possible) and then run this program again");
    refresh();
    
    for (;;)
    {
        //int c = getch();     /* refresh, accept single keystroke of input */

        /* process the command keystroke */
        sleep(1);
        
        if(--seconds == 0)
        {
            mvprintw(row/2,(col-strlen("TIME IS UP!"))/2,"%s","TIME IS UP!");   
            refresh();
            system("play ring.wav > /dev/null 2>&1 &");
            if(!quit)
            {
                return finish_curses(0);
            }
            else
            {
                finish_curses_and_quit(0);
            }
        }
           
        mvprintw(row/2,(col-strlen("          "))/2,"%s","          ");   

        timer = secsToTime(seconds);
        mvprintw(row/2,(col-strlen(timer.c_str()))/2,"%s",timer.c_str());   
        refresh();
    }
    
    if(!quit)
    {
        return finish_curses(0);
    }
    else
    {
        finish_curses_and_quit(0);
    }
    
}
Beispiel #4
0
int
main(int argc, const char *const argv[], const char *const envp[])
{
    ifmon_t *ifmons;
    char **ifnames;
    int nifs;
    int ret;
    int flags;
    int ch;
    double delta;
    double dtxb;
    double drxb;
    double dtxp;
    double drxp;
    int i;

    if ( 2 > argc ) {
        _usage(argv[0]);
    }
    /* Get interfaces */
    nifs = argc - 1;
    ifnames = malloc(sizeof(char *) * nifs);
    if ( NULL == ifnames ) {
        perror("malloc()");
        return EXIT_FAILURE;
    }
    ifmons = malloc(sizeof(ifmon_t) * nifs);
    if ( NULL == ifmons ) {
        perror("malloc()");
        return EXIT_FAILURE;
    }
    for ( i = 0; i < nifs; i++ ) {
        ifnames[i] = strdup(argv[i+1]);
        if ( NULL == ifnames[i] ) {
            perror("strdup()");
            return EXIT_FAILURE;
        }
        if ( NULL == ifmon_init(&ifmons[i], ifnames[i]) ) {
            /* Error */
            fprintf(stderr, "Error: ifname=%s\n", ifnames[i]);
            return EXIT_FAILURE;
        }
    }

#if WITH_CURSES
    /* curses */
    if ( NULL == initscr() ) {
        fprintf(stderr, "initscr(): Cannot initialize screen\n");
        return EXIT_FAILURE;
    }
    cbreak();
    noecho();
    scrollok(stdscr, FALSE);
    move(0, 0);
#endif

    /* Set stdin as non-blocking */
    flags = fcntl(STDIN_FILENO, F_GETFL, 0);
    if ( -1 == flags ) {
        flags = 0;
    }
    fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);

    for ( ;; ) {
#if WITH_CURSES
        ch = getch();
        if ( 'q' == ch ) {
            break;
        }
#endif

        for ( i = 0; i < nifs; i++ ) {
            ret = ifmon_update(&ifmons[i]);
            if ( 0 != ret ) {
                /* Error */
                break;
            }
        }

#if WITH_CURSES
        clear();
#endif

#if WITH_CURSES
        time_t timer;
        time(&timer);

        /*
          struct tm *tm;
          tm = localtime(&timer);
         */

        /*printw("Time: %.6f\n", );*/
        printw("Interface statistics\n%s\n", ctime(&timer));
        printw("                       pkts/s                    kbps\n");
        printw("                   TX          RX            TX          RX\n");
#endif
        for ( i = 0; i < nifs; i++ ) {
            delta = ifmons[i].curstat.time - ifmons[i].prevstat.time;
            dtxp = ifmons[i].curstat.total_pkts.tx
                - ifmons[i].prevstat.total_pkts.tx;
            drxp = ifmons[i].curstat.total_pkts.rx
                - ifmons[i].prevstat.total_pkts.rx;
            dtxb = ifmons[i].curstat.total_bytes.tx
                - ifmons[i].prevstat.total_bytes.tx;
            drxb = ifmons[i].curstat.total_bytes.rx
                - ifmons[i].prevstat.total_bytes.rx;
#if WITH_CURSES
            printw("%-8.8s: %11.02lf %11.02lf   %11.02lf %11.02lf\n",
                   ifnames[i], dtxp/delta, drxp/delta,
                   8*dtxb/delta/1000, 8*drxb/delta/1000);
#else
            printf("%-8.8s: %11.02lf %11.02lf   %11.02lf %11.02lf\n",
                   ifnames[i], dtxp/delta, drxp/delta,
                   8*dtxb/delta/1000, 8*drxb/delta/1000);
#endif
        }

#if 0
        printw("Time: %.6f (%.6f)\n",
               ifmon.curstat.time, ifmon.curstat.time - ifmon.prevstat.time);
        printw("\tTX: %15llu pkts\tRX: %15llu pkts\n",
               ifmon.curstat.total_pkts.tx - ifmon.prevstat.total_pkts.tx,
               ifmon.curstat.total_pkts.rx - ifmon.prevstat.total_pkts.rx);
        printw("\tTX: %15llu bytes\tRX: %15llu bytes\n",
               ifmon.curstat.total_bytes.tx - ifmon.prevstat.total_bytes.tx,
               ifmon.curstat.total_bytes.rx - ifmon.prevstat.total_bytes.rx);
#endif

#if WITH_CURSES
        refresh();
#endif
        sleep(1);
    }

#if WITH_CURSES
    /* End curses */
    endwin();
#endif

    return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
#ifdef ENABLE_LOGGING
  setupDebug();
#endif
 int seed = time(NULL);

//args: world seeding only.
 argc--; argv++;
 while (argc){
  if(std::string(argv[0]) == "--seed"){
   argc--; argv++;
   if(argc){
    seed = djb2_hash((unsigned char*)argv[0]);
    argc--; argv++;
   }
  }
  else // ignore unknown args.
   argc--; argv++;
 }

// ncurses stuff
 load_options(); // For getting size options
 initscr(); // Initialize ncurses
 noecho();  // Don't echo keypresses
 cbreak();  // C-style breaks (e.g. ^C to SIGINT)
 keypad(stdscr, true); // Numpad is numbers
 init_colors(); // See color.cpp
 curs_set(0); // Invisible cursor

 std::srand(seed);

 bool quit_game = false;
 bool delete_world = false;
 game *g = new game;
 MAPBUFFER.set_game(g);
 MAPBUFFER.load();

 #if (!(defined _WIN32 || defined WINDOWS))
  struct sigaction sigIntHandler;
  sigIntHandler.sa_handler = exit_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);
 #endif

 do {
  g->setup();
  while (!g->do_turn()) ;
  if (g->uquit == QUIT_DELETE_WORLD)
    delete_world = true;
  if (g->game_quit())
   quit_game = true;
 } while (!quit_game);

 if (delete_world)
 {
   g->delete_save();
 } else {
  MAPBUFFER.save_if_dirty();
 }

 exit_handler(-999);

 return 0;
}
/** Demo program using curses.
 *
 * This demo displays the text entered in a top windows that stretches
 * across the screen. The current prediction is displayed immediately
 * underneath the text window, at the leftmost position.
 *
 * The previous predictions are displayed in cronological order to the
 * right of the current prediction.
 *
 * Subsequent predictions shifted to the right, so that the current
 * prediction is always on the left hand side.
 * Context switches are marked in some way (either a vertical bar or a
 * box enclosing the other prediction boxes).
 *
 */
int main(int argc, char** argv)
{
    parseCommandLineArgs(argc, argv);

    // magic starts here
    PresageCallback* callback = new PresageDemoCallback(buffer); 
    Presage presage(callback, config);

    // configuration variable may be read and written programmatically
    if (suggestions.empty()) {
	suggestions = presage.config("Presage.Selector.SUGGESTIONS");
    } else {
	presage.config("Presage.Selector.SUGGESTIONS", suggestions);
    }

    // curses 
    initscr();
    noecho();
    cbreak();
    keypad(stdscr, TRUE);
    clear();
    refresh();

    disclaimer();

    // curses title window
    const int TITLE_WIN_HEIGHT  = 6;
    const int TITLE_WIN_WIDTH   = COLS;
    const int TITLE_WIN_BEGIN_Y = 0;
    const int TITLE_WIN_BEGIN_X = 0;
    WINDOW* title_win = newwin(TITLE_WIN_HEIGHT, TITLE_WIN_WIDTH, TITLE_WIN_BEGIN_Y, TITLE_WIN_BEGIN_X);
    draw_title_win(title_win);

    // curses context window
    const int CONTEXT_WIN_HEIGHT  = 5;
    const int CONTEXT_WIN_WIDTH   = COLS;
    const int CONTEXT_WIN_BEGIN_Y = TITLE_WIN_BEGIN_Y + TITLE_WIN_HEIGHT + 1;
    const int CONTEXT_WIN_BEGIN_X = 0;
    WINDOW* context_win = newwin(CONTEXT_WIN_HEIGHT, CONTEXT_WIN_WIDTH, CONTEXT_WIN_BEGIN_Y, CONTEXT_WIN_BEGIN_X);
    draw_context_win(context_win, std::string(""));

    // curses function keys window
    const int FUNCTION_WIN_HEIGHT  = atoi(suggestions.c_str()) + 2;
    const int FUNCTION_WIN_WIDTH   = 4;
    const int FUNCTION_WIN_BEGIN_Y = CONTEXT_WIN_BEGIN_Y + CONTEXT_WIN_HEIGHT + 1;
    const int FUNCTION_WIN_BEGIN_X = 0;
    WINDOW* function_win = newwin(FUNCTION_WIN_HEIGHT, FUNCTION_WIN_WIDTH, FUNCTION_WIN_BEGIN_Y, FUNCTION_WIN_BEGIN_X);
    draw_function_keys(function_win);

    mvprintw(LINES - 1, 0, "Press F12 to quit.");
    refresh();


    std::vector<std::string> words;
    int c = ' ';
    do {
	size_t size = words.size();
	if ((KEY_F0 < c) && (c <= KEY_F(size)) && (c - KEY_F0 <= size)) {
	    // prediction was successful. user pressed the function
	    // key corresponding to desired token. selecting
	    // suggestion.
	    std::string message = "Last selected word: " + words[c - KEY_F0 - 1];
	    mvprintw(LINES - 3, 0, message.c_str());
            clrtoeol();
	    move(LINES, COLS);

	    // update buffer with prediction completion
	    buffer << presage.completion(words[c - KEY_F0 - 1]);
	    // ask presage to predict next token
	    words = presage.predict();

	} else {
	    // prediction unsuccessful. get next character from user
	    // and elaborate a new prediction.
	    buffer << static_cast<char>(c);
	    words = presage.predict();

	    // refresh curses screen
	    refresh();
	}
	draw_context_win(context_win, presage.context());
	draw_previous_suggestions(words,
				  presage.context_change(),
                                  CONTEXT_WIN_BEGIN_Y + CONTEXT_WIN_HEIGHT + 1,
                                  FUNCTION_WIN_BEGIN_X + FUNCTION_WIN_WIDTH + 1 );
        c = getch();

    } while( c != KEY_F(12) );


    delwin(title_win);
    delwin(context_win);
    delwin(function_win);
    endwin();

    return 0;
}
int getchoice(char *greet, char *choices[]) {
    static int selected_row = 0; // static so we can re-highlight choice
    int max_row = 0;
    int start_screenrow = MESSAGE_LINE, start_screencol = 10;
    char **option;
    int selected;
    int key = 0;


    // determine the number of rows
    option = choices;
    while (*option) {
        max_row++;
        option++;
    }

    /* deal with the case where menu gets shorter after a cd is deleted */
    if (selected_row >= max_row) {
        selected_row = 0;
    }

    clear_all_screen();
    mvprintw(start_screenrow - 2, start_screencol, greet);

    // turn on keypad, cbreak, noecho
    keypad(stdscr, TRUE);
    cbreak();
    noecho();

    // loop over the menu redraw until the press 'q' or until they have
    // a choice highlighted and press enter.
    key = 0;
    while (key != 'q' && key != KEY_ENTER && key != '\n') {

        // move the selection up or down. Wrap across line 0.
        if (key == KEY_UP) {
            if (selected_row == 0) {
                selected_row = max_row - 1;
            } else {
                selected_row--;
            }
        } else if (key == KEY_DOWN) {
            if (selected_row == max_row - 1) {
                selected_row = 0;
            } else {
                selected_row++;
            }

        }

        // [] has higher precedence than *, so this is the same as
        // choices[selected_row][0].
        selected = *choices[selected_row];

        // draw the menu, then get the next key. Note initial case is handled.
        draw_menu(choices, selected_row, start_screenrow, start_screencol);
        key = getch();
    }

    // turn off keypad, cbreak, noecho
    keypad(stdscr, TRUE);
    nocbreak();
    echo();

    
    return selected;
}
Beispiel #8
0
int
main(int argc, char **argv)
{
    int FromCol, ToCol;

    setlocale(LC_ALL, "");

    switch (argc) {
    case 1:
	NTiles = DEFAULTTILES;
	break;
    case 2:
	NTiles = atoi(argv[1]);
	if (NTiles > MAXTILES || NTiles < MINTILES) {
	    fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
	    ExitProgram(EXIT_FAILURE);
	}
	break;
    case 3:
	if (strcmp(argv[2], "a")) {
	    Usage();
	    ExitProgram(EXIT_FAILURE);
	}
	NTiles = atoi(argv[1]);
	if (NTiles > MAXTILES || NTiles < MINTILES) {
	    fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
	    ExitProgram(EXIT_FAILURE);
	}
	AutoFlag = TRUE;
	break;
    default:
	Usage();
	ExitProgram(EXIT_FAILURE);
    }
    initscr();
    if (has_colors()) {
	int i;
	short bg = COLOR_BLACK;
	start_color();
#if HAVE_USE_DEFAULT_COLORS
	if (use_default_colors() == OK)
	    bg = -1;
#endif
	for (i = 0; i < 9; i++)
	    init_pair((short) (i + 1), bg, TileColour[i]);
    }
    cbreak();
    if (LINES < 24) {
	endwin();
	fprintf(stderr, "Min screen length 24 lines\n");
	ExitProgram(EXIT_FAILURE);
    }
    if (AutoFlag) {
	curs_set(0);
	leaveok(stdscr, TRUE);	/* Attempt to remove cursor */
    }
    InitTiles();
    DisplayTiles();
    if (AutoFlag) {
	do {
	    noecho();
	    AutoMove(0, 2, NTiles);
	} while (!Solved(NTiles));
	sleep(2);
    } else {
	echo();
	for (;;) {
	    if (GetMove(&FromCol, &ToCol))
		break;
	    if (InvalidMove(FromCol, ToCol)) {
		MvAddStr(STATUSLINE, 0, "Invalid Move !!");
		refresh();
		beep();
		continue;
	    }
	    MakeMove(FromCol, ToCol);
	    if (Solved(NTiles)) {
		MvPrintw(STATUSLINE, 0,
			 "Well Done !! You did it in %d moves", NMoves);
		refresh();
		sleep(5);
		break;
	    }
	}
    }
    endwin();
    ExitProgram(EXIT_SUCCESS);
}
Beispiel #9
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;

    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;
            COLS -= 2;
            width = COLS - width;
            height = LINES;
        } else if (params.cluster_dims == 3) {
            startx = width;
            COLS -= 2;
            width = COLS - width;
            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 */
}
Beispiel #10
0
int main(int argc, char **argv) {
	struct timeval t;
	int bytes_read, bytes_sent;
	int queryRegister;
	int i,n;

	int firstRegister=0;
	int lastRegister=39;


	char canInterface[128];
	strcpy(canInterface,"can0");

	while ((n = getopt (argc, argv, "hvi:")) != -1) {
		switch (n) {
			case 'h':
				fprintf(stdout,"# -p\tOutput a pretty human readable display to stderr\n");
				fprintf(stdout,"#\n");
				fprintf(stdout,"# -h\tThis help message then exit\n");
				fprintf(stdout,"#\n");
				fprintf(stdout,"# -i\tCAN interface to use (eg can0, can1, etc)\n");
				return 0;
			case 'i':
				strncpy(canInterface,optarg,sizeof(canInterface));
				canInterface[sizeof(canInterface)-1]='\0';
				fprintf(stdout,"# CAN interface = %s\n",canInterface);
				break;
			case 'v':
				outputDebug=1;
				fprintf(stdout,"# verbose (debugging) output to stderr enabled\n");
				break;
		}
	}

	if ( !outputDebug ) {
		fprintf(stdout,"# warning: no output format is selected. Nothing will show.\n");
	}

	/* setup ncurses screen */
	initscr();
	cbreak();
	noecho();
	/* non-blocking non-buffered character reads */
	nodelay(stdscr, TRUE);
	scrollok(stdscr, TRUE);
	
	/* initialize CAN frames */
	update_frame_event_update('\0');
	update_frame_operating_hours_fuel_level('\0');
	update_frame_status('\0');


	/* Create the socket */
	skt = socket( PF_CAN, SOCK_RAW, CAN_RAW );
 
	/* Locate the interface you wish to use */
	if ( outputDebug) printw("# Locating interface %s ... ",canInterface);
	struct ifreq ifr;
	strcpy(ifr.ifr_name, canInterface);
	ioctl(skt, SIOCGIFINDEX, &ifr); /* ifr.ifr_ifindex gets filled  with that device's index */
	if ( outputDebug) printw("done\n");
 
	/* Select that CAN interface, and bind the socket to it. */
	if ( outputDebug) printw("# Binding to interface ... ");
	struct sockaddr_can addr;
	addr.can_family = AF_CAN;
	addr.can_ifindex = ifr.ifr_ifindex;
	if ( 0 != bind( skt, (struct sockaddr*)&addr, sizeof(addr) ) ) {
		printw("\n# Error binding to interface. Bye.\n");
		return 1;
	}
	if ( outputDebug) printw("done\n");
 
 	for ( ; ; ) {
		int ch;

		/* 100 millisecond timer */
		t.tv_sec = 0;
		t.tv_usec = 100000; 
		select(0, NULL, NULL, NULL, &t); 

		update_frame_operating_hours_fuel_level('\0'); /* running time gets incremented everytime through */
		periodic_100ms();

		ch=getch();

		if ( '~' == ch ) {
			break;
		} else if ( ch >= 'a' && ch <= 'f' ) {
			update_frame_event_update(ch);
		} else if ( ch >= 'g' && ch <= 'j' ) {
			update_frame_operating_hours_fuel_level(ch);
		} else if ( ch >= 'k' && ch <= 'l' ) {
			update_frame_status(ch);
		}

	}
	
	/* tear down ncurses window */
	endwin();

	return 0;
}
Beispiel #11
0
Datei: main.c Projekt: bgee/twilc
int main() {
    setlocale(LC_ALL,"");

    clit_config *config = malloc(sizeof(clit_config));
    if(parse_config(config) == -1) {
        // first run
        int res = authorize(config);
        if(res == -1) {
            printf("Please retry.\n");
        }
        else
            printf("Authorization finished. Run the program again.\n");
        free(config);
        exit(0);
    }

    me = newuser();
    me->screen_name = config->screen_name;
    me->id = config->user_id;

    init_oauth(config->key,config->secret);
    free(config);

    init_mutex();
    raw_event_stream  =  new_raw_event_queue();

    printf("Loading the timelines....\n");
    if(init_timelines() == -1) {
        pthread_mutex_lock(&error_mutex);
        printf("Cannot load the timeline. Please check your network connection.\n");
        pthread_mutex_unlock(&error_mutex);
        goto exit_twilc;
    }

    initscr();
    curs_set(0);


    //if(has_colors() == FALSE)
    //goto exit_twilc;
    raw();
    keypad(stdscr,TRUE);
    noecho();
    start_color();

    move(0,0);
    refresh();

    if(init_ui() == -1)
        goto exit_twilc;

    start_userstream();
    wait_command(tl_win);


exit_twilc:

    destroy_ui();
    curs_set(1);
    endwin();

    destroy_mutex();
    for(int i = 0; i < TIMELINE_COUNT; ++i)
        destroy_timeline(timelines[i]);

    stop_userstream();
    pthread_mutex_lock(&event_buffer_mutex);
    destroy_raw_event_queue(raw_event_stream);
    raw_event_stream = NULL;
    pthread_mutex_unlock(&event_buffer_mutex);
    return 0;
}
Beispiel #12
0
/**
 * Prepare "curses" for use by the file "ui-term.c"
 *
 * Installs the "hook" functions defined above, and then activates
 * the main screen "term", which clears the screen and such things.
 *
 * Someone should really check the semantics of "initscr()"
 */
errr init_gcu(int argc, char **argv) {
	int i;
	int rows, cols, y, x;
	int next_win = 0;

	/* Initialize info about terminal capabilities */
	termtype = getenv("TERM");
	loaded_terminfo = termtype && tgetent(0, termtype) == 1;

	/* Parse args */
	for (i = 1; i < argc; i++) {
		if (prefix(argv[i], "-b")) {
			term_count = 1;
		} else if (prefix(argv[i], "-B")) {
			bold_extended = TRUE;
		} else if (prefix(argv[i], "-a")) {
			ascii_walls = TRUE;
		} else if (prefix(argv[i], "-n")) {
			term_count = atoi(&argv[i][2]);
			if (term_count > MAX_TERM_DATA) term_count = MAX_TERM_DATA;
			else if (term_count < 1) term_count = 1;
		} else {
			plog_fmt("Ignoring option: %s", argv[i]);
		}
	}

	/* Extract the normal keymap */
	keymap_norm_prepare();

	/* We do it like this to prevent a link error with curseses that
	 * lack ESCDELAY. */
	if (!getenv("ESCDELAY"))
		putenv("ESCDELAY=20");

	/* Initialize */
	if (initscr() == NULL) return (-1);

	/* Activate hooks */
	quit_aux = hook_quit;

	/* Require standard size screen */
	if (LINES < MIN_TERM0_LINES || COLS < MIN_TERM0_COLS) 
		quit("Angband needs at least an 80x24 'curses' screen");

#ifdef A_COLOR
	/* Do we have color, and enough color, available? */
	can_use_color = ((start_color() != ERR) && has_colors() &&
					 (COLORS >= 8) && (COLOR_PAIRS >= 8));

#ifdef HAVE_USE_DEFAULT_COLORS
	/* Should we use curses' "default color" */
	if (use_default_colors() == OK) bg_color = -1;
#endif

	/* Attempt to use colors */
	if (can_use_color) {
		/* Prepare the color pairs */
		/* PAIR_WHITE (pair 0) is *always* WHITE on BLACK */
		init_pair(PAIR_RED, COLOR_RED, bg_color);
		init_pair(PAIR_GREEN, COLOR_GREEN, bg_color);
		init_pair(PAIR_YELLOW, COLOR_YELLOW, bg_color);
		init_pair(PAIR_BLUE, COLOR_BLUE, bg_color);
		init_pair(PAIR_MAGENTA, COLOR_MAGENTA, bg_color);
		init_pair(PAIR_CYAN, COLOR_CYAN, bg_color);
		init_pair(PAIR_BLACK, COLOR_BLACK, bg_color);

		/* Prepare the colors */
		colortable[COLOUR_DARK]     = (COLOR_PAIR(PAIR_BLACK));
		colortable[COLOUR_WHITE]    = (COLOR_PAIR(PAIR_WHITE) | A_BRIGHT);
		colortable[COLOUR_SLATE]    = (COLOR_PAIR(PAIR_WHITE));
		colortable[COLOUR_ORANGE]   = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT);
		colortable[COLOUR_RED]      = (COLOR_PAIR(PAIR_RED));
		colortable[COLOUR_GREEN]    = (COLOR_PAIR(PAIR_GREEN));
		colortable[COLOUR_BLUE]     = (COLOR_PAIR(PAIR_BLUE));
		colortable[COLOUR_UMBER]    = (COLOR_PAIR(PAIR_YELLOW));
		colortable[COLOUR_L_DARK]   = (COLOR_PAIR(PAIR_BLACK) | A_BRIGHT);
		colortable[COLOUR_L_WHITE]  = (COLOR_PAIR(PAIR_WHITE));
		colortable[COLOUR_L_PURPLE] = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[COLOUR_YELLOW]   = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT);
		colortable[COLOUR_L_RED]    = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[COLOUR_L_GREEN]  = (COLOR_PAIR(PAIR_GREEN) | A_BRIGHT);
		colortable[COLOUR_L_BLUE]   = (COLOR_PAIR(PAIR_BLUE) | A_BRIGHT);
		colortable[COLOUR_L_UMBER]  = (COLOR_PAIR(PAIR_YELLOW));

		colortable[COLOUR_PURPLE]      = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[COLOUR_VIOLET]      = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[COLOUR_TEAL]        = (COLOR_PAIR(PAIR_CYAN));
		colortable[COLOUR_MUD]         = (COLOR_PAIR(PAIR_YELLOW));
		colortable[COLOUR_L_YELLOW]    = (COLOR_PAIR(PAIR_YELLOW | A_BRIGHT));
		colortable[COLOUR_MAGENTA]     = (COLOR_PAIR(PAIR_MAGENTA | A_BRIGHT));
		colortable[COLOUR_L_TEAL]      = (COLOR_PAIR(PAIR_CYAN) | A_BRIGHT);
		colortable[COLOUR_L_VIOLET]    = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[COLOUR_L_PINK]      = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[COLOUR_MUSTARD]     = (COLOR_PAIR(PAIR_YELLOW));
		colortable[COLOUR_BLUE_SLATE]  = (COLOR_PAIR(PAIR_BLUE));
		colortable[COLOUR_DEEP_L_BLUE] = (COLOR_PAIR(PAIR_BLUE));
	}
#endif

	/* Paranoia -- Assume no waiting */
	nodelay(stdscr, FALSE);

	/* Prepare */
	cbreak();
	noecho();
	nonl();

	/* Tell curses to rewrite escape sequences to KEY_UP and friends */
	keypad(stdscr, TRUE);

	/* Extract the game keymap */
	keymap_game_prepare();

	/* Now prepare the term(s) */
	for (i = 0; i < term_count; i++) {
		/* Get the terminal dimensions; if the user asked for a big screen
		 * then we'll put the whole screen in term 0; otherwise we'll divide
		 * it amongst the available terms */
		get_gcu_term_size(i, &rows, &cols, &y, &x);
		
		/* Skip non-existant windows */
		if (rows <= 0 || cols <= 0) continue;
		
		/* Create a term */
		term_data_init_gcu(&data[next_win], rows, cols, y, x);
		
		/* Remember the term */
		angband_term[next_win] = &data[next_win].t;
		
		/* One more window */
		next_win++;
	}

	/* Activate the "Angband" window screen */
	Term_activate(&data[0].t);

	/* Remember the active screen */
	term_screen = &data[0].t;

	/* Success */
	return (0);
}
Beispiel #13
0
int
main(int argc, char *argv[])
{
	int optc;
	int option_differences = 0,
                option_differences_cumulative = 0,
                option_exec = 0,
                option_beep = 0,
                option_color = 0,
                option_errexit = 0,
                option_help = 0,
                option_version = 0,
                option_clear = 1;
	double interval = 2;
	char *command;
	wchar_t *wcommand = NULL;
	char **command_argv;
	int command_length = 0;	/* not including final \0 */
	int wcommand_columns = 0;	/* not including final \0 */
	int wcommand_characters = 0; /* not including final \0 */
        watch_usec_t next_loop; /* next loop time in us, used for precise time
                                   keeping only */
	int pipefd[2];
	int status;
	pid_t child;

	setlocale(LC_ALL, "");
	progname = argv[0];

	while ((optc = getopt_long(argc, argv, "+bced::hn:pvtx", longopts, (int *) 0))
	       != EOF) {
		switch (optc) {
		case 'b':
			option_beep = 1;
			break;
                case 'c':
                        option_color = 1;
                        break;
		case 'd':
			option_differences = 1;
			if (optarg)
				option_differences_cumulative = 1;
			break;
                case 'e':
                        option_errexit = 1;
                        break;
		case 'h':
			option_help = 1;
			break;
		case 't':
			show_title = 0;
			break;
		case 'x':
                        option_exec = 1;
                        break;

		case 'C':
			option_clear = 0;
			break;

		case 'n':
                {
                        char *str;
                        interval = strtod(optarg, &str);
                        if (!*optarg || *str)
                                do_usage();
                        if(interval < 0.1)
                                interval = 0.1;
                        if(interval > ~0u/1000000)
                                interval = ~0u/1000000;
                }
                break;
		case 'p':
			precise_timekeeping = 1;
			break;
		case 'v':
			option_version = 1;
			break;
		default:
			do_usage();
			break;
		}
	}

	if (option_version) {
		fprintf(stderr, "%s\n", VERSION);
		if (!option_help)
			exit(0);
	}

	if (option_help) {
		fprintf(stderr, usage, progname);
		fputs("  -b, --beep\t\t\t\tbeep if the command has a non-zero exit\n", stderr);
		fputs("  -d, --differences[=cumulative]\thighlight changes between updates\n", stderr);
		fputs("\t\t(cumulative means highlighting is cumulative)\n", stderr);
		fputs("  -e, --errexit\t\t\t\texit watch if the command has a non-zero exit\n", stderr);
		fputs("  -h, --help\t\t\t\tprint a summary of the options\n", stderr);
		fputs("  -n, --interval=<seconds>\t\tseconds to wait between updates\n", stderr);
                fputs("  -p, --precise\t\t\t\tprecise timing, ignore command run time\n", stderr);
		fputs("  -v, --version\t\t\t\tprint the version number\n", stderr);
		fputs("  -t, --no-title\t\t\tturns off showing the header\n", stderr);
		fputs("  -x, --exec\t\t\t\tpass command to exec instead of sh\n", stderr);
		fputs("  -C, --no-clear\t\t\tturns off clearing the screen each time\n", stderr);
		exit(0);
	}

	if (optind >= argc)
		do_usage();

	command_argv=&(argv[optind]); /* save for later */

	command = strdup(argv[optind++]);
	command_length = strlen(command);
	for (; optind < argc; optind++) {
		char *endp;
		int s = strlen(argv[optind]);
		command = realloc(command, command_length + s + 2);	/* space and \0 */
		endp = command + command_length;
		*endp = ' ';
		memcpy(endp + 1, argv[optind], s);
		command_length += 1 + s;	/* space then string length */
		command[command_length] = '\0';
	}

	// convert to wide for printing purposes
	//mbstowcs(NULL, NULL, 0);
	wcommand_characters = mbstowcs(NULL, command, 0);
	if(wcommand_characters < 0) {
		fprintf(stderr, "Unicode Handling Error\n");
		exit(1);
	}
	wcommand = (wchar_t*)malloc((wcommand_characters+1) * sizeof(wcommand));
	if(wcommand == NULL) {
		fprintf(stderr, "Unicode Handling Error (malloc)\n");
		exit(1);
	}
	mbstowcs(wcommand, command, wcommand_characters+1);
	wcommand_columns = wcswidth(wcommand, -1);



	get_terminal_size();

	/* Catch keyboard interrupts so we can put tty back in a sane state.  */
	signal(SIGINT, die);
	signal(SIGTERM, die);
	signal(SIGHUP, die);
	signal(SIGWINCH, winch_handler);

	/* Set up tty for curses use.  */
	curses_started = 1;
	initscr();
        if (option_color) {
                if (has_colors()) {
                        start_color();
                        use_default_colors();
                        init_ansi_colors();
                } else
                        option_color = 0;
        }
	nonl();
	noecho();
	cbreak();

	if (precise_timekeeping)
		next_loop = get_time_usec();

	for (;;) {
		time_t t = time(NULL);
		char *ts = ctime(&t);
		int tsl = strlen(ts);
		char *header;
		FILE *p;
		int x, y;
		int oldeolseen = 1;

		if (screen_size_changed) {
			get_terminal_size();
			resizeterm(height, width);
			clear();
			/* redrawwin(stdscr); */
			screen_size_changed = 0;
			first_screen = 1;
		}

		if (show_title) {
			// left justify interval and command,
			// right justify time, clipping all to fit window width

			int hlen = asprintf(&header, "Every %.1fs: ", interval);

			// the rules:
			//   width < tsl : print nothing
			//   width < tsl + hlen + 1: print ts
			//   width = tsl + hlen + 1: print header, ts
			//   width < tsl + hlen + 4: print header, ..., ts
			//   width < tsl + hlen + wcommand_columns: print header, truncated wcommand, ..., ts
			//   width > "": print header, wcomand, ts
			// this is slightly different from how it used to be
			if(width >= tsl) {
				if(width >= tsl + hlen + 1) {
					mvaddstr(0, 0, header);
					if(width >= tsl + hlen + 2) {
						if(width < tsl + hlen + 4) {
							mvaddstr(0, width - tsl - 4, "...  ");
						}else{
							if(width < tsl + hlen + wcommand_columns) {
								// print truncated
								int avail_columns = width - tsl - hlen;
								int using_columns = wcommand_columns;
								int using_characters = wcommand_characters;
								while(using_columns > avail_columns - 4) {
									using_characters--;
                                                                        using_columns = wcswidth(wcommand, using_characters);
								}
								mvaddnwstr(0, hlen, wcommand, using_characters);
								mvaddstr(0, width - tsl - 4, "... ");
							}else{
								mvaddwstr(0, hlen, wcommand);
							}
						}
					}
				}
				mvaddstr(0, width - tsl + 1, ts);
			}

			free(header);
		}

		/* allocate pipes */
		if (pipe(pipefd)<0) {
                        perror("pipe");
			do_exit(7);
                }

		/* flush stdout and stderr, since we're about to do fd stuff */
		fflush(stdout);
		fflush(stderr);

		/* fork to prepare to run command */
		child=fork();

		if (child<0) { /* fork error */
                        perror("fork");
			do_exit(2);
                } else if (child==0) { /* in child */
                        close (pipefd[0]); /* child doesn't need read side of pipe */
                        close (1); /* prepare to replace stdout with pipe */
                        if (dup2 (pipefd[1], 1)<0) { /* replace stdout with write side of pipe */
                                perror("dup2");
                                exit(3);
                        }
                        dup2(1, 2); /* stderr should default to stdout */

                        if (option_exec) { /* pass command to exec instead of system */
                                if (execvp(command_argv[0], command_argv)==-1) {
                                        perror("exec");
                                        exit(4);
                                }
                        } else {
                                status=system(command); /* watch manpage promises sh quoting */

                                /* propagate command exit status as child exit status */
                                if (!WIFEXITED(status)) { /* child exits nonzero if command does */
                                        exit(1);
                                } else {
                                        exit(WEXITSTATUS(status));
                                }
                        }

                }

                /* otherwise, we're in parent */
                close(pipefd[1]); /* close write side of pipe */
                if ((p=fdopen(pipefd[0], "r"))==NULL) {
                        perror("fdopen");
                        do_exit(5);
                }


                for (y = show_title; y < height; y++) {
                        int eolseen = 0, tabpending = 0;
                        wint_t carry = WEOF;
                        for (x = 0; x < width; x++) {
                                wint_t c = L' ';
                                int attr = 0;

                                if (!eolseen) {
                                        /* if there is a tab pending, just spit spaces until the
                                           next stop instead of reading characters */
                                        if (!tabpending)
                                                do {
                                                        if(carry == WEOF) {
                                                                c = my_getwc(p);
                                                        }else{
                                                                c = carry;
                                                                carry = WEOF;
                                                        }
                                                }while (c != WEOF && !isprint(c) && c<128
                                                        && wcwidth(c) == 0
                                                        && c != L'\n'
                                                        && c != L'\t'
                                                        && (c != L'\033' || option_color != 1));
                                        if (c == L'\033' && option_color == 1) {
                                                x--;
                                                process_ansi(p);
                                                continue;
                                        }
                                        if (c == L'\n')
                                                if (!oldeolseen && x == 0) {
                                                        x = -1;
                                                        continue;
                                                } else
                                                        eolseen = 1;
                                        else if (c == L'\t')
                                                tabpending = 1;
                                        if (x==width-1 && wcwidth(c)==2) {
                                                y++;
                                                x = -1; //process this double-width
                                                carry = c; //character on the next line
                                                continue; //because it won't fit here
                                        }
                                        if (c == WEOF || c == L'\n' || c == L'\t')
                                                c = L' ';
                                        if (tabpending && (((x + 1) % 8) == 0))
                                                tabpending = 0;
                                }
                                move(y, x);
                                if (option_differences) {
                                        cchar_t oldc;
                                        in_wch(&oldc);
                                        attr = !first_screen
                                                && ((wchar_t)c != oldc.chars[0]
                                                    ||
                                                    (option_differences_cumulative
                                                     && (oldc.attr & A_ATTRIBUTES)));
                                }
                                if (attr)
                                        standout();
                                addnwstr((wchar_t*)&c,1);
                                if (attr)
                                        standend();
                                if(wcwidth(c) == 0) { x--; }
                                if(wcwidth(c) == 2) { x++; }
                        }
                        oldeolseen = eolseen;
                }

                fclose(p);

                /* harvest child process and get status, propagated from command */
                if (waitpid(child, &status, 0)<0) {
                        perror("waitpid");
                        do_exit(8);
                };

                /* if child process exited in error, beep if option_beep is set */
                if ((!WIFEXITED(status) || WEXITSTATUS(status))) {
                        if (option_beep) beep();
                        if (option_errexit) do_exit(8);
                }

                first_screen = 0;
                refresh();
                if (precise_timekeeping) {
                        watch_usec_t cur_time = get_time_usec();
                        next_loop += USECS_PER_SEC*interval;
                        if (cur_time < next_loop)
                                usleep(next_loop - cur_time);
                } else
                        usleep(interval * 1000000);
        }

        endwin();

        return 0;
}
Beispiel #14
0
int main(int argc, char *argv[]) {
	if( argc == 2 ) {
		//printf("The argument supplied is %s\n", argv[1]);
		fileToOpen = new char[strlen(argv[1])+1];
		strcpy(fileToOpen, argv[1]);
		fileNameSupplied = true;
	}
	
	//Initiate the NCurses System
	initscr();
	keypad(stdscr, TRUE);
	curs_set(1);
	noecho();
	
	//Set the Screen Parameters
	getmaxyx(stdscr, WINHEIGHT, WINWIDTH);
	
	//App Name boiler plate!
	mvprintw(0, 0, "%s", applicationName);
	
	//Top Bar below menu
	attron(A_REVERSE);
	for (int i = 0; i < WINWIDTH; i++) {
		mvaddch(1, i, ' ');
	}
	//Bottom Status Bar
	for (int i = 0; i < WINWIDTH; i++) {
		mvaddch(WINHEIGHT-1, i, ' ');
	}
	
	mvprintw(WINHEIGHT-1, 1, "^X:QUIT");
	mvprintw(WINHEIGHT-1, 10, "^S:SAVE");
	mvprintw(WINHEIGHT-1, 20, "F1:HELP");
	mvprintw(WINHEIGHT-1, WINWIDTH-4, "INS");
	attroff(A_REVERSE);
	refresh();
	
	//displayHelp();
	
	WINDOW* textWin = newwin(WINHEIGHT-3, WINWIDTH, 2, 0);
	wrefresh(textWin);
	
	twin* tEditorWin;
	if (fileNameSupplied == true) {	//name was supplied
		if (fileExists(fileToOpen)) {	//file exists, so open it
			tEditorWin = new twin(textWin, fileToOpen, WINHEIGHT-3, WINWIDTH);
		} else {	//doesn't exist, so create and open
			if (createFile(fileToOpen) == true) {
				tEditorWin = new twin(textWin, fileToOpen, WINHEIGHT-3, WINWIDTH);
			} else {
				printf("Error creating file. Please check access.\n");
				exit(1);
			}
		}
	} else {
		fileToOpen = new char[strlen((char*)"unnamed.txt")+1];
		strcpy(fileToOpen, (char*)"unnamed.txt");
		fileNameSupplied = true;
		if (createFile(fileToOpen) == true) {
			tEditorWin = new twin(textWin, fileToOpen, WINHEIGHT-3, WINWIDTH);
		} else {
			printf("Error creating file. Please check access.\n");
			exit(1);
		}
	}
	tEditorWin->process();
	
	//getch();
	delete tEditorWin;
	endwin();
	return 0;
}
Beispiel #15
0
/*  
init_nhwindows(int* argcp, char** argv)
                -- Initialize the windows used by NetHack.  This can also
                   create the standard windows listed at the top, but does
                   not display them.
                -- Any commandline arguments relevant to the windowport
                   should be interpreted, and *argcp and *argv should
                   be changed to remove those arguments.
                -- When the message window is created, the variable
                   iflags.window_inited needs to be set to TRUE.  Otherwise
                   all plines() will be done via raw_print().
                ** Why not have init_nhwindows() create all of the "standard"
                ** windows?  Or at least all but WIN_INFO?      -dean
*/
void curses_init_nhwindows(int* argcp, char** argv)
{
#ifdef PDCURSES
    char window_title[BUFSZ];
#endif

#ifdef XCURSES
    base_term = Xinitscr(*argcp, argv);
#else
    base_term = initscr();
#endif
#ifdef TEXTCOLOR
    if (has_colors())
    {
        start_color();
        curses_init_nhcolors();
    }
    else
    {
        iflags.use_color = FALSE;
        set_option_mod_status("color", SET_IN_FILE);
        iflags.wc2_guicolor = FALSE;
        set_wc2_option_mod_status(WC2_GUICOLOR, SET_IN_FILE);    
    }
#else
    iflags.use_color = FALSE;
    set_option_mod_status("color", SET_IN_FILE);    
    iflags.wc2_guicolor = FALSE;
    set_wc2_option_mod_status(WC2_GUICOLOR, SET_IN_FILE);    
#endif
    noecho();
    raw();
    meta(stdscr, TRUE);
    orig_cursor = curs_set(0);
    keypad(stdscr, TRUE);
#ifdef NCURSES_VERSION
# ifdef __APPLE__
 ESCDELAY = 25;
# else
    set_escdelay(25);
# endif /* __APPLE__ */
#endif  /* NCURSES_VERSION */
#ifdef PDCURSES
# ifdef DEF_GAME_NAME
#  ifdef VERSION_STRING
    sprintf(window_title, "%s %s", DEF_GAME_NAME, VERSION_STRING);
#  else
    sprintf(window_title, "%s", DEF_GAME_NAME);
#  endif /* VERSION_STRING */
# else
#  ifdef VERSION_STRING
    sprintf(window_title, "%s %s", "NetHack", VERSION_STRING);
#  else
    sprintf(window_title, "%s", "NetHack");
#  endif /* VERSION_STRING */
# endif /* DEF_GAME_NAME */
    PDC_set_title(window_title);
    PDC_set_blink(TRUE);    /* Only if the user asks for it! */
    timeout(1);
    (void)getch();
    timeout(-1);
#endif  /* PDCURSES */
    getmaxyx(base_term, term_rows, term_cols);
    counting = FALSE;
    curses_init_options();
    if ((term_rows < 15) || (term_cols < 40))
    {
        panic("Terminal too small.  Must be minumum 40 width and 15 height");
    }

    curses_create_main_windows();
    curses_init_mesg_history();
    curses_display_splash_window();
}
Beispiel #16
0
int checklogfile_new(char *filename)
{
    int lineno;
    int tooshort;
    char buffer[160];
    FILE *fp;

    /* check if logfile exist and can be opened for read */
    if ((fp = fopen(filename, "r")) == NULL) {

	if (errno == EACCES) {
	    showstring( "Can not access log file: ", filename);
	    return 1;
	}

	if (errno == ENOENT) {
	    /* File not found, create new one */
	    showmsg( "Log file not found, creating new one");
	    sleep(2);
	    if ((fp = fopen(filename, "w")) == NULL) {
		/* cannot create logfile */
		showmsg( "Creating logfile not possible");
	        return 1;
	    }
	    /* New logfile created */
	    fclose(fp);
	    return 0;
	}
    }


    /* check each line of the logfile of correct format */
    lineno = 0;
    tooshort = 0;

    while (fgets(buffer, sizeof(buffer), fp)) {
	int band, linelen;
	int bandok = 0; 

	lineno++;

	/* if no logline -> complain and back */
	band = atoi(buffer);

	if ((band == 160) ||
	    (band == 80) ||
	    (band == 40) ||
	    (band == 30) ||
	    (band == 20) ||
	    (band == 17) ||
	    (band == 15) ||
	    (band == 12) ||
	    (band == 10))
		bandok = 1;

	if (!((buffer[0] == ';') || bandok)) {
	    /* msg no valid logline in line #, cannot handle it */
	    shownr( "No valid log line in line ", lineno);
	    return 1;
	}

	linelen = strlen(buffer);

	/* if to long -> complain and back */
	if (linelen > LOGLINELEN) {
	    /* msg length of line # to long,
	     * cannot handle that log file format */
	    shownr( "Log line to long in line ", lineno);
	    showmsg( "Can not handle that log format");
	    return 1;
	}

	/* if to short -> remember */
	if (linelen < LOGLINELEN) {
	    tooshort = 1;
	}
    }

    fclose(fp);

    if (tooshort) {
	char c;

	/* some lines in logfile are too short, maybe old logfile format */
	showmsg( "Some log lines are too short (maybe an old log format)!" );
	showmsg( "Shall I try to repair? Y/(N) " );
	echo();
	c =toupper( getch() );
	noecho();

	if (c != 'Y') {
	    return 1;			/* giving up */
	}

	/* trying to repair */
	return repair_log(filename);
    }

    return 0;
}
int window_online_print()
{
  int y,x;
  char buf[250];
  curseson(); cbreak(); noecho(); nonl(); keypad(stdscr,TRUE);

  getmaxyx(stdscr,y,x);
  attrset(A_NORMAL);
  attrset(COLOR_PAIR(14));

  snprintf(buf, x,
	   "whoIam   :   %s %140.140s", cfg.identity, " ");
  mvaddnstr(y+gui_window_online.y0,
	    0,
	    buf,
	    x-1);

  if (josua_online_status==EXOSIP_NOTIFY_UNKNOWN)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "unknown", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_PENDING)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "pending", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_ONLINE)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Online", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_BUSY)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Busy", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_BERIGHTBACK)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Be Right Back", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_AWAY)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Away", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_ONTHEPHONE)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "On The Phone", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_OUTTOLUNCH)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Out To Lunch", " ");
  else if (josua_online_status==EXOSIP_NOTIFY_CLOSED)
    snprintf(buf, x,
	     "IM status:   %s %140.140s", "Closed", " ");
  else
    snprintf(buf, x,
	     "IM status:   ?? %140.140s" , " ");
  mvaddnstr(y+gui_window_online.y0+1,
	    0,
	    buf,
	    x-1);

  if (josua_registration_status==-1)
    {
      snprintf(buf, x,
	       "registred:   --Not registred-- %140.140s", " ");
      mvaddnstr(y+gui_window_online.y0+2,
		0,
		buf,
		x-1);
    }
  else if (199<josua_registration_status && josua_registration_status<300)
    {
      snprintf(buf, x,
	       "registred:   [%i %s] %s %140.140s",
	       josua_registration_status,
	       josua_registration_reason_phrase,
	       josua_registration_server, " ");
      mvaddnstr(y+gui_window_online.y0+2,
		0,
		buf,
		x-1);
    }
  else if (josua_registration_status>299)
    {
      snprintf(buf, x,
	       "registred:   [%i %s] %s %140.140s",
	       josua_registration_status,
	       josua_registration_reason_phrase,
	       josua_registration_server, " ");
      mvaddnstr(y+gui_window_online.y0+2,
		0,
		buf,
		x-1);
    }
  else if (josua_registration_status==0)
    {
      snprintf(buf, x,
	       "registred:   [no answer] %s %140.140s",
	       josua_registration_server, " ");
      mvaddnstr(y+gui_window_online.y0+2,
		0,
		buf,
		x-1);
    }

  return 0;
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    WINDOW *win;
    int key, old_option = -1, new_option = 0, i;
    bool quit = FALSE;

    setlocale(LC_ALL, "");

    if (initTest(&win, argc, argv))
        return 1;

    for( i = 1; i < argc; i++)
        if( argv[i][0] == '-')
            switch( argv[i][1])
            {
                case 'b': case 'B':
                    PDC_set_blink( TRUE);
                    break;
                case 'l': case 'L':
                    setlocale( LC_ALL, argv[i] + 2);
                    break;
                case 'i': case 'I':
                    background_index = (short)atoi( argv[i] + 2);
                    break;
                case 'm': case 'M':
                    PDC_return_key_modifiers( TRUE);
                    break;
                default:
                    break;
            }

#ifdef A_COLOR
    if (has_colors())
    {
        init_pair(1, COLOR_WHITE, COLOR_BLUE);
        wbkgd(win, COLOR_PAIR(1));
    }
    else
#endif
        wbkgd(win, A_REVERSE);

    erase();
    display_menu(old_option, new_option);

    while (1)
    {
        noecho();
        keypad(stdscr, TRUE);
        raw();

        key = getch();

        switch(key)
        {
        case 10:
        case 13:
        case KEY_ENTER:
            old_option = -1;
            erase();
            refresh();
            (*command[new_option].function)(win);
            erase();
            display_menu(old_option, new_option);
            break;

        case KEY_PPAGE:
        case KEY_HOME:
            old_option = new_option;
            new_option = 0;
            display_menu(old_option, new_option);
            break;

        case KEY_NPAGE:
        case KEY_END:
            old_option = new_option;
            new_option = MAX_OPTIONS - 1;
            display_menu(old_option, new_option);
            break;

        case KEY_UP:
            old_option = new_option;
            new_option = (new_option == 0) ?
                new_option : new_option - 1;
            display_menu(old_option, new_option);
            break;

        case KEY_DOWN:
            old_option = new_option;
            new_option = (new_option == MAX_OPTIONS - 1) ?
                new_option : new_option + 1;
            display_menu(old_option, new_option);
            break;
        case KEY_RESIZE:
# ifdef PDCURSES
            resize_term(0, 0);
# endif
            old_option = -1;
            erase();
            display_menu(old_option, new_option);
            break;
        case 'Q':
        case 'q':
            quit = TRUE;
        }

        if (quit == TRUE)
            break;
    }

    delwin(win);
    endwin();

    return 0;
}
Beispiel #19
0
// Run the user's paddle
void *moveme(void* vp) {
	int ch;

	// get the extents of the screen
	int maxx;
	int maxy;
	getmaxyx(win, maxy, maxx);
	int vpos = maxy / 2;

	// draw the default paddle
	drawPaddle(vpos);

	while (!quit) {
		(void) noecho();
		ch = getch();
		switch (ch) {

		case KEY_UP: // The user has pressed the up arrow.  Move the paddle one pixel upwards if possible.
			if (!pauseGame) {
				undrawPaddle(vpos);
				vpos--;
				if (vpos < 0 + PADDLE_SIZE / 2) {
					vpos = PADDLE_SIZE / 2;
				}
				drawPaddle(vpos);
			}
			break;

		case KEY_DOWN: // The user has pressed the down arrow.  Move the paddle one pixel downward if possible.
			if (!pauseGame) {
				undrawPaddle(vpos);
				vpos++;
				if (vpos > (maxy - (PADDLE_SIZE / 2))) {
					vpos = (maxy - (PADDLE_SIZE / 2));
				}
				drawPaddle(vpos);
			}
			break;

		case 'q': // The user has pressed the quiz button.  Exit the game.
			quit = true;
			break;
		case 'p':
			pauseGame = !pauseGame;
			break;
		case '+': // The user pressed the plus key to increase the speed of ball
			pthread_mutex_lock(&mutex);
			int temp = ballMovementDelay / 2;
			if(temp > 0)
				ballMovementDelay = temp;
			pthread_mutex_unlock(&mutex);
			break;
		case '-': // The user pressed the minus key to decrease the speed of ball
			pthread_mutex_lock(&mutex);
			ballMovementDelay *= 2;
			pthread_mutex_unlock(&mutex);
			break;
		default:
			break;
		}
	}
	return NULL;
}
Beispiel #20
0
void inputTest(WINDOW *win)
{
    int w, h, bx, by, sw, sh, i, c, num = 0;
    int line_to_use = 3;
    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 | REPORT_MOUSE_POSITION);
    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, line_to_use, 3, spinner[spinner_count]);
                wrefresh(win);
            }
            else
                break;
        }
#ifdef PDCURSES
//      wmove(win, line_to_use + 1, 18);
//      wclrtoeol(win);
#endif
        mvwaddstr(win, line_to_use, 5, "Key Pressed: ");
        wclrtoeol(win);

        wprintw( win, "(%x) ", c);
        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, status = 0;
            request_mouse_pos();

            if (BUTTON_CHANGED(1))
                button = 1;
            else if (BUTTON_CHANGED(2))
                button = 2;
            else if (BUTTON_CHANGED(3))
                button = 3;
            else if (BUTTON_CHANGED(4))   /* added 21 Jan 2011: BJG */
                button = 4;
            else if (BUTTON_CHANGED(5))
                button = 5;
            if( button)
                status = (button > 3 ? Mouse_status.xbutton[(button) - 4] :
                                       Mouse_status.button[(button) - 1]);

            wmove(win, line_to_use, 5);
            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 ((status & BUTTON_ACTION_MASK) == BUTTON_PRESSED)
                waddstr(win, "pressed: ");
            else if ((status & BUTTON_ACTION_MASK) == BUTTON_CLICKED)
                waddstr(win, "clicked: ");
            else if ((status & BUTTON_ACTION_MASK) == BUTTON_DOUBLE_CLICKED)
                waddstr(win, "double: ");
            else if ((status & BUTTON_ACTION_MASK) == BUTTON_TRIPLE_CLICKED)
                waddstr(win, "triple: ");
            else
                waddstr(win, "released: ");

            wprintw(win, "Posn: Y: %d X: %d", MOUSE_Y_POS, MOUSE_X_POS);
            if (button && (status & BUTTON_MODIFIER_MASK))
            {
                if (status & BUTTON_SHIFT)
                    waddstr(win, " SHIFT");

                if (status & BUTTON_CONTROL)
                    waddstr(win, " CONTROL");

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

        }
        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;
        line_to_use++;
        if( line_to_use == 10)
           line_to_use = 3;
    }

    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);
}
/* This function can only be called if a cd has already been selected and
 * stored in the globals `current_cd` and `current_cat`. */
void list_tracks() {
    FILE *tracks_fp;
    char entry[MAX_ENTRY];
    int cat_length;
    int lines_op = 0;
    WINDOW *track_pad;
    int ntracks = 0;
    int key;
    int first_line = 0;

    // handle the case of no current cd
    if (current_cd[0] == '\0') {
        mvprintw(ERROR_LINE, 0, "You must select a CD before listing tracks");
        get_return();
        return;
    }

    clear_all_screen();

    // First, count the number of tracks for the current CD. close the
    // file when done so we can reopen before listing them.
    cat_length = strlen(current_cat);
    tracks_fp = fopen(TRACKS_FILE, "r");
    if (!tracks_fp) return;
    while (fgets(entry, MAX_ENTRY, tracks_fp)) {
        if (strncmp(current_cat, entry, cat_length) == 0) {
            ntracks++;
        }
    }
    fclose(tracks_fp);

    // make a new pad. Make sure it is big enough to fill up the boxed region
    // even if there are no listings.
    //   NOTE: we don't actually make a box for this operation... the box is
    //   only used in update_cd. But we are reusing the same region.
    track_pad = newpad(ntracks + 1 + BOXED_LINES, BOXED_COLS + 1);
    if (!track_pad) return;

    // reopen the tracks file
    tracks_fp = fopen(TRACKS_FILE, "r");
    if (!tracks_fp) return;

    // print out all the tracks onto the pad.
    mvprintw(4, 0, "CD Track Listing\n");
    while (fgets(entry, MAX_ENTRY, tracks_fp)) {
        if (strncmp(current_cat, entry, cat_length) == 0) {
            // print the track info. Use `cat_length+1` bc of the comma
            //    this actually is kind of strange because we are still
            //    printing a kind of ugly comma-separated track number and
            //    name, but it works. You could make it better as an exercise.
            mvwprintw(track_pad, lines_op++, 0, "%s", entry + cat_length + 1);
        }
    }
    fclose(tracks_fp);

    // tell the user what to do
    if (lines_op > BOXED_LINES) {
        mvprintw(MESSAGE_LINE, 0, "Arrows to scroll, RETURN or q to exit.");
    } else {
        mvprintw(MESSAGE_LINE, 0, "RETURN or q to exit.");
    }

    // set up the control keys and such, refresh the main screen
    wrefresh(stdscr);
    keypad(stdscr, TRUE);
    cbreak();
    noecho();

    // start up a loop over control keys; inside the loop refresh the pad
    key = 0;
    while (key != '\n' && key != KEY_ENTER && key != 'q') {
        if (key == KEY_UP) {
            if (first_line > 0) {
                first_line--;
            }
        } else if (key == KEY_DOWN) {
            if (first_line + BOXED_LINES < ntracks - 1) {
                first_line++;
            }
        }

        prefresh(track_pad, first_line, 0,
                 BOX_LINE_POS, BOX_COL_POS,
                 BOX_LINE_POS + BOXED_LINES, BOX_COL_POS + BOXED_COLS);
        key = getch();
    }
}
Beispiel #22
0
int main(void)
{
  int ch;
  WINDOW *reg_win;
  const char *runhalt[]={"Running","Halted ","Trap   "};

  preload();
  rim();

  df32_init();

  // get ncurses going
  initscr();
  raw();			// turn off line buffering
  noecho();
  keypad(stdscr,TRUE);		// lets us use function keys etc
  scrollok(stdscr,TRUE);
  reg_win=newwin(1,79,23,0);	// define a register window

  nodelay(stdscr, TRUE);	// nonblocking tty IO

  // set up the registers and stuff
  l=0;ac=0;			// AC and Link
  pc=07000;			// PC is set for ODT HIGH
  sr=0;				// SR is clear
  ifr=0; ifrb=0; dfr=0;		// Extended memory registers

  tty_pun_f=1;			// TTY flags preset
  tty_rdr_f=0;
  tty_pun_clk=0;
  cycles=0;			// cycle count
  halt=0;

  // initial display code goes here
  mvwprintw(reg_win,0,0,"PC: %05o L: %o AC: %04o MB: %04o %s", (010000*ifr)+pc,l,ac,core[(010000*ifr)+pc],runhalt[halt]);
  wrefresh(reg_win);

  // main loop begins
  while(ch!=KEY_F(12)) { 	// if the key pressed was F11, we'll leave
    ch = getch();		// get a keystroke
    if (ch!=ERR) {		// there actually *is* a keystroke
      switch (ch) {
        case KEY_F(2):		// F2 is single-step
	  functionmesh(core[pc+(010000*ifr)]);	// do the instruction
  	  break;
        case KEY_F(3):		// F3 is halt/run
	  halt=!halt;		// pretty simple really
	  break;
	case KEY_F(4):		// interrupt (sssh, nasty cheat)
	  core[00000]=pc+1;
	  pc=00001;
	  break;
	case KEY_F(9):
	  pc=07000;
	  halt=0;
	  break;
	default:
          tty_rdr_buf=ch;		// keep that ready for later, in the reader buffer
          tty_rdr_f=1;		// raise the flag, there's a character ready
      }
      // Eeeew.  This bit is horrible.  It prints the registers when we single-step
      // it's actually done every time we press a key.  Ick.  I hate this bit
      // in fact, let's have a *** FIXME *** right here
      mvwprintw(reg_win,0,0,"PC: %05o L: %o AC: %04o MB: %04o %s", (010000*ifr)+pc,l,ac,core[(010000*ifr)+pc],runhalt[halt]);
      wrefresh(reg_win);
    }

    cycles++;			// increase the cycle counter

    if(!halt) {			// CPU is running, let's do the instruction
      functionmesh(core[pc+(01000*ifr)]);
    }				// we can always add more here later

    tty_run();			// handle the TTY
    df32_run();
    // more peripheral handlers will go here
  }

  endwin();			// leave ncurses mode
  return (0);
}
Beispiel #23
0
int os_inner_init(const char* title)
{
	const char* display;
	struct utsname uts;
	struct sigaction term_action;
	struct sigaction quit_action;
	struct sigaction hup_action;
	struct sigaction pipe_action;
#ifdef USE_SDL
	SDL_version compiled;
#endif
	unsigned char endian[4] = { 0x1, 0x2, 0x3, 0x4 };
	uint32 endian_little = 0x04030201;
	uint32 endian_big = 0x01020304;

	log_std(("os: os_inner_init\n"));

	if (uname(&uts) != 0) {
		log_std(("ERROR:os: uname failed\n"));
	} else {
		log_std(("os: sys %s\n", uts.sysname));
		log_std(("os: release %s\n", uts.release));
		log_std(("os: version %s\n", uts.version));
		log_std(("os: machine %s\n", uts.machine));
	}

#if HAVE_SYSCONF
#ifdef _SC_CLK_TCK
	log_std(("os: sysconf(_SC_CLK_TCK) %ld\n", sysconf(_SC_CLK_TCK)));
#endif
#ifdef _SC_NPROCESSORS_CONF
	log_std(("os: sysconf(_SC_NPROCESSORS_CONF) %ld\n", sysconf(_SC_NPROCESSORS_CONF)));
#endif
#ifdef _SC_NPROCESSORS_ONLN
	log_std(("os: sysconf(_SC_NPROCESSORS_ONLN) %ld\n", sysconf(_SC_NPROCESSORS_ONLN)));
#endif
#ifdef _SC_PHYS_PAGES
	log_std(("os: sysconf(_SC_PHYS_PAGES) %ld\n", sysconf(_SC_PHYS_PAGES)));
#endif
#ifdef _SC_AVPHYS_PAGES
	log_std(("os: sysconf(_SC_AVPHYS_PAGES) %ld\n", sysconf(_SC_AVPHYS_PAGES)));
#endif
#ifdef _SC_CHAR_BIT
	log_std(("os: sysconf(_SC_CHAR_BIT) %ld\n", sysconf(_SC_CHAR_BIT)));
#endif
#ifdef _SC_LONG_BIT
	log_std(("os: sysconf(_SC_LONG_BIT) %ld\n", sysconf(_SC_LONG_BIT)));
#endif
#ifdef _SC_WORD_BIT
	log_std(("os: sysconf(_SC_WORD_BIT) %ld\n", sysconf(_SC_WORD_BIT)));
#endif
#endif

#ifdef _POSIX_PRIORITY_SCHEDULING /* OSDEF Check for POSIX scheduling */
	log_std(("os: scheduling available\n"));
#else
	log_std(("os: scheduling NOT available\n"));
#endif

	/* print the compiler version */
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) /* OSDEF Detect compiler version */
#define COMPILER_RESOLVE(a) #a
#define COMPILER(a, b, c) COMPILER_RESOLVE(a) "." COMPILER_RESOLVE(b) "." COMPILER_RESOLVE(c)
	log_std(("os: compiler GNU %s\n", COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)));
#else
	log_std(("os: compiler unknown\n"));
#endif

	/* check for int size */
	if (sizeof(uint8) != 1) {
		target_err("The program is compiled with invalid uint8 type.\n");
		return -1;
	}
	if (sizeof(uint16) != 2) {
		target_err("The program is compiled with invalid uint16 type.\n");
		return -1;
	}
	if (sizeof(uint32) != 4) {
		target_err("The program is compiled with invalid uint32 type.\n");
		return -1;
	}
	if (sizeof(uint64) != 8) {
		target_err("The program is compiled with invalid uint64 type.\n");
		return -1;
	}

	/* check for the endianess */
#ifdef USE_MSB
	log_std(("os: compiled big endian system\n"));
	if (memcmp(endian, &endian_big, 4) != 0) {
		target_err("The program is compiled as bigendian but system doesn't appear to be bigendian.\n");
		return -1;
	}
#endif
#ifdef USE_LSB
	log_std(("os: compiled little endian system\n"));
	if (memcmp(endian, &endian_little, 4) != 0) {
		target_err("The program is compiled as littleendian but system doesn't appear to be littleendian.\n");
		return -1;
	}
#endif

#ifdef USE_SMP
	/* check the thread support */
	if (os_thread() != 0) {
		target_err("Error on the threading support.\n");
		return -1;
	}
#endif

	/* get DISPLAY environment variable */
	display = getenv("DISPLAY");
	if (display)
		log_std(("os: DISPLAY=%s\n", display));
	else
		log_std(("os: DISPLAY undef\n"));

	/* probe the delay system */
	os_delay();

	if (!os_internal_wm_active()) {
		log_std(("os: save term\n"));
		if (tcgetattr(fileno(stdin), &OS.term) != 0) {
			log_std(("ERROR:os: error getting the tty state.\n"));
			OS.term_active = 0;
		} else {
			OS.term_active = 1;
		}
	}

#if defined(USE_X)
	OS.x_active = 0;
	{
		int event_base, error_base;
		int major_version, minor_version;

		log_std(("os: XOpenDisplay()\n"));
		OS.dga_display = XOpenDisplay(0);
		if (OS.dga_display) {
			OS.x_active = 1;
		} else {
			log_std(("WARNING:os: XOpenDisplay() failed. All the X drivers will be disabled.\n"));
		}
	}
#endif
#if defined(USE_SVGALIB)
	OS.svgalib_active = 0;
	if (!os_internal_wm_active()) {
		int h;
		log_std(("os: open /dev/svga\n"));

		/* try opening the device, otherwise vga_init() will abort the program. */
		h = open("/dev/svga", O_RDWR);
		if (h >= 0) {
			int res;
			close(h);

			vga_disabledriverreport();

			/* check the version of the SVGALIB */
			res = vga_setmode(-1);
			if (res < 0 || res < 0x1911) { /* 1.9.11 */
				log_std(("WARNING:os: invalid SVGALIB version %x. All the SVGALIB drivers will be disabled.\n", (int)res));
				/* don't print the message. It may be a normal condition. */
				/* target_nfo("Invalid SVGALIB version, you need SVGALIB version 1.9.x or 2.0.x.\nPlease upgrade or recompile without SVGALIB support.\n"); */
			} else {
				log_std(("os: vga_init()\n"));
				if (vga_init() != 0) {
					log_std(("os: vga_init() failed\n"));
					target_err("Error initializing the SVGALIB video support.\n");
					return -1;
				}
				OS.svgalib_active = 1;
			}
		} else {
			log_std(("WARNING:os: open /dev/svga failed. All the SVGALIB drivers will be disabled.\n"));
			/* don't print the message. It may be a normal condition. */
			/* target_nfo("Error opening the SVGALIB device /dev/svga.\n"); */
		}
	} else {
		log_std(("WARNING:os: vga_init() skipped because X is active. All the SVGALIB drivers will be disabled.\n"));
		/* don't print the message. It may be a normal condition. */
		/* target_nfo("SVGALIB not initialized because it's unusable in X.\n"); */
	}
#endif
#if defined(USE_SDL)
	log_std(("os: SDL_Init(SDL_INIT_NOPARACHUTE)\n"));
	if (SDL_Init(SDL_INIT_NOPARACHUTE) != 0) {
		log_std(("os: SDL_Init() failed, %s\n", SDL_GetError()));
		target_err("Error initializing the SDL video support.\n");
		return -1;
	} 
	OS.sdl_active = 1;
	SDL_VERSION(&compiled);

	log_std(("os: compiled with sdl %d.%d.%d\n", compiled.major, compiled.minor, compiled.patch));
	log_std(("os: linked with sdl %d.%d.%d\n", SDL_Linked_Version()->major, SDL_Linked_Version()->minor, SDL_Linked_Version()->patch));
#ifdef USE_MSB
	if (SDL_BYTEORDER != SDL_BIG_ENDIAN) {
		target_err("Invalid SDL endianess.\n");
		return -1;
	}
#endif
#ifdef USE_LSB
	if (SDL_BYTEORDER != SDL_LIL_ENDIAN) {
		target_err("Invalid SDL endianess.\n");
		return -1;
	}
#endif
#endif
#if defined(USE_SLANG)
	OS.slang_active = 0;
	if (!os_internal_wm_active()) {
		log_std(("os: SLtt_get_terminfo()\n"));
		SLtt_get_terminfo();
		log_std(("os: SLsmg_init_smg()\n"));
		SLsmg_init_smg();
		OS.slang_active = 1;
	} else {
		log_std(("WARNING:os: SLang_init_tty() skipped because X is active. All the SLang drivers will be disabled.\n"));
	}
#endif
#if defined(USE_CURSES)
	OS.curses_active = 0;
	if (!os_internal_wm_active()) {
		log_std(("os: initscr()\n"));
		initscr();
		start_color();
		cbreak();
		noecho();
		nonl();
		OS.curses_active = 1;
	} else {
		log_std(("WARNING:os: curses initscr() skipped because X is active. All the curses drivers will be disabled.\n"));
	}
#endif

	/* set the titlebar */
	sncpy(OS.title_buffer, sizeof(OS.title_buffer), title);

	/* set some signal handlers */

	/* STANDARD signals */
	term_action.sa_handler = (void (*)(int))os_signal;
	/* block external generated signals in the signal handler */
	sigemptyset(&term_action.sa_mask);
	sigaddset(&term_action.sa_mask, SIGALRM);
	sigaddset(&term_action.sa_mask, SIGINT);
	sigaddset(&term_action.sa_mask, SIGTERM);
	sigaddset(&term_action.sa_mask, SIGHUP);
	sigaddset(&term_action.sa_mask, SIGQUIT);
	term_action.sa_flags = SA_RESTART | SA_SIGINFO;
	/* external generated */
	sigaction(SIGALRM, &term_action, 0);
	sigaction(SIGINT, &term_action, 0);
	sigaction(SIGTERM, &term_action, 0);
	/* internal generated */
	sigaction(SIGABRT, &term_action, 0);
	sigaction(SIGFPE, &term_action, 0);
	sigaction(SIGILL, &term_action, 0);
	sigaction(SIGSEGV, &term_action, 0);
	sigaction(SIGBUS, &term_action, 0);

	/* HUP signal */
	hup_action.sa_handler = os_hup_signal;
	sigemptyset(&hup_action.sa_mask);
	hup_action.sa_flags = SA_RESTART;
	sigaction(SIGHUP, &hup_action, 0);

	/* QUIT signal */
	quit_action.sa_handler = os_quit_signal;
	sigemptyset(&quit_action.sa_mask);
	quit_action.sa_flags = SA_RESTART;
	sigaction(SIGQUIT, &quit_action, 0);

	/* PIPE signal, ignoring it force some functions to */
	/* return with error. It happen for example on the LCD sockets. */
	pipe_action.sa_handler = SIG_IGN;
	sigemptyset(&pipe_action.sa_mask);
	pipe_action.sa_flags = SA_RESTART;
	sigaction(SIGPIPE, &pipe_action, 0);

	return 0;
}
Beispiel #24
0
//void sigintcallback();
int main() {
//INIT stuff
initscr();
raw();
noecho();
timeout(-1); //turn off blocking
//signal(SIGINT, &sigintcallback);

char vorgabe[MAXPOS];
char versuch[MAXPOS]; //jede Eingabe
char getroffen[MAXPOS]; //getroffene Buchstaben
int schwarz, weiss; //zaehler fuer getroffene buchstaben

printw("Bitte geben sie ihre zu ratende Kombination ein (B,G,Y,O,R,M): ");

for(int i=0;i<MAXPOS; i++){ //lese Vorgabe ein
    char buf;
    do {
        buf = toupper(getch());
    }
    while(buf<=MAXPOS+1);
	vorgabe[i] = buf;
	printw("_%c_", vorgabe[i]);
}
refresh(); //update screen
//sleep(1); //zur kontrolle
clear(); //clear screen

for(int v=0;v<=MAXVERSUCHE;v++){
    for(int a=0;a<MAXPOS;a++) getroffen[a] = vorgabe[a]; //Wert kopieren
    
    if(v==MAXVERSUCHE){
        printw("Pech! Die richtige Kombination lautet: _");
        for(int i=0;i<MAXPOS;i++){
            printw("_%c_", vorgabe[i]);
        }
        putchar('_');
        break;
    }
    else if(schwarz==MAXPOS){
        printw("Gratulation! Geraten nach %d Versuchen.", v);
        break;
    }
    schwarz=0; weiss=0; //clear variables
    
    printw("%d. Versuch: ", v+1);
    
    //gehe in Abfrageschleife
    for(int i=0;i<MAXPOS; i++){ //lese Versuch ein
    	versuch[i] = toupper(getch());
    	printw("_%c_", versuch[i]);
    }

    //vergleiche Versuch mit Vorgabe
    for(int vindex=0;vindex<MAXPOS; vindex++){ //gehe durch getroffen und versuch; index ist der einzelne char
        if(versuch[vindex] == getroffen[vindex]){
            schwarz++; //richtiger Char an richtiger Stelle
            getroffen[vindex] = 0; //markieren
        }
        else{ //suche nun f�r den aktuellen index in versuch einen gleichen in getroffen
            bool isDuplicate = false;
            bool occuredOnce = false;
            
            for(int gindex=0;gindex<MAXPOS;gindex++){ //gehe durch getroffen und suche nach uebereinstmmungen zum aktuellen vindex
                if(getroffen[gindex] == versuch[vindex]){
                    for(int gr=0;gr<MAXPOS;gr++){
                        if(getroffen[gr] == vindex){
                            if(!occuredOnce) occuredOnce = true;
                            else isDuplicate = true;
                        }
                    }
                    if(!isDuplicate) weiss++; //irgendwo ein richtiger Char
                    versuch[vindex] = gindex+1; //markieren
                }
            }
        }
    }
    printw("\t|| Schwarz: %d\t Weiss: %d\n", schwarz, weiss);
}

getch();
//printf("\e[2J\e[H"); //clrscr
endwin();
return 0;
}
Beispiel #25
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 */
#if defined set_escdelay
    set_escdelay(10);
#else
    ESCDELAY = 10;
#endif

    /* 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;
}
int adduser(void)
{
	
	/* Declarations */
	getmaxyx(stdscr, y,x); /* Screen Sizes */
	
	int key;
	
	while(true)
	{
	drawauscreen(); /* Draw the Screen */
	refresh();
	 do
	 {
		key = getch();
		switch(key)
		{
			/* Field Edit Keys which are number keys */
			case '1':
			 echo();
				if((loginname = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			 attron(A_REVERSE);
			 mvprintw(7, 35, "_________________");
			 mvwgetnstr(stdscr, 7,35, loginname, 15);
			 attroff(A_REVERSE);
			 noecho();
			break;
			case '2':
			 echo();
				if((usergecos = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			  attron(A_REVERSE);
			  mvprintw(8, 35, "_________________");
			  mvwgetnstr(stdscr, 8,35, usergecos, 15);
			  attroff(A_REVERSE);
			  noecho();
			break;
			case '3':
			 echo();
				if((userid = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			  attron(A_REVERSE);
			  mvprintw(9, 35, "_________________");
			  mvwgetnstr(stdscr, 9,35, userid, 5);
			  attroff(A_REVERSE);
			  noecho();
			break;
			case '4':
			 echo();
				if((groupid = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			  attron(A_REVERSE);
			  mvprintw(10, 35, "_________________");
			  mvwgetnstr(stdscr, 10,35, groupid, 5);
			  attroff(A_REVERSE);
			  noecho();
			break;
			  case '5':
			 echo();
				if((usershell = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			  attron(A_REVERSE);
			  mvprintw(11, 35, "_________________");
			  mvwgetnstr(stdscr, 11,35, usershell, 15);
			  attroff(A_REVERSE);
			  noecho();
			break;
			case '6':
			 echo();
				if((homedir = malloc(sizeof(char) * USER_BUFFER + 1)) == NULL)
				return(1);
			  attron(A_REVERSE);
			  mvprintw(12, 35, "_________________");
			  mvwgetnstr(stdscr, 12,35, homedir, 15);
			  attroff(A_REVERSE);
			  noecho();
			break;
			/* Function Key Controls */
			case KEY_F(1):  /* Help */
			
			break;
			case KEY_F(2):  /* Refresh */
			 refresh();
			break;
			case KEY_F(3): /* Cancel Key */
			
			break;
			case KEY_F(4): 
			/* Reset Fields if statements to prevent crashing if pressed more than once. strcmp does cause segmentation fault */
			 if(loginname != "(cleared)")
			 free(loginname);
		
			 
			 if(usergecos != "(cleared)")
			 free(usergecos);
			 
			 if(usershell != "(cleared)")
			 free(usershell);
			 
			 if(homedir != "(cleared)")
			 free(homedir); 
			 
			 if(userid != "(cleared)")
			 free(userid); 
			 
			 if(groupid != "(cleared)")
			 free(groupid); 
			 
			 loginname = "(cleared)";
			 usergecos = "(cleared)";
			 usershell = "(cleared)";
			 homedir = "(cleared)"; 
			 userid = "(cleared)"; 
			 groupid = "(cleared)"; 
			break;
			case KEY_F(5): /* Run Command */
			 //executecmd(command); /* Execute command */
			break;
			case KEY_F(6): /* Add User */
				verifyadd(); /* Confirms then Add or quits */
			break;
			case KEY_F(9): /* Run Default Shell */
			 clear();
			 endwin();
			 system(DEFAULT_SHELL);
			break;
			case KEY_F(10): /* Quits Dialog */
			 return(0);
			break;
			
		}
		drawauscreen();
		refresh();
	} while(key != '\n');
	
	/* Other Statments goes here */
	
	
 };
		
		
	
	/* Finish up */
	
	
	free(loginname);
	free(usergecos);
	free(usershell);
	free(homedir);
	
	return 0;
}
int main()
{	WINDOW *menu_win;
	int highlight = 1;
	int choice = 0;
	int c;
	int fd;

	fd = open("/dev/fb1",O_RDWR);
	if(fd < 0)
	{
		printf("Can not open device\n");
		return -1;
	}

	initscr();
	clear();
	noecho();
	cbreak();	/* Line buffering disabled. pass on everything */
	startx = (80 - WIDTH) / 2;
	starty = (24 - HEIGHT) / 2;
		
	menu_win = newwin(HEIGHT, WIDTH, starty, startx);
	keypad(menu_win, TRUE);
	mvprintw(0, 0, "Use arrow keys to go up and down, Press enter to select a choice");
	refresh();
	print_menu(menu_win, highlight);
	while(1)
	{	c = wgetch(menu_win);
		switch(c)
		{	case KEY_UP:
				if(highlight == 1)
					highlight = n_choices;
				else
					--highlight;
				break;
			case KEY_DOWN:
				if(highlight == n_choices)
					highlight = 1;
				else 
					++highlight;
				break;
			case KEY_RIGHT:
				if (cur_value[highlight-1]<100)
					cur_value[highlight-1]++;
				break;
			case KEY_LEFT:
				if (cur_value[highlight-1]>0)
					cur_value[highlight-1]--;
				break;
			case 10:
				choice = highlight;
				break;
			default:
				mvprintw(24, 0, "Charcter pressed is = %3d Hopefully it can be printed as '%c'", c, c);
				refresh();
				break;
		}

		
		brightness = cur_value[0];
		brightness_coeff = 2.0 * ((float)brightness/100.);

		contrast = cur_value[1];
		contrast_coeff = 2.0 * ((float)contrast/100.);

		saturation = cur_value[2];
		saturation_coeff = 2.0 * ((float)saturation/100.);

		hue = cur_value[3];
		hue_coeff = 180 + (180 * ((float)hue/100.));

		memcpy(color_correction_matrix,default_matrix_coeff_hd,sizeof(default_matrix_coeff_hd));
		create_color_correction_matrix();
		fb_set_std_table(fd, 255);
		
		print_menu(menu_win, highlight);
		if(choice != 0)	/* User did a choice come out of the infinite loop */
			break;
	}	
	mvprintw(23, 0, "You chose choice %d with choice string %s\n", choice, choices[choice - 1]);
	clrtoeol();
	refresh();
	endwin();
	return 0;
}
Beispiel #28
0
static void
test_inserts(int level)
{
    static bool first = TRUE;

    int ch;
    int limit;
    int row = 1;
    int col;
    int row2, col2;
    int length;
    wchar_t buffer[BUFSIZ];
    WINDOW *look = 0;
    WINDOW *work = 0;
    WINDOW *show = 0;
    int margin = (2 * MY_TABSIZE) - 1;
    Options option = ((m_opt ? oMove : oDefault)
                      | ((w_opt || (level > 0)) ? oWindow : oDefault));

    if (first) {
        static char cmd[80];
        setlocale(LC_ALL, "");

        putenv(strcpy(cmd, "TABSIZE=8"));

        initscr();
        (void) cbreak();	/* take input chars one at a time, no wait for \n */
        (void) noecho();	/* don't echo input */
        keypad(stdscr, TRUE);
    }

    limit = LINES - 5;
    if (level > 0) {
        look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1);
        work = newwin(limit - 2, COLS - (2 * level), 1, level);
        show = newwin(4, COLS, limit + 1, 0);
        box(look, 0, 0);
        wnoutrefresh(look);
        limit -= 2;
    } else {
        work = stdscr;
        show = derwin(stdscr, 4, COLS, limit + 1, 0);
    }
    keypad(work, TRUE);

    for (col = margin + 1; col < COLS; col += MY_TABSIZE)
        mvwvline(work, row, col, '.', limit - 2);

    mvwvline(work, row, margin, ACS_VLINE, limit - 2);
    mvwvline(work, row, margin + 1, ACS_VLINE, limit - 2);
    limit /= 2;

    mvwaddstr(work, 1, 2, "String");
    mvwaddstr(work, limit + 1, 2, "Chars");
    wnoutrefresh(work);

    buffer[length = 0] = '\0';
    legend(show, level, option, buffer, length);
    wnoutrefresh(show);

    doupdate();

    /*
     * Show the characters inserted in color, to distinguish from those that
     * are shifted.
     */
    if (has_colors()) {
        start_color();
        init_pair(1, COLOR_WHITE, COLOR_BLUE);
        wbkgdset(work, COLOR_PAIR(1) | ' ');
    }

    while ((ch = read_linedata(work)) != ERR && !isQUIT(ch)) {
        wmove(work, row, margin + 1);
        switch (ch) {
        case key_RECUR:
            test_inserts(level + 1);

            touchwin(look);
            touchwin(work);
            touchwin(show);

            wnoutrefresh(look);
            wnoutrefresh(work);
            wnoutrefresh(show);

            doupdate();
            break;
        case key_NEWLINE:
            if (row < limit) {
                ++row;
                /* put the whole string in, all at once */
                col2 = margin + 1;
                switch (option) {
                case oDefault:
                    if (n_opt > 1) {
                        for (col = 0; col < length; col += n_opt) {
                            col2 = ColOf(buffer, col, margin);
                            if (move(row, col2) != ERR) {
                                InsNStr(buffer + col, LEN(col));
                            }
                        }
                    } else {
                        if (move(row, col2) != ERR) {
                            InsStr(buffer);
                        }
                    }
                    break;
                case oMove:
                    if (n_opt > 1) {
                        for (col = 0; col < length; col += n_opt) {
                            col2 = ColOf(buffer, col, margin);
                            MvInsNStr(row, col2, buffer + col, LEN(col));
                        }
                    } else {
                        MvInsStr(row, col2, buffer);
                    }
                    break;
                case oWindow:
                    if (n_opt > 1) {
                        for (col = 0; col < length; col += n_opt) {
                            col2 = ColOf(buffer, col, margin);
                            if (wmove(work, row, col2) != ERR) {
                                WInsNStr(work, buffer + col, LEN(col));
                            }
                        }
                    } else {
                        if (wmove(work, row, col2) != ERR) {
                            WInsStr(work, buffer);
                        }
                    }
                    break;
                case oMoveWindow:
                    if (n_opt > 1) {
                        for (col = 0; col < length; col += n_opt) {
                            col2 = ColOf(buffer, col, margin);
                            MvWInsNStr(work, row, col2, buffer + col, LEN(col));
                        }
                    } else {
                        MvWInsStr(work, row, col2, buffer);
                    }
                    break;
                }

                /* do the corresponding single-character insertion */
                row2 = limit + row;
                for (col = 0; col < length; ++col) {
                    col2 = ColOf(buffer, col, margin);
                    switch (option) {
                    case oDefault:
                        if (move(row2, col2) != ERR) {
                            InsCh((chtype) buffer[col]);
                        }
                        break;
                    case oMove:
                        MvInsCh(row2, col2, (chtype) buffer[col]);
                        break;
                    case oWindow:
                        if (wmove(work, row2, col2) != ERR) {
                            WInsCh(work, (chtype) buffer[col]);
                        }
                        break;
                    case oMoveWindow:
                        MvWInsCh(work, row2, col2, (chtype) buffer[col]);
                        break;
                    }
                }
            } else {
                beep();
            }
            break;
        default:
            buffer[length++] = ch;
            buffer[length] = '\0';

            /* put the string in, one character at a time */
            col = ColOf(buffer, length - 1, margin);
            switch (option) {
            case oDefault:
                if (move(row, col) != ERR) {
                    InsStr(buffer + length - 1);
                }
                break;
            case oMove:
                MvInsStr(row, col, buffer + length - 1);
                break;
            case oWindow:
                if (wmove(work, row, col) != ERR) {
                    WInsStr(work, buffer + length - 1);
                }
                break;
            case oMoveWindow:
                MvWInsStr(work, row, col, buffer + length - 1);
                break;
            }

            /* do the corresponding single-character insertion */
            switch (option) {
            case oDefault:
                if (move(limit + row, col) != ERR) {
                    InsCh(ch);
                }
                break;
            case oMove:
                MvInsCh(limit + row, col, ch);
                break;
            case oWindow:
                if (wmove(work, limit + row, col) != ERR) {
                    WInsCh(work, ch);
                }
                break;
            case oMoveWindow:
                MvWInsCh(work, limit + row, col, ch);
                break;
            }

            wnoutrefresh(work);

            legend(show, level, option, buffer, length);
            wnoutrefresh(show);

            doupdate();
            break;
        }
    }
    if (level > 0) {
        delwin(show);
        delwin(work);
        delwin(look);
    }
}
int main()
{
    	struct usb_bus *busses;
    
    	usb_init();
    	usb_find_busses();
    	usb_find_devices();
    
    	busses = usb_get_busses();
        


   	struct usb_bus *bus;
    	int c, i, a;
    
    	/* ... */
    
    	for (bus = busses; bus; bus = bus->next) 
	{
    		struct usb_device *dev;
    
    		for (dev = bus->devices; dev; dev = dev->next) 
		{
    			/* Check if this device is a printer */
    			if (dev->descriptor.idVendor == 6465)
			{
				launcher = usb_open(dev);

				//do stuff
				int claimed = usb_claim_interface(launcher, 0); //the device is put into the associated state, these commands are not one shots. As such, you have to send a message triple where all 3 messages are all zeroes in order to stop whatever is happening (in my case, pressing a key sends the move/fire m
				if (claimed == 0)
				{
					int c;
					int redrawNeeded = 0;
					//movement_handler(0x10);

					//c = getchar();

					//movement_handler(0x0);
					//set up curses
					initscr();
					noecho();
					keypad(stdscr, TRUE);
					cbreak();
					nodelay(stdscr, TRUE);

					//draw the interface
					drawScreen();

					//main program loop
					while ( c = getch() )
					{
						//up
						if (c == '8')
						{
							movement_handler(1);

							move(halfLines - 2, halfCols);
							addch('8' | A_BOLD);
							redrawNeeded = 1;

							pauseForMove();
						}
						//down
						else if (c == '5')
						{
							movement_handler(2);

							move(halfLines + 2, halfCols);
							addch('5' | A_BOLD);
							redrawNeeded = 1;

							pauseForMove();
						}
						//left
						else if (c == '4')
						{
							movement_handler(4);

							move(halfLines, halfCols - 3);
							addch('4' | A_BOLD);
							redrawNeeded = 1;

							pauseForMove();
						}
						//right
						else if (c == '6')
						{
							movement_handler(8);
							
							move(halfLines, halfCols + 3);
							addch('6' | A_BOLD);
							redrawNeeded = 1;

							pauseForMove();
						}
						//fire
						else if (c == '0')
						{
							fire();
						}
						else if (c == 'q')
						{
							break;
						}
						else
						{
							movement_handler(0);
							if (redrawNeeded)
							{
								fixHighlights();
								redrawNeeded = 0;
							}
						}
					}


					//stop curses
					endwin();

					usb_release_interface(launcher, 0);
				}

				usb_close(launcher);
    			}
		}
    
    	}
}
Beispiel #30
0
int main(int argc, char *argv[])
{
    if (argc < 4) {
        printf("[!] Usage: %s [IP] [port] [public_key] <nokey>\n", argv[0]);
        exit(0);
    }
    int c;
    int on = 0;
    initMessenger();
    //if keyfiles exist
    if(argc > 4){
        if(strncmp(argv[4], "nokey", 6) < 0){
        //load_key();
        }
    } else {
        load_key();
    }
    m_callback_friendrequest(print_request);
    m_callback_friendmessage(print_message);
    m_callback_namechange(print_nickchange);
    m_callback_userstatus(print_statuschange);
    char idstring0[200];
    char idstring1[32][5];
    char idstring2[32][5];
    uint32_t i;
    for(i = 0; i < 32; i++)
    {
        if(self_public_key[i] < 16)
            strcpy(idstring1[i],"0");
        else 
            strcpy(idstring1[i], "");
        sprintf(idstring2[i], "%hhX",self_public_key[i]);
    }
    strcpy(idstring0,"[i] your ID: ");
    for (i=0; i<32; i++) {
        strcat(idstring0,idstring1[i]);
        strcat(idstring0,idstring2[i]);
    }
    initscr();
    noecho();
    raw();
    getmaxyx(stdscr,y,x);
    new_lines(idstring0);
    new_lines("[i] commands: /f ID (to add friend), /m friendnumber message  (to send message), /s status (to change status), /n nick (to change nickname), /q (to quit)");
    strcpy(line, "");
    IP_Port bootstrap_ip_port;
    bootstrap_ip_port.port = htons(atoi(argv[2]));
    int resolved_address = resolve_addr(argv[1]);
    if (resolved_address != -1)
        bootstrap_ip_port.ip.i = resolved_address;
    else 
        exit(1);
    
    DHT_bootstrap(bootstrap_ip_port, hex_string_to_bin(argv[3]));
    nodelay(stdscr, TRUE);
    while(true) {
        if (on == 0 && DHT_isconnected()) {
            new_lines("[i] connected to DHT\n[i] define username with /n");
            on = 1;
        }

        doMessenger();
        c_sleep(1);
        do_refresh();

        c = getch();

        if (c == ERR || c == 27)
            continue;

        getmaxyx(stdscr, y, x);
        if (c == '\n') {
            line_eval(lines, line);
            strcpy(line, "");
        } else if (c == 127) {
            line[strlen(line) - 1] = '\0';
        } else if (isalnum(c) || ispunct(c) || c == ' ') {
            strcpy(line, appender(line, (char) c));
        }
    }
    endwin();
    return 0;
}