Exemplo n.º 1
0
int
ncurses_init()
{
    int bg, fg;
    const char *term;
    // Set Locale
    setlocale(LC_CTYPE, "");

    // Initialize curses
    if (!initscr()) {
        fprintf(stderr, "Unable to initialize ncurses mode.\n");
        return -1;
    }

    // Check if user wants a black background
    if (setting_has_value(SETTING_BACKGROUND, "dark")) {
        assume_default_colors(COLOR_WHITE, COLOR_BLACK);
    } else {
        use_default_colors();
    }
    // Enable Colors
    start_color();
    cbreak();

    // Dont write user input on screen
    noecho();
    // Hide the cursor
    curs_set(0);
    // Only delay ESC Sequences 25 ms (we dont want Escape sequences)
    ESCDELAY = 25;

    // Redefine some keys
    term = getenv("TERM");
    if (term
        && (!strcmp(term, "xterm") || !strcmp(term, "xterm-color") || !strcmp(term, "vt220"))) {
        define_key("\033[H", KEY_HOME);
        define_key("\033[F", KEY_END);
        define_key("\033OP", KEY_F(1));
        define_key("\033OQ", KEY_F(2));
        define_key("\033OR", KEY_F(3));
        define_key("\033OS", KEY_F(4));
        define_key("\033[11~", KEY_F(1));
        define_key("\033[12~", KEY_F(2));
        define_key("\033[13~", KEY_F(3));
        define_key("\033[14~", KEY_F(4));
        define_key("\033[17;2~", KEY_F(18));
    }

    if (setting_has_value(SETTING_BACKGROUND, "dark")) {
        fg = COLOR_WHITE;
        bg = COLOR_BLACK;
    } else {
        fg = COLOR_DEFAULT;
        bg = COLOR_DEFAULT;
    }

    // Initialize colorpairs
    init_pair(CP_CYAN_ON_DEF, COLOR_CYAN, bg);
    init_pair(CP_YELLOW_ON_DEF, COLOR_YELLOW, bg);
    init_pair(CP_MAGENTA_ON_DEF, COLOR_MAGENTA, bg);
    init_pair(CP_GREEN_ON_DEF, COLOR_GREEN, bg);
    init_pair(CP_RED_ON_DEF, COLOR_RED, bg);
    init_pair(CP_BLUE_ON_DEF, COLOR_BLUE, bg);
    init_pair(CP_WHITE_ON_DEF, COLOR_WHITE, bg);
    init_pair(CP_DEF_ON_CYAN, fg, COLOR_CYAN);
    init_pair(CP_DEF_ON_BLUE, fg, COLOR_BLUE);
    init_pair(CP_WHITE_ON_BLUE, COLOR_WHITE, COLOR_BLUE);
    init_pair(CP_BLACK_ON_CYAN, COLOR_BLACK, COLOR_CYAN);
    init_pair(CP_WHITE_ON_CYAN, COLOR_WHITE, COLOR_CYAN);
    init_pair(CP_YELLOW_ON_CYAN, COLOR_YELLOW, COLOR_CYAN);
    init_pair(CP_BLUE_ON_CYAN, COLOR_BLUE, COLOR_CYAN);
    init_pair(CP_BLUE_ON_WHITE, COLOR_BLUE, COLOR_WHITE);
    init_pair(CP_CYAN_ON_WHITE, COLOR_CYAN, COLOR_WHITE);
    init_pair(CP_CYAN_ON_BLACK, COLOR_CYAN, COLOR_BLACK);

    return 0;
}
Exemplo n.º 2
0
int main(int argc, char *argv[]) {
  int i, option, task_list_size;
  int cflag = 0, lflag = 0, dflag = 0, iflag = 0;
  char *cvalue, *dvalue;
  char *tasks[100];
  FILE *task_list;

  while((option = getopt(argc, argv, "ilc:d:")) != -1) {
    switch(option) {
    case 'i':
      iflag = 1;
      break;
    case 'c':
      cflag = 1;
      cvalue = optarg;
      break;
    case 'd':
      dflag = 1;
      dvalue = optarg;
      break;
    case 'l':
      lflag = 1;
      break;
    default:
      fprintf(stderr, "Usage: %s [-c task] [-d task] [-l] [-i]\n", argv[0]);
      exit(EXIT_FAILURE);
    }
  }

  if(iflag) {
    WINDOW *window;
    int startx = 5, starty = 3, c, highlight;
    char buffer[100];

    initscr();
    clear();
    raw();
    noecho();
    cbreak();
    curs_set(0);

    startx = (80 - WIDTH);
    starty = (24 - HEIGHT);
    window = newwin(HEIGHT, WIDTH, starty, startx);
    keypad(window, TRUE);

    while(1) {
      mvwprintw(window, starty, startx, "TODOs ('c' to add, 'd' to remove)");
      wclrtoeol(window);

      if((task_list_size = read_tasks(tasks, task_list))) {
        for(i = 0; i < task_list_size; i++) {
          if(highlight == i) {
            wattron(window, A_REVERSE);
            mvwprintw(window, starty + (i + 2), startx, "%d. %s", i + 1, tasks[i]);
            wattroff(window, A_REVERSE);
          } else {
            mvwprintw(window, starty + (i + 2), startx, "%d. %s", i + 1, tasks[i]);
          }

          wclrtoeol(window);
        }

        wclrtobot(window);
      } else {
        mvwprintw(window, starty + 2, startx, "None!");
        wclrtoeol(window);
        wclrtobot(window);
      }

      wrefresh(window);

      c = wgetch(window);
      switch(c) {
      case KEY_UP:
        if(highlight == 0) {
          highlight = task_list_size - 1;
        } else {
          --highlight;
        }
        break;
      case KEY_DOWN:
        if(highlight == task_list_size - 1) {
          highlight = 0;
        } else {
          ++highlight;
        }
        break;
      case 'd':
        if(delete_task(tasks[highlight], task_list) == 1) {
          --highlight;
        }
        break;
      case 'c':
        mvwprintw(window, starty, startx, "Creating task: ");
        wclrtoeol(window);
        echo();

        if(wgetstr(window, buffer) == OK) {
          if(create_task(buffer, task_list) == 1) {
            if((task_list_size) == 0) {
              highlight = 0;
            } else {
              ++highlight;
            }
          }
        }

        noecho();
        break;
      }
    }

    curs_set(1);
    refresh();
    endwin();
  } else {
    if(dflag) {
      if(delete_task(dvalue, task_list) == 0) {
        fprintf(stderr, "Could not delete task!");
      }
    }

    if(cflag) {
      if(create_task(cvalue, task_list) == 0) {
        fprintf(stderr, "Could not create task!");
      }
    }

    if(lflag) {
      printf("TODOs\n\n");

      if((task_list_size = read_tasks(tasks, task_list))) {
        for(i = 0; i < task_list_size; i++) {
          printf("%s\n", tasks[i]);
        }
      } else {
        printf("None!\n");
      }
    }
  }

  return 0;
}
Exemplo n.º 3
0
/*
 * Prepare "curses" for use by the file "z-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(void)
{
	int i;

	int num_term = MAX_TERM_DATA, next_win = 0;

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


#if defined(USG)
	/* Initialize for USG Unix */
	if (initscr() == NULL) return (-1);
#else
	/* Initialize for other systems */
	if (initscr() == (WINDOW*)ERR) return (-1);
#endif

	/* Activate hooks */
	quit_aux = hook_quit;
	core_aux = hook_quit;

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

#ifdef USE_GRAPHICS
	/* Set graphics flag */
	use_graphics = GRAPHICS_NONE;

	/* Use the graphical wall tiles? */
	use_blocks = arg_graphics;
#endif

#ifdef A_COLOR

	/*** Init the Color-pairs and set up a translation table ***/

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

#ifdef REDEFINE_COLORS
	/* Can we change colors? */
	can_fix_color = (can_use_color && can_change_color() &&
	                 (COLORS >= 16) && (COLOR_PAIRS > 8));
#endif

	/* Attempt to use customized colors */
	if (can_fix_color)
	{
		/* Prepare the color pairs */
		for (i = 1; i <= 8; i++)
		{
			/* Reset the color */
			if (init_pair(i, i - 1, 0) == ERR)
			{
				quit("Color pair init failed");
			}

			/* Set up the colormap */
			colortable[i - 1] = (COLOR_PAIR(i) | A_NORMAL);
			colortable[i + 7] = (COLOR_PAIR(i) | A_BRIGHT);
		}

		/* XXX XXX XXX Take account of "gamma correction" */

		/* Prepare the "Angband Colors" */
		Term_xtra_gcu_react();
	}

	/* Attempt to use colors */
	else if (can_use_color)
	{
		/* Color-pair 0 is *always* WHITE on BLACK */

		/* Prepare the color pairs */
		init_pair(1, COLOR_RED,     COLOR_BLACK);
		init_pair(2, COLOR_GREEN,   COLOR_BLACK);
		init_pair(3, COLOR_YELLOW,  COLOR_BLACK);
		init_pair(4, COLOR_BLUE,    COLOR_BLACK);
		init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
		init_pair(6, COLOR_CYAN,    COLOR_BLACK);
		init_pair(7, COLOR_BLACK,   COLOR_BLACK);

		/* Prepare the "Angband Colors" -- Bright white is too bright */
		colortable[0] = (COLOR_PAIR(7) | A_NORMAL);	/* Black */
		colortable[1] = (COLOR_PAIR(0) | A_BRIGHT);	/* White */
		colortable[2] = (COLOR_PAIR(0) | A_NORMAL);	/* Grey XXX */
		colortable[3] = (COLOR_PAIR(1) | A_BRIGHT);	/* Orange XXX */
		colortable[4] = (COLOR_PAIR(1) | A_NORMAL);	/* Red */
		colortable[5] = (COLOR_PAIR(2) | A_NORMAL);	/* Green */
		colortable[6] = (COLOR_PAIR(4) | A_NORMAL);	/* Blue */
		colortable[7] = (COLOR_PAIR(3) | A_NORMAL);	/* Umber */
		colortable[8] = (COLOR_PAIR(7) | A_BRIGHT);	/* Dark-grey XXX */
		colortable[9] = (COLOR_PAIR(0) | A_NORMAL);	/* Light-grey XXX */
		colortable[10] = (COLOR_PAIR(5) | A_NORMAL);	/* Purple */
		colortable[11] = (COLOR_PAIR(3) | A_BRIGHT);	/* Yellow */
		colortable[12] = (COLOR_PAIR(5) | A_BRIGHT);	/* Light Red XXX */
		colortable[13] = (COLOR_PAIR(2) | A_BRIGHT);	/* Light Green */
		colortable[14] = (COLOR_PAIR(4) | A_BRIGHT);	/* Light Blue */
		colortable[15] = (COLOR_PAIR(3) | A_NORMAL);	/* Light Umber XXX */
	}

#endif


	/*** Low level preparation ***/

#ifdef USE_GETCH

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

#endif

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

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


	/*** Now prepare the term(s) ***/

	/* Create several terms */
	for (i = 0; i < num_term; i++)
	{
		int rows, cols, y, x;

		/* Hack - the main window is huge */
		
		/* Work out how much extra room we have */
		cols = (COLS - 80) / 4;
		rows = (LINES - 24) / 2;
		
		/* Prevent stupidly small windows */
		if (cols < 25) cols = 0;
		if (rows < 10) rows = 0;
		
		/* Ok - so we now have the size of the main window */
		cols += 80;
		rows += 24;

		/* Decide on size and position */
		switch (i)
		{
			/* Upper left */
			case 0:
				y = x = 0;
				break;

			/* Lower left */
			case 1:				
				y = rows + 1;
				x = 0;
				rows = LINES - (rows + 1);
				break;

			/* Upper right */
			case 2:				
				y = 0;
				x = cols + 1;
				cols = COLS - (cols + 1);
				break;

			/* Lower right */
			case 3:				
				y = rows + 1;
				x = cols + 1;
				rows = LINES - (rows + 1);
				cols = COLS - (cols + 1);				
				break;

			/* XXX */
			default:
				rows = cols = y = x = 0;
				break;
		}

		/* 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);
}
Exemplo n.º 4
0
/**
 * Main function. Initializes and starts the game
 */
int spitm() {listP mao1,mao2,pl11,pl12,pl13,pl14,pl21,pl22,pl23,pl24;
    int stock1[stk],stock2[stk],baralho[(num*2)-2],pc1[sz],pc2[sz],pc3[sz];
    mao1=mao2=pl11=pl12=pl13=pl14=pl21=pl22=pl23=pl24=NULL;
    int vencedor=0,turno=1,o,d,i=0,n=0,x=(LINES/2),y=(COLS/2);

    initscr();
    cbreak();
    keypad(stdscr,TRUE);
    noecho();
    start_color();
    init_pair(1,COLOR_WHITE,COLOR_GREEN);
    init_pair(2,COLOR_RED,COLOR_GREEN);
    bkgd(COLOR_PAIR(1));
    attron(COLOR_PAIR(2));

    limpa(pc1,13);
    limpa(pc2,13);
    limpa(pc3,13);
    shuff(baralho);
    atoa(baralho,stock1,20);
    atoa(baralho,stock2,20);
    mao1=atod(baralho,mao1,5);
    mao2=atod(baralho,mao2,5);
    while(!i) {
        if(stock1[0] > stock2[0]) {
            turno=1;i++;
        };break;
	    if(stock1[0] < stock2[0]) {
            turno=2;
            i++;
        };break;
	    barStk(stock1,stk);
        barStk(stock2,stk);
	};
    
    while(vencedor==0) {
        while(elemN(mao1)<5)
            mao1=atod(baralho,mao1,1);
        while(turno==1)	{
            clear();
            mostrac(mao1,pl11, pl12,pl13, pl14, mao2, pl21, pl22, pl23,pl24, pc1, pc2, pc3, stock1, stock2,turno);
            echo();
            mvprintw(22,0,"Insira origem(1-10) e destino (1-7):__ __");
            mvscanw(22,36," %d %d",&o,&d);
            if(o>0 && o<6) {
                if(d==1) {
                    if (showi(mao1,elemN(mao1)-o) == topAr(pc1)+1) {
                        dtoa(mao1,elemN(mao1)-o,pc1);
                    };
                };
                if(d==2) {
                    if (showi(mao1,elemN(mao1)-o) == topAr(pc2)+1) {
                        dtoa(mao1,elemN(mao1)-o,pc2);
                    };
                };
			    if(d==3) {
                    if (showi(mao1,elemN(mao1)-o) == topAr(pc3)+1) {
                        dtoa(mao1,elemN(mao1)-o,pc3);
                    };
                };
    			if(d==4) {
                    pl11=poe(pl11,showi(mao1,elemN(mao1)-o));
                    if(elemN(mao1) == o) {
                        mao1=rmUlt(mao1);turno=2;
                    } else {
                        rmI(mao1,elemN(mao1)-(o));
                        turno=2;
                    };
                };
	
			    if(d==5) {
                    pl12=poe(pl12,showi(mao1,elemN(mao1)-o));
                    if(elemN(mao1) == o) {
                        mao1=rmUlt(mao1);
                        turno=2;
                    } else {
                        rmI(mao1,elemN(mao1)-(o));
                        turno=2;
                    };
                };
			    if(d==6) {
                    pl13=poe(pl13,showi(mao1,elemN(mao1)-o));
                    if(elemN(mao1) == o) {
                        mao1=rmUlt(mao1);
                        turno=2;
                    } else {
                        rmI(mao1,elemN(mao1)-(o));
                        turno=2;
                    };
                };
			    if(d==7) {
                    pl14=poe(pl14,showi(mao1,elemN(mao1)-o));
                    if(elemN(mao1) == o) {
                        mao1=rmUlt(mao1);
                        turno=2;
                    } else {
                        rmI(mao1,elemN(mao1)-(o));
                        turno=2;
                    };
                };
			}; //end if(o>0 && o<6)
            if(o==10) {
                if(d==1){
                    if (topAr(stock1) == topAr(pc1)+1) {
                        addAe(stock1,pc1);
                    };
                };
			    if(d==2) {
                    if (topAr(stock1) == topAr(pc2)+1) {
                        addAe(stock1,pc2);
                    };
                };
			    if(d==3) {
                    if (topAr(stock1) == topAr(pc3)+1) {
                        addAe(stock1,pc3);
                    };
                };
            };
            if(o>5 && o< 10) {
                if(o==6 && d==1 && (elemN(pl11)!=0)) {
                    if (showi(pl11,elemN(pl11)-o) == topAr(pc1)+1) {
                        dtoa(pl11,elemN(pl11)-1,pc1);
                    };
                };
			    if(o==7 && d==1 && (elemN(pl12)!=0)) {
                    if (showi(pl12,elemN(pl12)-o) == topAr(pc1)+1) {
                        dtoa(pl12,elemN(pl12)-1,pc1);
                    };
                };
			    if(o==8 && d==1 && (elemN(pl13)!=0)) {
                    if (showi(pl13,elemN(pl13)-o) == topAr(pc1)+1) {
                        dtoa(pl13,elemN(pl13)-1,pc1);
                    };
                };
                if(o==9 && d==1 && (elemN(pl14)!=0)) {
                    if (showi(pl14,elemN(pl14)-o) == topAr(pc1)+1) {
                        dtoa(pl14,elemN(pl14)-1,pc1);
                    };
                };
            
                if(o==6 && d==2 && (elemN(pl11)!=0)) {
                    if (showi(pl11,elemN(pl11)-o) == topAr(pc2)+1) {
                        dtoa(pl11,elemN(pl11)-1,pc2);
                    };
                };
                if(o==7 && d==2 && (elemN(pl12)!=0)) {
                    if (showi(pl12,elemN(pl12)-o) == topAr(pc2)+1) {
                        dtoa(pl12,elemN(pl12)-1,pc2);
                    };
                };
                if(o==8 && d==2 && (elemN(pl13)!=0)) {
                    if (showi(pl13,elemN(pl13)-o) == topAr(pc2)+1) {
                        dtoa(pl13,elemN(pl13)-1,pc2);
                    };
                };
                if(o==9 && d==2 && (elemN(pl14)!=0)) {
                    if (showi(pl14,elemN(pl14)-o) == topAr(pc2)+1) {
                        dtoa(pl14,elemN(pl14)-1,pc2);
                    };
                };

                if(o==6 && d==3 && (elemN(pl11)!=0)) {
                    if (showi(pl11,elemN(pl11)-o) == topAr(pc3)+1) {
                        dtoa(pl11,elemN(pl11)-1,pc3);
                    };
                };
                if(o==7 && d==3 && (elemN(pl12)!=0)) {
                    if (showi(pl12,elemN(pl12)-o) == topAr(pc3)+1) {
                        dtoa(pl12,elemN(pl12)-1,pc3);
                    };
                };
                if(o==8 && d==3 && (elemN(pl13)!=0)) {
                    if (showi(pl13,elemN(pl13)-o) == topAr(pc3)+1) {
                        dtoa(pl13,elemN(pl13)-1,pc3);
                    };
                };
                if(o==9 && d==3 && (elemN(pl14)!=0)) {
                    if (showi(pl14,elemN(pl14)-o) == topAr(pc3)+1) {
                        dtoa(pl14,elemN(pl14)-1,pc3);
                    };
                };
            };//end if(o>5 && o< 10)
        }; //end while(turno==1)

        n=0;
        while ((stock1[n]==0) && (n<stk)) {
            n++;
        };
        // Winner is player 1
        if (stock1[n] == 0) {
            vencedor=1;
            turno=1;
        }

        // Tie
        if(baralho[num*2-3]==0)	{
            vencedor=3;
        };

        // Clean central stack
        if(pc1[0]==13) {
            atoa(pc1,baralho,13);
        };
        if(pc2[0]==13) {
            atoa(pc2,baralho,13);
        };
        if(pc3[0]==13) {
            atoa(pc3,baralho,13);
        };

        // fill hand 2
        while(elemN(mao2)<5) {
            mao2=atod(baralho,mao2,1);
        };

        while(turno==2) {
            clear();
            mostrac(mao1,pl11, pl12,pl13, pl14, mao2, pl21, pl22, pl23,pl24, pc1, pc2, pc3, stock1, stock2,turno);
            echo();
            mvprintw(22,0,"Insira origem(1-10) e destino (1-7):__ __");
            mvscanw(22,36,"%d %d",&o,&d);
            if(o>0 && o<6) {
                if(d==1) {
                    if (showi(mao2,elemN(mao2)-o) == topAr(pc1)+1) {
                        dtoa(mao2,elemN(mao2)-o,pc1);};
                    };
                    if(d==2) {
                        if (showi(mao2,elemN(mao2)-o) == topAr(pc2)+1) {
                            dtoa(mao2,elemN(mao2)-o,pc2);
                        };
                    };
                    if(d==3) {
                        if (showi(mao2,elemN(mao2)-o) == topAr(pc3)+1) {
                            dtoa(mao2,elemN(mao2)-o,pc3);
                        };
                    };
                    if(d==4) {
                        pl21=poe(pl21,showi(mao2,elemN(mao2)-o));
                        if(elemN(mao2) == o) {
                            mao2=rmUlt(mao2);turno=1;
                        } else {
                            rmI(mao2,elemN(mao2)-(o));
                            turno=1;
                        };
                    };
                    if(d==5) {
                        pl22=poe(pl22,showi(mao2,elemN(mao2)-o));
                        if(elemN(mao2) == o) {
                            mao2=rmUlt(mao2);
                            turno=1;
                        } else {
                            rmI(mao2,elemN(mao2)-(o));
                            turno=1;
                        };
                    };
                    if(d==6) {
                        pl23=poe(pl23,showi(mao2,elemN(mao2)-o));
                        if(elemN(mao2) == o) {
                            mao2=rmUlt(mao2);
                            turno=1;
                        } else {
                            rmI(mao2,elemN(mao2)-(o));
                            turno=1;
                        };
                    };
                    if(d==7) {
                        pl24=poe(pl24,showi(mao2,elemN(mao2)-o));
                        if(elemN(mao2) == o) {
                            mao2=rmUlt(mao2);
                            turno=1;
                        } else {
                            rmI(mao2,elemN(mao2)-(o));
                            turno=1;
                        }
                    };
		        };
                if(o==10) {
                    if(d==1){
                        if (topAr(stock2) == topAr(pc1)+1) {
                            addAe(stock2,pc1);
                        };
			        };
		            if(d==2) {
                        if (topAr(stock2) == topAr(pc2)+1) {
                            addAe(stock2,pc2);
                        };
			        };
                    if(d==3) {
                        if (topAr(stock2) == topAr(pc3)+1)  {
                            addAe(stock2,pc3);
                        };
				    };
                };
                if(o>5 && o< 10) {
                    if(o==6 && d==1 && (elemN(pl21)!=0)) {
                        if (showi(pl21,elemN(pl21)-o) == topAr(pc1)+1) {
                            dtoa(pl21,elemN(pl21)-1,pc1);
                        };
                    };
                    if(o==7 && d==1 && (elemN(pl22)!=0)) {
                        if (showi(pl22,elemN(pl22)-o) == topAr(pc1)+1) {
                            dtoa(pl22,elemN(pl22)-1,pc1);
                        };
                    };
                if(o==8 && d==1 && (elemN(pl23)!=0)) {
                    if (showi(pl23,elemN(pl23)-o) == topAr(pc1)+1) {
                        dtoa(pl23,elemN(pl23)-1,pc1);
                    };
                };
                if(o==9 && d==1 && (elemN(pl24)!=0)) {
                    if (showi(pl24,elemN(pl24)-o) == topAr(pc1)+1) {
                        dtoa(pl24,elemN(pl24)-1,pc1);
                    };
                };
                if(o==6 && d==2 && (elemN(pl21)!=0)) {
                    if (showi(pl21,elemN(pl21)-o) == topAr(pc2)+1) {
                        dtoa(pl21,elemN(pl21)-1,pc2);
                    };
                };
                if(o==7 && d==2 && (elemN(pl22)!=0)) {
                    if (showi(pl22,elemN(pl22)-o) == topAr(pc2)+1) {
                        dtoa(pl22,elemN(pl22)-1,pc2);
                    };
			    };
                if(o==8 && d==2 && (elemN(pl23)!=0)) {
                    if (showi(pl23,elemN(pl23)-o) == topAr(pc2)+1) {
                         dtoa(pl23,elemN(pl23)-1,pc2);
                     };
                };
                if(o==9 && d==2 && (elemN(pl24)!=0)) {
                    if (showi(pl24,elemN(pl24)-o) == topAr(pc2)+1) {
                        dtoa(pl24,elemN(pl24)-1,pc2);
                    };
                };

                if(o==6 && d==3 && (elemN(pl21)!=0)) {
                    if (showi(pl21,elemN(pl21)-o) == topAr(pc3)+1) {
                        dtoa(pl21,elemN(pl21)-1,pc3);
                    };
                };
                if(o==7 && d==3 && (elemN(pl22)!=0)) {
                    if (showi(pl22,elemN(pl22)-o) == topAr(pc3)+1) {
                        dtoa(pl22,elemN(pl22)-1,pc3);
                    };
                };
                if(o==8 && d==3 && (elemN(pl23)!=0)) {
                    if (showi(pl23,elemN(pl23)-o) == topAr(pc3)+1) {
                        dtoa(pl23,elemN(pl23)-1,pc3);
                    };
                };
                if(o==9 && d==3 && (elemN(pl24)!=0)) {
                    if (showi(pl24,elemN(pl24)-o) == topAr(pc3)+1) {
                        dtoa(pl24,elemN(pl24)-1,pc3);
                    };
                };
             };
        };
        n=0;
        while ((stock2[n]==0) && (n<stk)) {
            n++;
        };
        // Winner is player 2
        if (stock2[n] == 0) {
            vencedor=1;
            turno=1;
        }

        // Tie
        if(baralho[num*2-3]==0) {
            vencedor=3;
        };

        // Clean central stack
        if(pc1[0]==13) {
            atoa(pc1,baralho,13);
        };
        if(pc2[0]==13) {
            atoa(pc2,baralho,13);
        };
        if(pc3[0]==13) {
            atoa(pc3,baralho,13);
        };
    };
    if((vencedor==1)||(vencedor==2)) {
        clear();
        mvprintw(x-1,y-10,"+------------------------------------+");
        mvprintw(x,y-10,"|O jogador %d vence!                 |",vencedor);
        mvprintw(x+1,y-10,"+------------------------------------+");
        getch();
    } else {
        clear();
        mvprintw(x-1,y-10,"+------------------------------------+");
        mvprintw(x,y-10,"|Empate, não há vencedores.          |");
        mvprintw(x+1,y-10,"+------------------------------------+");
        getch();
    };
    endwin();
    bkgd(COLOR_PAIR(2));
    return 0;
}
Exemplo n.º 5
0
void
init_display(void)
{
	bool no_display = !!getenv("TIG_NO_DISPLAY");
	const char *term;
	int x, y;

	die_callback = done_display;
	/* XXX: Restore tty modes and let the OS cleanup the rest! */
	if (atexit(done_display))
		die("Failed to register done_display");

	/* Initialize the curses library */
	if (!no_display && isatty(STDIN_FILENO)) {
		cursed = !!initscr();
		opt_tty = stdin;
	} else {
		/* Leave stdin and stdout alone when acting as a pager. */
		FILE *out_tty;

		opt_tty = fopen("/dev/tty", "r+");
		out_tty = no_display ? fopen("/dev/null", "w+") : opt_tty;
		if (!opt_tty || !out_tty)
			die("Failed to open /dev/tty");
		cursed = !!newterm(NULL, out_tty, opt_tty);
	}

	if (!cursed)
		die("Failed to initialize curses");

	nonl();		/* Disable conversion and detect newlines from input. */
	cbreak();       /* Take input chars one at a time, no wait for \n */
	noecho();       /* Don't echo input */
	leaveok(stdscr, false);

	init_colors();

	getmaxyx(stdscr, y, x);
	status_win = newwin(1, x, y - 1, 0);
	if (!status_win)
		die("Failed to create status window");

	/* Enable keyboard mapping */
	keypad(status_win, true);
	wbkgdset(status_win, get_line_attr(NULL, LINE_STATUS));
	enable_mouse(opt_mouse);

#if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
	set_tabsize(opt_tab_size);
#else
	TABSIZE = opt_tab_size;
#endif

	term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
	if (term && !strcmp(term, "gnome-terminal")) {
		/* In the gnome-terminal-emulator, the warning message
		 * shown when scrolling up one line while the cursor is
		 * on the first line followed by scrolling down one line
		 * corrupts the status line. This is fixed by calling
		 * wclear. */
		use_scroll_status_wclear = true;
		use_scroll_redrawwin = false;

	} else if (term && !strcmp(term, "xrvt-xpm")) {
		/* No problems with full optimizations in xrvt-(unicode)
		 * and aterm. */
		use_scroll_status_wclear = use_scroll_redrawwin = false;

	} else {
		/* When scrolling in (u)xterm the last line in the
		 * scrolling direction will update slowly. */
		use_scroll_redrawwin = true;
		use_scroll_status_wclear = false;
	}
}
Exemplo n.º 6
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_all_mods = false;

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    PATH_INFO::init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#if (defined USE_HOME_DIR || defined USE_XDG_DIR)
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standard_filenames();

    MAP_SHARING::setDefaults();
    {
        const char *section_default = nullptr;
        const char *section_map_sharing = "Map sharing";
        const char *section_user_directory = "User directories";
        const arg_handler first_pass_arguments[] = {
            {
                "--seed", "<string of letters and or numbers>",
                "Sets the random number generator's seed value",
                section_default,
                [&seed](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    const unsigned char *hash_input = (const unsigned char *) params[0];
                    seed = djb2_hash(hash_input);
                    return 1;
                }
            },
            {
                "--jsonverify", nullptr,
                "Checks the cdda json files",
                section_default,
                [&verifyexit](int, const char **) -> int {
                    verifyexit = true;
                    return 0;
                }
            },
            {
                "--check-mods", nullptr,
                "Checks the json files belonging to cdda mods",
                section_default,
                [&check_all_mods](int, const char **) -> int {
                    check_all_mods = true;
                    return 0;
                }
            },
            {
                "--basepath", "<path>",
                "Base path for all game data subdirectories",
                section_default,
                [](int num_args, const char **params) {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_base_path(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            },
            {
                "--shared", nullptr,
                "Activates the map-sharing mode",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setSharing(true);
                    MAP_SHARING::setCompetitive(true);
                    MAP_SHARING::setWorldmenu(false);
                    return 0;
                }
            },
            {
                "--username", "<name>",
                "Instructs map-sharing code to use this name for your character.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::setUsername(params[0]);
                    return 1;
                }
            },
            {
                "--addadmin", "<username>",
                "Instructs map-sharing code to use this name for your character and give you "
                "access to the cheat functions.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addAdmin(params[0]);
                    return 1;
                }
            },
            {
                "--adddebugger", "<username>",
                "Informs map-sharing code that you're running inside a debugger",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addDebugger(params[0]);
                    return 1;
                }
            },
            {
                "--competitive", nullptr,
                "Instructs map-sharing code to disable access to the in-game cheat functions",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setCompetitive(true);
                    return 0;
                }
            },
            {
                "--userdir", "<path>",
                "Base path for user-overrides to files from the ./data directory and named below",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_user_dir(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            }
        };

        // The following arguments are dependent on one or more of the previous flags and are run
        // in a second pass.
        const arg_handler second_pass_arguments[] = {
            {
                "--worldmenu", nullptr,
                "Enables the world menu in the map-sharing code",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setWorldmenu(true);
                    return true;
                }
            },
            {
                "--datadir", "<directory name>",
                "Sub directory from which game data is loaded",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("datadir", params[0]);
                    PATH_INFO::update_datadir();
                    return 1;
                }
            },
            {
                "--savedir", "<directory name>",
                "Subdirectory for game saves",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("savedir", params[0]);
                    return 1;
                }
            },
            {
                "--configdir", "<directory name>",
                "Subdirectory for game configuration",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("config_dir", params[0]);
                    PATH_INFO::update_config_dir();
                    return 1;
                }
            },
            {
                "--memorialdir", "<directory name>",
                "Subdirectory for memorials",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("memorialdir", params[0]);
                    return 1;
                }
            },
            {
                "--optionfile", "<filename>",
                "Name of the options file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("options", params[0]);
                    return 1;
                }
            },
            {
                "--keymapfile", "<filename>",
                "Name of the keymap file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("keymap", params[0]);
                    return 1;
                }
            },
            {
                "--autopickupfile", "<filename>",
                "Name of the autopickup options file within the configdir",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("autopickup", params[0]);
                    return 1;
                }
            },
            {
                "--motdfile", "<filename>",
                "Name of the message of the day file within the motd directory",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("motd", params[0]);
                    return 1;
                }
            },
        };

        // Process CLI arguments.
        const size_t num_first_pass_arguments =
            sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]);
        const size_t num_second_pass_arguments =
            sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]);
        int saved_argc = --argc; // skip program name
        const char **saved_argv = (const char **)++argv;
        while (argc) {
            if(!strcmp(argv[0], "--help")) {
                printHelpMessage(first_pass_arguments, num_first_pass_arguments,
                                 second_pass_arguments, num_second_pass_arguments);
                return 0;
            } else {
                bool arg_handled = false;
                for (size_t i = 0; i < num_first_pass_arguments; ++i) {
                    auto &arg_handler = first_pass_arguments[i];
                    if (!strcmp(argv[0], arg_handler.flag)) {
                        argc--;
                        argv++;
                        int args_consumed = arg_handler.handler(argc, (const char **)argv);
                        if (args_consumed < 0) {
                            printf("Failed parsing parameter '%s'\n", *(argv - 1));
                            exit(1);
                        }
                        argc -= args_consumed;
                        argv += args_consumed;
                        arg_handled = true;
                        break;
                    }
                }
                // Skip other options.
                if (!arg_handled) {
                    --argc;
                    ++argv;
                }
            }
        }
        while (saved_argc) {
            bool arg_handled = false;
            for (size_t i = 0; i < num_second_pass_arguments; ++i) {
                auto &arg_handler = second_pass_arguments[i];
                if (!strcmp(saved_argv[0], arg_handler.flag)) {
                    --saved_argc;
                    ++saved_argv;
                    int args_consumed = arg_handler.handler(saved_argc, saved_argv);
                    if (args_consumed < 0) {
                        printf("Failed parsing parameter '%s'\n", *(argv - 1));
                        exit(1);
                    }
                    saved_argc -= args_consumed;
                    saved_argv += args_consumed;
                    arg_handled = true;
                    break;
                }
            }
            // Ingore unknown options.
            if (!arg_handled) {
                --saved_argc;
                ++saved_argv;
            }
        }
    }

    if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
        printf("Can't open or create %s. Check permissions.\n",
               FILENAMES["user_dir"].c_str());
        exit(1);
    }

    setupDebug();

    if (setlocale(LC_ALL, "") == NULL) {
        DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '').";
    }

    // Options strings loaded with system locale
    initOptions();
    load_options();

    set_language(true);

    if (initscr() == NULL) { // Initialize ncurses
        DebugLog( D_ERROR, DC_ALL ) << "initscr failed!";
        return 1;
    }
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        g->load_static_data();
        if (verifyexit) {
            if(g->game_error()) {
                exit_handler(-999);
            }
            exit_handler(0);
        }
        if (check_all_mods) {
            // Here we load all the mods and check their
            // consistency (both is done in check_all_mod_data).
            g->init_ui();
            popup_nowait("checking all mods");
            g->check_all_mod_data();
            if(g->game_error()) {
                exit_handler(-999);
            }
            // At this stage, the mods (and core game data)
            // are find and we could start playing, but this
            // is only for verifying that stage, so we exit.
            exit_handler(0);
        }
    } catch(std::string &error_message) {
        if(!error_message.empty()) {
            debugmsg("%s", error_message.c_str());
        }
        exit_handler(-999);
    }

    // Now we do the actual game.

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#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

    bool quit_game = false;
    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}
Exemplo n.º 7
0
void
tty_raw_mode (void)
{
    raw ();                     /* FIXME: uneeded? */
    cbreak ();
}
Exemplo n.º 8
0
uint8_t ccbi_cbreak(int on) { return chk(on ? nocbreak() : cbreak()); }
Exemplo n.º 9
0
int
main(int argc, char *argv[])
{
    time_t now;
    struct tm *tm;
    long t, a;
    int i, j, s, k;
    int count = 0;
    FILE *ofp = stdout;
    FILE *ifp = stdin;
    bool scrol = FALSE;

    setlocale(LC_ALL, "");

    CATCHALL(sighndl);

    while ((k = getopt(argc, argv, "sn")) != -1) {
	switch (k) {
	case 's':
	    scrol = TRUE;
	    break;
	case 'n':
	    ifp = fopen("/dev/null", "r");
	    redirected = TRUE;
	    break;
	default:
	    usage();
	}
    }
    if (optind < argc) {
	count = atoi(argv[optind++]);
	assert(count >= 0);
    }
    if (optind < argc)
	usage();

    if (redirected) {
	char *name = getenv("TERM");
	if (name == 0
	    || newterm(name, ofp, ifp) == 0) {
	    fprintf(stderr, "cannot open terminal\n");
	    ExitProgram(EXIT_FAILURE);
	}

    } else {
	initscr();
    }
    cbreak();
    noecho();
    nodelay(stdscr, 1);
    curs_set(0);

    hascolor = has_colors();

    if (hascolor) {
	short bg = COLOR_BLACK;
	start_color();
#if HAVE_USE_DEFAULT_COLORS
	if (use_default_colors() == OK)
	    bg = -1;
#endif
	init_pair(PAIR_DIGITS, COLOR_BLACK, COLOR_RED);
	init_pair(PAIR_OTHERS, COLOR_RED, bg);
	init_pair(PAIR_FRAMES, COLOR_WHITE, bg);
	(void) attrset(COLOR_PAIR(PAIR_OTHERS));
    }

  restart:
    for (j = 0; j < 5; j++)
	older[j] = newer[j] = next[j] = 0;

    clear();
    drawbox(FALSE);

    do {
	char buf[30];

	time(&now);
	tm = localtime(&now);

	mask = 0;
	set(tm->tm_sec % 10, 0);
	set(tm->tm_sec / 10, 4);
	set(tm->tm_min % 10, 10);
	set(tm->tm_min / 10, 14);
	set(tm->tm_hour % 10, 20);
	set(tm->tm_hour / 10, 24);
	set(10, 7);
	set(10, 17);

	for (k = 0; k < 6; k++) {
	    if (scrol) {
		for (i = 0; i < 5; i++)
		    newer[i] = (newer[i] & ~mask) | (newer[i + 1] & mask);
		newer[5] = (newer[5] & ~mask) | (next[k] & mask);
	    } else
		newer[k] = (newer[k] & ~mask) | (next[k] & mask);
	    next[k] = 0;
	    for (s = 1; s >= 0; s--) {
		standt(s);
		for (i = 0; i < 6; i++) {
		    if ((a = (newer[i] ^ older[i]) & (s ? newer : older)[i])
			!= 0) {
			for (j = 0, t = 1 << 26; t; t >>= 1, j++) {
			    if (a & t) {
				if (!(a & (t << 1))) {
				    move(YBASE + i, XBASE + 2 * j);
				}
				addstr("  ");
			    }
			}
		    }
		    if (!s) {
			older[i] = newer[i];
		    }
		}
		if (!s) {
		    if (scrol)
			drawbox(TRUE);
		    refresh();
		    /*
		     * If we're scrolling, space out the refreshes to fake
		     * movement.  That's 7 frames, or 6 intervals, which would
		     * be 166 msec if we spread it out over a second.  It looks
		     * better (but will work on a slow terminal, e.g., less
		     * than 9600bd) to squeeze that into a half-second, and use
		     * half of 170 msec to ensure that the program doesn't eat
		     * a lot of time when asking what time it is, at the top of
		     * this loop -T.Dickey
		     */
		    if (scrol)
			napms(85);
		}
	    }
	}

	/* this depends on the detailed format of ctime(3) */
	(void) strcpy(buf, ctime(&now));
	(void) strcpy(buf + 10, buf + 19);
	MvAddStr(16, 30, buf);

	move(6, 0);
	drawbox(FALSE);
	refresh();

	/*
	 * If we're not scrolling, wait 1000 msec (1 sec).  Use napms() rather
	 * than sleep() because the latter does odd things on some systems,
	 * e.g., suspending output as well.
	 */
	if (scrol)
	    napms(500);
	else
	    napms(1000);

	/*
	 * This is a safe way to check if we're interrupted - making the signal
	 * handler set a flag that we can check.  Since we're running
	 * nodelay(), the wgetch() call returns immediately, and in particular
	 * will return an error if interrupted.  This works only if we can
	 * read from the input, of course.
	 */
	switch (wgetch(stdscr)) {
	case 'q':
	    count = 1;
	    break;
	case 's':
	    nodelay(stdscr, FALSE);
	    break;
	case ' ':
	    nodelay(stdscr, TRUE);
	    break;
#ifdef KEY_RESIZE
	case KEY_RESIZE:
#endif
	case '?':
	    goto restart;
	case ERR:
	    if (sigtermed) {
		(void) standend();
		endwin();
		fprintf(stderr, "gdc terminated by signal %d\n", sigtermed);
		ExitProgram(EXIT_FAILURE);
	    }
	    /* FALLTHRU */
	default:
	    continue;
	}
    } while (--count);
    (void) standend();
    endwin();
    ExitProgram(EXIT_SUCCESS);
}
Exemplo n.º 10
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;
	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 '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);
		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;
}
Exemplo n.º 11
0
static WINDOW *
ncurses_setup(void){
	struct ncurses_input_marshal *nim;
	const char *errstr = NULL;
	WINDOW *w = NULL;

	fprintf(stderr,"Entering ncurses mode...\n");
	if(initscr() == NULL){
		fprintf(stderr,"Couldn't initialize ncurses\n");
		return NULL;
	}
	if(cbreak() != OK){
		errstr = "Couldn't disable input buffering\n";
		goto err;
	}
	if(noecho() != OK){
		errstr = "Couldn't disable input echoing\n";
		goto err;
	}
	if(intrflush(stdscr,TRUE) != OK){
		errstr = "Couldn't set flush-on-interrupt\n";
		goto err;
	}
	if(scrollok(stdscr,FALSE) != OK){
		errstr = "Couldn't disable scrolling\n";
		goto err;
	}
	if(nonl() != OK){
		errstr = "Couldn't disable nl translation\n";
		goto err;
	}
	if(start_color() != OK){
		errstr = "Couldn't initialize ncurses color\n";
		goto err;
	}
	if(use_default_colors()){
		errstr = "Couldn't initialize ncurses colordefs\n";
		goto err;
	}
	w = stdscr;
	keypad(stdscr,TRUE);
	if(nodelay(stdscr,FALSE) != OK){
		errstr = "Couldn't set blocking input\n";
		goto err;
	}
	if(preserve_colors() != OK){
		errstr = "Couldn't preserve initial colors\n";
		goto err;
	}
	if(setup_extended_colors() != OK){
		errstr = "Couldn't initialize extended colors\n";
		assert(init_pair(BORDER_COLOR,COLOR_GREEN,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_RED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CYAN,-1) == OK); // will use A_BOLD via OUR_BOLD
		assert(init_pair(UCAST_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(USELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(MSELECTED_COLOR,-1,COLOR_BLUE) == OK);
		assert(init_pair(BSELECTED_COLOR,-1,COLOR_MAGENTA) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_WHITE,-1) == OK);
	}else{
		assert(init_pair(BORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_ORANGE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_RED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_WHITE,COLOR_PALEALUMINIUM) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CHAMELEON,-1) == OK);
		assert(init_pair(UCAST_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_SKYBLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_VIOLET,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,-1,COLOR_CHAMELEON) == OK);
		assert(init_pair(USELECTED_COLOR,-1,COLOR_BLUE) == OK);
		assert(init_pair(MSELECTED_COLOR,-1,COLOR_SKYBLUE) == OK);
		assert(init_pair(BSELECTED_COLOR,-1,COLOR_VIOLET) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CHAMELEON_75,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_BLUE_75,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_SKYBLUE_75,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_VIOLET_75,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CHAMELEON_50,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_BLUE_50,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_SKYBLUE_50,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_VIOLET_50,-1) == OK);
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CHAMELEON,COLOR_PALECYAN) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_BLUE,COLOR_PALECYAN) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_SKYBLUE,COLOR_PALECYAN) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_VIOLET,COLOR_PALECYAN) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CHAMELEON_75,COLOR_PALECYAN) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_BLUE_75,COLOR_PALECYAN) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_SKYBLUE_75,COLOR_PALECYAN) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_VIOLET_75,COLOR_PALECYAN) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CHAMELEON_50,COLOR_PALECYAN) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_BLUE_50,COLOR_PALECYAN) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_SKYBLUE_50,COLOR_PALECYAN) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_VIOLET_50,COLOR_PALECYAN) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_BRIGHTWHITE,-1) == OK);
	}
	if(curs_set(0) == ERR){
		errstr = "Couldn't disable cursor\n";
		goto err;
	}
	if(setup_statusbar(COLS)){
		errstr = "Couldn't setup status bar\n";
		goto err;
	}
	if(draw_main_window(w)){
		errstr = "Couldn't use ncurses\n";
		goto err;
	}
	if((nim = malloc(sizeof(*nim))) == NULL){
		goto err;
	}
	nim->w = w;
	nim->maintid = pthread_self();
	// Panels aren't yet being used, so we need call refresh() to
	// paint the main window.
	refresh();
	if(pthread_create(&inputtid,NULL,ncurses_input_thread,nim)){
		errstr = "Couldn't create UI thread\n";
		free(nim);
		goto err;
	}
	// FIXME install SIGWINCH() handler...?
	return w;

err:
	mandatory_cleanup(&w);
	fprintf(stderr,"%s",errstr);
	return NULL;
}
Exemplo n.º 12
0
int start_ncurses(const char *prog_name, const char *real_prog_name)
{
#if defined(DJGPP) || defined(__MINGW32__)
  if(initscr()==NULL)
  {
    log_critical("initscr() has failed. Exiting\n");
    printf("initscr() has failed. Exiting\n");
    printf("Press Enter key to quit.\n");
    (void)getchar();
    return 1;
  }
#else
  get_newterm(real_prog_name);
  if(screenp==NULL)
  {
    log_critical("Terminfo file is missing.\n");
#if defined(__CYGWIN__)
    printf("The terminfo file '63\\cygwin' is missing.\n");
#else
    printf("Terminfo file is missing.\n");
#endif
    printf("Extract all files and subdirectories before running the program.\n");
    printf("Press Enter key to quit.\n");
    (void)getchar();
    return 1;
  }
#endif
  /* Should solve a problem with users who redefined the colors */
  if(has_colors())
  {
    start_color();
#ifdef HAVE_ASSUME_DEFAULT_COLORS
    assume_default_colors(COLOR_WHITE,COLOR_BLACK);
#endif
    init_pair(1, COLOR_RED, COLOR_BLACK);
    init_pair(2, COLOR_GREEN, COLOR_BLACK);
  }
  noecho();
#ifndef DJGPP
  nonl(); /*don't use for Dos version but enter will work with it... dilema */
#endif
  /*  intrflush(stdscr, FALSE); */
  cbreak();
  curs_set(0);
  {
    int quit=0;
    while(LINES>=8 && LINES<MINIMUM_LINES && quit==0)
    {
      aff_copy(stdscr);
      wmove(stdscr,4,0);
      wprintw(stdscr,"%s need %d lines to work.", prog_name, MINIMUM_LINES);
      wmove(stdscr,5,0);
      wprintw(stdscr,"Please enlarge the terminal.");
      wmove(stdscr,LINES-2,0);
      wattrset(stdscr, A_REVERSE);
      waddstr(stdscr,"[ Quit ]");
      wattroff(stdscr, A_REVERSE);
      wrefresh(stdscr);
      switch(wgetch(stdscr))
      {
	case 'q':
	case 'Q':
	case KEY_ENTER:
#ifdef PADENTER
	case PADENTER:
#endif
	case '\n':
	case '\r':
	  quit=1;
	  break;
      }
    }
  }
  if(LINES < MINIMUM_LINES)
  {
    end_ncurses();
    printf("%s need %d lines to work.\nPlease enlarge the terminal and restart %s.\n", prog_name, MINIMUM_LINES, prog_name);
    log_critical("Terminal has only %d lines\n",LINES);
    return 1;
  }
  return 0;
}
Exemplo n.º 13
0
int main()
{   

    FILE * pwrite = fopen("/dev/rfcomm0", "w");

    if(pwrite == NULL){
        printf("couldn't open rfcomm\n");
        return 0;
    }


    int c;

    initscr();
    clear();
    noecho();
    cbreak();   /* Line buffering disabled. pass on everything */
    
    keypad(stdscr, TRUE);
    mvprintw(0, 0, "Use arrow keys to choose direction of motion");
    mvprintw(1, 0, "Press the same key to undo your selection");
    mvprintw(2, 0, "Spacebar switches between high/low speed");
    refresh();
    while(1)
    {   c = getch();
        // clear();
        switch(c)
        {   
            case ' ':
                fputc(' ', pwrite);
                fflush(pwrite);

                mvprintw(5, 0, "SPEED");
                clrtoeol();
                break;

            case KEY_UP:
                fputc('o', pwrite);
                fflush(pwrite);

                mvprintw(5, 0, "UP");
                clrtoeol();
                break;
            case KEY_DOWN:
                fputc('c', pwrite);
                fflush(pwrite);

                mvprintw(5, 0, "DOWN");
                clrtoeol();
                break;
            case KEY_LEFT:
                fputc('r', pwrite);
                fflush(pwrite);

                mvprintw(5, 0, "LEFT");
                clrtoeol();
                break;
            case KEY_RIGHT:
                fputc('l', pwrite);
                fflush(pwrite);

                mvprintw(5, 0, "RIGHT");
                clrtoeol();
                break;
            default:
                mvprintw(5, 0, "Undefined: %3d '%c'", c, c);
                clrtoeol();
                break;
        }

        refresh();
    }   
    clrtoeol();
    refresh();
    endwin();
    return 0;
}
Exemplo n.º 14
0
/*
 * Prepare "curses" for use by the file "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 num_term = 4, next_win = 0;
   char path[1024];

   /* Unused */
   (void)argc;
   (void)argv;


#ifdef USE_SOUND

   /* Build the "sound" path */
   path_build(path, sizeof(path), ANGBAND_DIR_XTRA, "sound");

   /* Allocate the path */
   ANGBAND_DIR_XTRA_SOUND = string_make(path);

#endif

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

#if defined(USG)
   /* Initialize for USG Unix */
   if (initscr() == NULL) return (-1);
#else
   /* Initialize for others systems */
   if (initscr() == (WINDOW*)ERR) return (-1);
#endif

   /* Activate hooks */
   quit_aux = hook_quit;
   core_aux = hook_quit;

   /* Hack -- Require large screen, or Quit with message */
   i = ((LINES < 24) || (COLS < 80));
   if (i) quit("Angband needs an 80x24 'curses' screen");


#ifdef A_COLOR

   /*** Init the Color-pairs and set up a translation table ***/

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

#ifdef REDEFINE_COLORS
	/* Can we change colors? */
	can_fix_color = (can_use_color && can_change_color() &&
			 (COLORS >= 16) && (COLOR_PAIRS > 8));
#endif

   /* Attempt to use customized colors */
   if (can_fix_color)
   {
      /* Prepare the color pairs */
      for (i = 1; i <= 63; i++)
      {
	 /* Reset the color */
	 if (init_pair(i, (i - 1) % 8, (i - 1) / 8) == ERR)
	 {
	    quit("Color pair init failed");
	 }

	/* Set up the colormap */
	colortable[i - 1] = (COLOR_PAIR(i) | A_NORMAL);
	colortable[i + 7] = (COLOR_PAIR(i) | A_BRIGHT);

	/* XXX XXX XXX Take account of "gamma correction" */

	/* Prepare the "Angband Colors" */
	Term_xtra_gcu_react();
      }
   }
   /* Attempt to use colors */
   else if (can_use_color)
   {
		/* Color-pair 0 is *always* WHITE on BLACK */

		/* Prepare the color pairs */
		init_pair(1, COLOR_RED,     COLOR_BLACK);
		init_pair(2, COLOR_GREEN,   COLOR_BLACK);
		init_pair(3, COLOR_YELLOW,  COLOR_BLACK);
		init_pair(4, COLOR_BLUE,    COLOR_BLACK);
		init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
		init_pair(6, COLOR_CYAN,    COLOR_BLACK);
		init_pair(7, COLOR_BLACK,   COLOR_BLACK);

		/* Prepare the "Angband Colors" -- Bright white is too bright */
		/* Changed in Drangband. Cyan as grey sucks -- -TM- */
		colortable[0] = (COLOR_PAIR(7) | A_NORMAL);	/* Black */
		colortable[1] = (COLOR_PAIR(0) | A_BRIGHT);	/* White */
		colortable[2] = (COLOR_PAIR(0) | A_NORMAL);	/* Grey XXX */
		colortable[3] = (COLOR_PAIR(1) | A_BRIGHT);	/* Orange XXX */
		colortable[4] = (COLOR_PAIR(1) | A_NORMAL);	/* Red */
		colortable[5] = (COLOR_PAIR(2) | A_NORMAL);	/* Green */
		colortable[6] = (COLOR_PAIR(4) | A_NORMAL);	/* Blue */
		colortable[7] = (COLOR_PAIR(3) | A_NORMAL);	/* Umber */
		colortable[8] = (COLOR_PAIR(7) | A_BRIGHT);	/* Dark-grey XXX */
		colortable[9] = (COLOR_PAIR(0) | A_NORMAL);	/* Light-grey XXX */
		colortable[10] = (COLOR_PAIR(5) | A_NORMAL);	/* Purple */
		colortable[11] = (COLOR_PAIR(3) | A_BRIGHT);	/* Yellow */
		colortable[12] = (COLOR_PAIR(5) | A_BRIGHT);	/* Light Red XXX */
		colortable[13] = (COLOR_PAIR(2) | A_BRIGHT);	/* Light Green */
		colortable[14] = (COLOR_PAIR(4) | A_BRIGHT);	/* Light Blue */
		colortable[15] = (COLOR_PAIR(3) | A_NORMAL);	/* Light Umber XXX */

   }

#endif

#ifdef USE_SOUND
   /* Handle "arg_sound" */
   if (use_sound != arg_sound)
   {
      /* Initialize (if needed) */
      if (arg_sound && !init_sound())
      {
	 /* Warning */
	 plog("Cannot initialize sound!");

	 /* Cannot enable */
	 arg_sound = FALSE;
      }

      /* Change setting */
      use_sound = arg_sound;
   }
#endif

#ifdef USE_GRAPHICS

   /* Try graphics */
   if (arg_graphics)
   {
      /* if USE_NCURSES_ACS is defined, we can do something with graphics in curses! */
#ifdef USE_NCURSES_ACS
      use_graphics = TRUE;
#endif
   }

#endif /* USE_GRAPHICS */



   /*** Low level preparation ***/

#ifdef USE_GETCH

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

#endif

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

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


   /*** Now prepare the term(s) ***/
   for (i = 0; i < num_term; i++)
   {
      int rows, cols;
      int y, x;

      switch (i)
      {
	 /* Upper left */
	 case 0: rows = 24;
	    cols = 80;
	    y = x = 0;
	    break;
	 /* Lower left */
	 case 1: rows = LINES - 25;
	    cols = 80;
	    y = 24;
	    x = 0;
	    break;
	 /* Upper right */
	 case 2: rows = 24;
	    cols = COLS - 81;
	    y = 0;
	    x = 81;
	    break;
	 /* Lower right */
	 case 3: rows = LINES - 25;
	    cols = COLS - 81;
	    y = 24;
	    x = 81;
	    break;
	 /* XXX */
	 default: rows = cols = 0;
	     y = x = 0;
	     break;
      }

      /* No non-windows */
      if (rows <= 0 || cols <= 0) continue;

      /* Initialize */
      term_data_init(&data[next_win], rows, cols, y, x);

      /* Store */
      angband_term[next_win] = Term;

      next_win++;
   }

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

   /* Store */
   term_screen = &data[0].t;

   /* Success */
   return (0);
}
Exemplo n.º 15
0
wgetnstr_events(WINDOW *win,
		char *str,
		int maxlen,
		EVENTLIST_1st(_nc_eventlist * evl))
{
    SCREEN *sp = _nc_screen_of(win);
    TTY buf;
    bool oldnl, oldecho, oldraw, oldcbreak;
    char erasec;
    char killc;
    char *oldstr;
    int ch;
    int y, x;

    T((T_CALLED("wgetnstr(%p,%p, %d)"), win, str, maxlen));

    if (!win)
	returnCode(ERR);

    _nc_get_tty_mode(&buf);

    oldnl = sp->_nl;
    oldecho = sp->_echo;
    oldraw = sp->_raw;
    oldcbreak = sp->_cbreak;
    nl();
    noecho();
    noraw();
    cbreak();

    erasec = erasechar();
    killc = killchar();

    oldstr = str;
    getyx(win, y, x);

    if (is_wintouched(win) || (win->_flags & _HASMOVED))
	wrefresh(win);

    while ((ch = wgetch_events(win, evl)) != ERR) {
	/*
	 * Some terminals (the Wyse-50 is the most common) generate
	 * a \n from the down-arrow key.  With this logic, it's the
	 * user's choice whether to set kcud=\n for wgetch();
	 * terminating *getstr() with \n should work either way.
	 */
	if (ch == '\n'
	    || ch == '\r'
	    || ch == KEY_DOWN
	    || ch == KEY_ENTER) {
	    if (oldecho == TRUE
		&& win->_cury == win->_maxy
		&& win->_scroll)
		wechochar(win, (chtype) '\n');
	    break;
	}
#ifdef KEY_EVENT
	if (ch == KEY_EVENT)
	    break;
#endif
#ifdef KEY_RESIZE
	if (ch == KEY_RESIZE)
	    break;
#endif
	if (ch == erasec || ch == KEY_LEFT || ch == KEY_BACKSPACE) {
	    if (str > oldstr) {
		str = WipeOut(win, y, x, oldstr, str, oldecho);
	    }
	} else if (ch == killc) {
	    while (str > oldstr) {
		str = WipeOut(win, y, x, oldstr, str, oldecho);
	    }
	} else if (ch >= KEY_MIN
		   || (maxlen >= 0 && str - oldstr >= maxlen)) {
	    beep();
	} else {
	    *str++ = (char) ch;
	    if (oldecho == TRUE) {
		int oldy = win->_cury;
		if (waddch(win, (chtype) ch) == ERR) {
		    /*
		     * We can't really use the lower-right
		     * corner for input, since it'll mess
		     * up bookkeeping for erases.
		     */
		    win->_flags &= ~_WRAPPED;
		    waddch(win, (chtype) ' ');
		    str = WipeOut(win, y, x, oldstr, str, oldecho);
		    continue;
		} else if (win->_flags & _WRAPPED) {
		    /*
		     * If the last waddch forced a wrap &
		     * scroll, adjust our reference point
		     * for erasures.
		     */
		    if (win->_scroll
			&& oldy == win->_maxy
			&& win->_cury == win->_maxy) {
			if (--y <= 0) {
			    y = 0;
			}
		    }
		    win->_flags &= ~_WRAPPED;
		}
		wrefresh(win);
	    }
	}
    }

    win->_curx = 0;
    win->_flags &= ~_WRAPPED;
    if (win->_cury < win->_maxy)
	win->_cury++;
    wrefresh(win);

    /* Restore with a single I/O call, to fix minor asymmetry between
     * raw/noraw, etc.
     */
    sp->_nl = oldnl;
    sp->_echo = oldecho;
    sp->_raw = oldraw;
    sp->_cbreak = oldcbreak;

    _nc_set_tty_mode(&buf);

    *str = '\0';
    if (ch == ERR)
	returnCode(ch);

    T(("wgetnstr returns %s", _nc_visbuf(oldstr)));

#ifdef KEY_EVENT
    if (ch == KEY_EVENT)
	returnCode(ch);
#endif
#ifdef KEY_RESIZE
    if (ch == KEY_RESIZE)
	returnCode(ch);
#endif

    returnCode(OK);
}
Exemplo n.º 16
0
cell pp_curs_cbreak(cell x) {
	if (!Running) return UNSPECIFIC;
	cbreak();
	return UNSPECIFIC;
}
Exemplo n.º 17
0
int main(void)
{
        WINDOW *win1;
        int x, y, i, j, k;	// j, k not used yet.
	int xidx;
	float xmu[3500] = {}, xvar[3500] = {}, deltamu[3500] = {}, deltavar[3500] = {};
	float ymu[3500] = {}, yvar[3500] = {};
	int xrnd[3500] = {};
	int xused[3500] = {};
	int scnarr[35][100] = {};
	int slowness = 50;

        initscr();
        cbreak();               // Line buffering disabled
        keypad(stdscr, TRUE);   // allow softkeys
        noecho();               // don't display input when (w)getch();
	curs_set(0);		// don't display the cursor.
        getmaxyx(stdscr,y,x);

	srand((unsigned)(int)time(NULL));

        win1 = newwin(y,x,0,0);

	for (i=0; i<3500; i++) {	// i == xrnd[index]
		xrnd[i] = rand()%100;
	}				// end i.
	for (i=0; i<3500; i++) {				// i == xrnd[] index
		if (scnarr[0][xrnd[i]] == 1)
			break;
		for (j=34; j>=0; j--) {				// j == vertical scan index
			if (scnarr[j][xrnd[i]] != 1) {

/** */ 				for (k=0; k<=j; k++) {		// k == white drop space
					if (k>0)
						mvwprintw(win1,k-1,xrnd[i]," ");
					mvwprintw(win1,k,xrnd[i],"O");
					wrefresh(win1);
  // Enable This Line when running from localhost (not over ssh):	
  //					waitmics(slowness);
				}
/*  **/
				scnarr[j][xrnd[i]] = 1;
		break;
			}
		}
		xidx = i;
		ymu[i] = (float)i/100;
	}
	wgetch(win1);
	wclear(win1);
	/*
***********************************************************************************************
	*/
	wrefresh(win1);
	while (1) {
		k = wgetch(win1);
		if (k == 27) {				//clear BS input, keep good stuff
			k = wgetch(win1); //k == 91
			k = wgetch(win1); //k==50s+getch: pgup/pgdn; k==60s up/dn/l/r
			if (k/10 == 5) wgetch(win1); //ignore extra getch sent
		}

		if (k == 68) {				//if KEY_LEFT:
			wclear(win1);			//  print generated ballistic dep.
			for (i=0; i<100; i++) {
				for (j=34; j>=0; j--) {
					if (scnarr[j][i] == 1)	mvwprintw(win1, j, i, "O");
				}
			}
			wrefresh(win1);
 		} else if (k == 67) {			//if KEY_RIGHT
			wclear(win1);			// print statistics and graphs
			mvwprintw(win1, 10, 10," xidx= %d", xidx);
			mvwprintw(win1, 11, 10," ymu = %f", ymu[xidx]);
			mvwprintw(win1, 13, 10," ymu[0:1500](by 100's): ");
			for (i=0; i<15; i++) {
				mvwprintw(win1, 14, i*6, "%.2f", ymu[i*100]);
			}
			wrefresh(win1);

		} else if (k == 10) {			//if ENTER
		        delwin(win1);			//  end
			endwin();
			system("clear");
			break;
		}
	}
	return k;
	/*
***********************************************************************************************
	*/
	delwin(win1);
	endwin();
	system("clear");
        return 0;
}
Exemplo n.º 18
0
/**
 * @brief
 */
void Sv_InitConsole(void) {

	if (!dedicated->value) {
		return;
	}

#if defined(_WIN32)
	if (AllocConsole()) {
		freopen("CONIN$", "r", stdin);
		freopen("CONOUT$", "w", stdout);
		freopen("CONERR$", "w", stderr);
	} else {
		Com_Warn("Failed to allocate console: %u\n", (uint32_t) GetLastError());
	}
#endif

	memset(&sv_console_state, 0, sizeof(sv_console_state));

	sv_console_state.window = initscr();
	sv_console_state.dirty = true;

	cbreak();
	noecho();
	keypad(sv_console_state.window, TRUE);
	nodelay(sv_console_state.window, TRUE);
	curs_set(1);

	if (has_colors() == TRUE) {
		start_color();
		use_default_colors();
		init_pair(CON_COLOR_RED, COLOR_RED, -1);
		init_pair(CON_COLOR_GREEN, COLOR_GREEN, -1);
		init_pair(CON_COLOR_YELLOW, COLOR_YELLOW, -1);
		init_pair(CON_COLOR_BLUE, COLOR_BLUE, -1);
		init_pair(CON_COLOR_CYAN, COLOR_CYAN, -1);
		init_pair(CON_COLOR_MAGENTA, COLOR_MAGENTA, -1);
		init_pair(CON_COLOR_WHITE, COLOR_WHITE, -1);
	}

#ifdef SIGWINCH
	signal(SIGWINCH, Sv_ResizeConsole);
#endif

	memset(&sv_console, 0, sizeof(sv_console));

	sv_console.Append = Sv_Print;

	Con_AddConsole(&sv_console);

	if (dedicated->value) {
		file_t *file = Fs_OpenRead("history");
		if (file) {
			Con_ReadHistory(&sv_console, file);
			Fs_Close(file);
		} else {
			Com_Debug(DEBUG_SERVER, "Couldn't read history");
		}
	}

	Com_Print("Server console initialized\n");
}
Exemplo n.º 19
0
int teacher_menu(char *database){
	int i, c, n, choice = 0;
	teacher *xteacher;
	WINDOW *win;
	ITEM **items;
	MENU *menu;
	n = teacher_number(database);
	start_color();
	cbreak();
	noecho();
	keypad(stdscr, TRUE);
	xteacher = (teacher *)malloc(sizeof(teacher) * (n + 1));
	items = (ITEM **)calloc(n + 3, sizeof(ITEM *));
	for(i = 0; i < n; ++i) {
		xteacher[i] = get_teacher(database,i);
		items[i] = new_item(xteacher[i].name, NULL);
	}
	menu = new_menu((ITEM **)items);
	win = newwin(0, 0, 0, 0);
	int y,x;
	getmaxyx(win,y,x);
	keypad(win, TRUE);
	set_menu_win(menu, win);
	set_menu_sub(menu, derwin(win, y - 5, 38, 5, 0.4*x));
	set_menu_format(menu,x - 4, 1);
	set_menu_mark(menu, " * ");
	set_menu_spacing(menu, 0, 2, 0);
	box(win, 0, 0);
	print_in_middle(win, 1, 0, x, "Teachers" , COLOR_PAIR(1));
	mvwaddch(win, 2, 0, ACS_LTEE);
	mvwhline(win, 2, 1, ACS_HLINE, x - 2);
	mvwaddch(win, 2, x - 1, ACS_RTEE);
	mvwaddch(win, y - 3, 0, ACS_LTEE);
	mvwhline(win, y - 3, 1, ACS_HLINE, x - 2);
	mvwaddch(win, y - 3, x - 1, ACS_RTEE);
	refresh();
	if(n) {
		if(n > 1)
			mvwprintw(win,y - 2, 2,"N:New Teacher\t\tR:Remove Teacher\tS:Sort\t\tB:Back\tQ:Quit");
		else
			mvwprintw(win,y - 2, 2,"N:New Teacher\t\tR:Remove Teacher\tB:Back\tQ:Quit");
		for(i = 0; i < choice; i++)
			menu_driver(menu, REQ_DOWN_ITEM);
		post_menu(menu);
		wrefresh(win);
		while((c = wgetch(win))){
			switch(c) {
				case KEY_DOWN:
					menu_driver(menu, REQ_DOWN_ITEM);
					if(choice != n -1)
						choice++;
					break;
				case KEY_UP:
					menu_driver(menu, REQ_UP_ITEM);
					if(choice != 0)
						choice--;
					break;
				case 10: /* Enter */
					remove_menu(menu,items,n);
					return choice;
				case 'R':
				case 'r':
					remove_teacher(database, choice);
					remove_menu(menu,items,n);
					return -1;
				case 'B':
				case 'b':
					remove_menu(menu,items,n);
					return n + 1;
				case 'N':
				case 'n':
					remove_menu(menu,items,n);
					return n + 2;
				case 'Q':
				case 'q':
					remove_menu(menu,items,n);
					return INT_MIN;
				default:
					break;
			}
			wrefresh(win);
		}
	}
	else {
		mvwprintw(win,y - 2, 2,"N:New Teacher\t\tB:Back\t\tQ:Quit");
		mvwprintw(win,5,3*x/7,"No Teachers found :(\n");
		wrefresh(win);
		curs_set(0);
		while((c = wgetch(win)))
		{
			switch(c) {
				case 'n':
				case 'N':
					remove_menu(menu,items,n);
					curs_set(1);
					return n+2;
				case 'b':
				case 'B':
					remove_menu(menu,items,n);
					curs_set(1);
					return n+1;
				case 'Q':
				case 'q':
					remove_menu(menu,items,n);
					curs_set(1);
					return INT_MIN;
				default:
					break;
			}
			wrefresh(win);
		}
	}
	free(xteacher);
	return -1;
}
Exemplo n.º 20
0
int main(int argc, char **argv)
{
	int opt, optind = 0;
	int ch = ERR;

	struct option lopts[] = {
		{ "help",          no_argument,       NULL, 'h' },
		{ "version",       no_argument,       NULL, 'V' },
		{ "networks",      no_argument,       NULL, 'n' },
		{ "vbds",          no_argument,       NULL, 'x' },
		{ "repeat-header", no_argument,       NULL, 'r' },
		{ "vcpus",         no_argument,       NULL, 'v' },
		{ "delay",         required_argument, NULL, 'd' },
		{ "batch",	   no_argument,	      NULL, 'b' },
		{ "iterations",	   required_argument, NULL, 'i' },
		{ "full-name",     no_argument,       NULL, 'f' },
		{ 0, 0, 0, 0 },
	};
	const char *sopts = "hVnxrvd:bi:f";

	if (atexit(cleanup) != 0)
		fail("Failed to install cleanup handler.\n");

	while ((opt = getopt_long(argc, argv, sopts, lopts, &optind)) != -1) {
		switch (opt) {
		default:
			usage(argv[0]);
			exit(1);
		case '?':
		case 'h':
			usage(argv[0]);
			exit(0);
		case 'V':
			version();
			exit(0);
		case 'n':
			show_networks = 1;
			break;
		case 'x':
			show_vbds = 1;
			break;
		case 'r':
			repeat_header = 1;
			break;
		case 'v':
			show_vcpus = 1;
			break;
		case 'd':
			delay = atoi(optarg);
			break;
		case 'b':
			batch = 1;
			break;
		case 'i':
			iterations = atoi(optarg);
			loop = 0;
			break;
		case 'f':
			show_full_name = 1;
			break;
		case 't':
			show_tmem = 1;
			break;
		}
	}

	/* Get xenstat handle */
	xhandle = xenstat_init();
	if (xhandle == NULL)
		fail("Failed to initialize xenstat library\n");

	if (!batch) {
		/* Begin curses stuff */
		cwin = initscr();
		start_color();
		cbreak();
		noecho();
		nonl();
		keypad(stdscr, TRUE);
		halfdelay(5);
#ifndef __sun__
		use_default_colors();
#endif
		init_pair(1, -1, COLOR_YELLOW);

		do {
			gettimeofday(&curtime, NULL);
			if(ch != ERR || (curtime.tv_sec - oldtime.tv_sec) >= delay) {
				erase();
				top();
				oldtime = curtime;
				refresh();
				if ((!loop) && !(--iterations))
					break;
			}
			ch = getch();
		} while (handle_key(ch));
	} else {
		struct sigaction sa = {
			.sa_handler = signal_exit_handler,
			.sa_flags = 0
		};
		sigemptyset(&sa.sa_mask);
		sigaction(SIGINT, &sa, NULL);
		sigaction(SIGTERM, &sa, NULL);

		do {
			gettimeofday(&curtime, NULL);
			top();
			fflush(stdout);
			oldtime = curtime;
			if ((!loop) && !(--iterations))
				break;
			sleep(delay);
		} while (!signal_exit);
	}

	/* Cleanup occurs in cleanup(), so no work to do here. */

	return 0;
}
Exemplo n.º 21
0
Arquivo: snake.c Projeto: kahn04/snake
int main(int argc, char *argv[])
{
    int ch;

    initscr();
    start_color();
    cbreak();
    keypad(stdscr, TRUE);
    noecho();
    curs_set(0);
    init_pair(1, COLOR_CYAN, COLOR_BLACK);

    attron(COLOR_PAIR(1));
    //画边
    mvaddch(1, 0, '+');
    mvaddch(1, COLS-1, '+');
    mvaddch(LINES-1, COLS-1, '+');
    mvaddch(LINES-1, 0, '+');
    mvhline(1, 1, '-', COLS-1-1);
    mvhline(LINES-1, 1, '-', COLS-1-1);
    mvvline(2, 0, '|', LINES-2-1);
    mvvline(2, COLS-1, '|', LINES-2-1);

    refresh();
    attroff(COLOR_PAIR(1));

    // 来条蛇
    SNAKE snake;
    init_snake(&snake);
    draw_whole_snake(&snake);
    
    // 初始豆儿
    int *food;
    food = random_food(&snake);
    //mvaddch(food[1], food[0], '*');
    draw_food(food);

    int d;
    int i;
    now_time=0;
    while (1)
    {
        if(ioctl(0,FIONREAD,&i)<0)
        {
            printf("ioctl failed, error=%d\n ",errno);
            break;
        }
        if(!i)  // 小蛇自动跑部分
        {
            usleep(time_rate);
            now_time = now_time + time_rate;
            if (!(now_time < speed))
            {
                now_time = 0;
                if (snake_move(&snake, food))
                    break;
            }
            continue;
        }
        now_time = 0;
        ch = getch();
        if (ch < 258 || ch > 261)
            continue;
        if ( ch+snake.d != KEY_LEFT+KEY_UP )
        {
            d = ch - snake.d;
            if ( d == 1 || d == -1)
                continue;
        }
        snake.d = ch;

        if (snake_move(&snake, food))
            break;

    }
    getch();
    endwin();
    return 0;
}
Exemplo n.º 22
0
int main(int argc, char **argv) {
    init_buf();
    if (argc > 1)
        strncpy(file_name, argv[1], BUFSIZ);
    else
        strcpy(file_name, "untitled.txt");
    read_file(file_name);
    initscr();
    cbreak();
    noecho();
    if (has_colors()) {
        int white;
        start_color();
        if (COLORS > 255)
            white = 231;
        else if (COLORS > 87)
            white = 79;
        else
            white = 15;
        init_pair(1, white, 0);
        minibuf_attrs = COLOR_PAIR(1);
    } else {
        minibuf_attrs = A_BOLD;
    }

    while (TRUE) {
        int ch;
        // Redisplay
        drop_until(getmaxy(stdscr) / 2);
        print_queue();
        mbuf_display();
        refresh();

        // Wait for input
        switch ((ch = getch())) {
        case EOF:
        case '\x04': // ^D
            quit();
        case '\x08': // ^H
        case '\x7f': // DEL
            del_buf(buf.i - 1); break;
        case '\x17': // ^W
            del_buf(buf.wbeg); break;
        case '\x15': // ^U
            reset_buf("");
            break;
        case '\x1b': // ESC
            mbuf_msg("Press CTRL+D to quit");
            break;
        case '\r':
        case '\n':
            append_buf('\n');
            break;
        default:
            mbuf_msg(file_name);
            if (ch > '\x1f')
                append_buf(ch);
        }
    }
    return 0;
}
Exemplo n.º 23
0
static void
test_adds(int level)
{
    static bool first = TRUE;

    int ch;
    int limit;
    int row = 1;
    int col;
    int row2, col2;
    int length;
    char buffer[BUFSIZ];
    WINDOW *look = 0;
    WINDOW *work = 0;
    WINDOW *show = 0;
    int margin = (2 * MY_TABSIZE) - 1;
    Options option = (Options) ((unsigned) (m_opt
					    ? oMove
					    : oDefault)
				| (unsigned) ((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;

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

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

    doupdate();

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

    while ((ch = read_linedata(work)) != ERR && !isQUIT(ch)) {
	wmove(work, row, margin + 1);
	switch (ch) {
	case key_RECUR:
	    test_adds(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) {
				AddNStr(ChStr2(buffer + col), LEN(col));
			    }
			}
		    } else {
			if (move(row, col2) != ERR) {
			    AddStr(ChStr2(buffer));
			}
		    }
		    break;
		case oMove:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvAddNStr(row, col2, ChStr2(buffer + col), LEN(col));
			}
		    } else {
			MvAddStr(row, col2, ChStr2(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) {
				WAddNStr(work, ChStr2(buffer + col), LEN(col));
			    }
			}
		    } else {
			if (wmove(work, row, col2) != ERR) {
			    WAddStr(work, ChStr2(buffer));
			}
		    }
		    break;
		case oMoveWindow:
		    if (n_opt > 1) {
			for (col = 0; col < length; col += n_opt) {
			    col2 = ColOf(buffer, col, margin);
			    MvWAddNStr(work, row, col2, ChStr2(buffer + col),
				       LEN(col));
			}
		    } else {
			MvWAddStr(work, row, col2, ChStr2(buffer));
		    }
		    break;
		}

		/* do the corresponding single-character add */
		row2 = limit + row;
		for (col = 0; col < length; ++col) {
		    col2 = ColOf(buffer, col, margin);
		    switch (option) {
		    case oDefault:
			if (move(row2, col2) != ERR) {
			    AddCh(UChar(buffer[col]));
			}
			break;
		    case oMove:
			MvAddCh(row2, col2, UChar(buffer[col]));
			break;
		    case oWindow:
			if (wmove(work, row2, col2) != ERR) {
			    WAddCh(work, UChar(buffer[col]));
			}
			break;
		    case oMoveWindow:
			MvWAddCh(work, row2, col2, UChar(buffer[col]));
			break;
		    }
		}
	    } else {
		beep();
	    }
	    break;
	case KEY_BACKSPACE:
	    ch = '\b';
	    /* FALLTHRU */
	default:
	    if (ch <= 0 || ch > 255) {
		beep();
		break;
	    }
	    buffer[length++] = (char) 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) {
		    AddStr(ChStr2(buffer + length - 1));
		}
		break;
	    case oMove:
		MvAddStr(row, col, ChStr2(buffer + length - 1));
		break;
	    case oWindow:
		if (wmove(work, row, col) != ERR) {
		    WAddStr(work, ChStr2(buffer + length - 1));
		}
		break;
	    case oMoveWindow:
		MvWAddStr(work, row, col, ChStr2(buffer + length - 1));
		break;
	    }

	    /* do the corresponding single-character add */
	    switch (option) {
	    case oDefault:
		if (move(limit + row, col) != ERR) {
		    AddCh(UChar(ch));
		}
		break;
	    case oMove:
		MvAddCh(limit + row, col, UChar(ch));
		break;
	    case oWindow:
		if (wmove(work, limit + row, col) != ERR) {
		    WAddCh(work, UChar(ch));
		}
		break;
	    case oMoveWindow:
		MvWAddCh(work, limit + row, col, UChar(ch));
		break;
	    }

	    wnoutrefresh(work);

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

	    doupdate();
	    break;
	}
    }
    if (level > 0) {
	delwin(show);
	delwin(work);
	delwin(look);
    }
}
Exemplo n.º 24
0
void MapEditor()
{
	int key;
	clear();
	ShowEditorWindow();

	editing_terrain=FALSE;
	FillMap();
	editing_terrain=TRUE;
	FillMap();

	LoadLevel();
	ShowEditorMap();
	ShowEditorWindow();

	mouse_on(ALL_MOUSE_EVENTS);
	nodelay(stdscr,TRUE);
	cbreak();	

	for(;;)
	{
		key=getch(); 
		request_mouse_pos();
		if (mouse_active && (MOUSE_X_POS!=cursor_x || MOUSE_Y_POS!=cursor_y))
		{
			curs_set(0);
			EditorMoveCursor(MOUSE_X_POS,MOUSE_Y_POS);
			curs_set(2);
		}
		switch(key)
		{

		case KEY_F0+1:
			editing_terrain=TRUE;
			ShowEditorWindow();
			break;
		case KEY_F0+2:
			editing_terrain=FALSE;
			ShowEditorWindow();
			break;
		case KEY_F0+5:
			clear();
			PlayLevel();

			ClearAfterPlaying();
			ShowEditorWindow();

			mouse_on(ALL_MOUSE_EVENTS);
			nodelay(stdscr,TRUE);
			cbreak();	
			break;
		case KEY_F0+8:
			SaveLevel();
			break;
		case KEY_F0+9:
			LoadLevel();
			ShowEditorMap();
			ShowEditorWindow();
			break;
		case KEY_F0+12:
			FillMap();
			break;
		case KEY_MOVE_LEFT:
			EditorMoveCursor(cursor_x-1,cursor_y);
			break;
		case KEY_MOVE_RIGHT:
			EditorMoveCursor(cursor_x+1,cursor_y);
			break;
		case KEY_MOVE_UP:
			EditorMoveCursor(cursor_x,cursor_y-1);
			break;
		case KEY_MOVE_DOWN:
			EditorMoveCursor(cursor_x,cursor_y+1);
			break;
		case KEY_MOUSE:
		case KEY_ACTION:
			curs_set(0);
			EditorAction();
			move(cursor_y,cursor_x);
			curs_set(2);
		}
	}
}
Exemplo n.º 25
0
int main()
{	WINDOW *my_wins[3];
	PANEL  *my_panels[3];
	PANEL_DATA panel_datas[3];
	PANEL_DATA *temp;
	int ch;

	/* Initialize curses */
	initscr();
	start_color();
	cbreak();
	noecho();
	keypad(stdscr, TRUE);

	/* Initialize all the colors */
	init_pair(1, COLOR_RED, COLOR_BLACK);
	init_pair(2, COLOR_GREEN, COLOR_BLACK);
	init_pair(3, COLOR_BLUE, COLOR_BLACK);
	init_pair(4, COLOR_CYAN, COLOR_BLACK);

	init_wins(my_wins, 3);
	
	/* Attach a panel to each window */ 	/* Order is bottom up */
	my_panels[0] = new_panel(my_wins[0]); 	/* Push 0, order: stdscr-0 */
	my_panels[1] = new_panel(my_wins[1]); 	/* Push 1, order: stdscr-0-1 */
	my_panels[2] = new_panel(my_wins[2]); 	/* Push 2, order: stdscr-0-1-2 */

	/* Initialize panel datas saying that nothing is hidden */
	panel_datas[0].hide = FALSE;
	panel_datas[1].hide = FALSE;
	panel_datas[2].hide = FALSE;

	set_panel_userptr(my_panels[0], &panel_datas[0]);
	set_panel_userptr(my_panels[1], &panel_datas[1]);
	set_panel_userptr(my_panels[2], &panel_datas[2]);

	/* Update the stacking order. 2nd panel will be on top */
	update_panels();

	/* Show it on the screen */
	attron(COLOR_PAIR(4));
	mvprintw(LINES - 3, 0, "Show or Hide a window with 'a'(first window)  'b'(Second Window)  'c'(Third Window)");
	mvprintw(LINES - 2, 0, "F1 to Exit");

	attroff(COLOR_PAIR(4));
	doupdate();
	
	while((ch = getch()) != KEY_F(1))
	{	switch(ch)
		{	case 'a':			
				temp = (PANEL_DATA *)panel_userptr(my_panels[0]);
				if(temp->hide == FALSE)
				{	hide_panel(my_panels[0]);
					temp->hide = TRUE;
				}
				else
				{	show_panel(my_panels[0]);
					temp->hide = FALSE;
				}
				break;
			case 'b':
				temp = (PANEL_DATA *)panel_userptr(my_panels[1]);
				if(temp->hide == FALSE)
				{	hide_panel(my_panels[1]);
					temp->hide = TRUE;
				}
				else
				{	show_panel(my_panels[1]);
					temp->hide = FALSE;
				}
				break;
			case 'c':
				temp = (PANEL_DATA *)panel_userptr(my_panels[2]);
				if(temp->hide == FALSE)
				{	hide_panel(my_panels[2]);
					temp->hide = TRUE;
				}
				else
				{	show_panel(my_panels[2]);
					temp->hide = FALSE;
				}
				break;
		}
		update_panels();
		doupdate();
	}
	endwin();
	return 0;
}
Exemplo n.º 26
0
static int
test_opaque(int level, char **argv, WINDOW *stswin)
{
    WINDOW *txtbox = 0;
    WINDOW *txtwin = 0;
    FILE *fp;
    int ch;
    int txt_x = 0, txt_y = 0;
    int base_y;
    bool in_status = FALSE;
    int active = 0;

    if (argv[level] == 0) {
	beep();
	return FALSE;
    }

    if (level > 1) {
	txtbox = newwin(LINES - BASE_Y, COLS - level, BASE_Y, level);
	box(txtbox, 0, 0);
	wnoutrefresh(txtbox);

	txtwin = derwin(txtbox,
			getmaxy(txtbox) - 2,
			getmaxx(txtbox) - 2,
			1, 1);
	base_y = 0;
    } else {
	txtwin = stdscr;
	base_y = BASE_Y;
    }

    keypad(txtwin, TRUE);	/* enable keyboard mapping */
    (void) cbreak();		/* take input chars one at a time, no wait for \n */
    (void) noecho();		/* don't echo input */

    txt_y = base_y;
    txt_x = 0;
    wmove(txtwin, txt_y, txt_x);

    if ((fp = fopen(argv[level], "r")) != 0) {
	while ((ch = fgetc(fp)) != EOF) {
	    if (waddch(txtwin, UChar(ch)) != OK) {
		break;
	    }
	}
	fclose(fp);
    } else {
	wprintw(txtwin, "Cannot open:\n%s", argv[1]);
    }

    for (;;) {
	if (in_status) {
	    to_keyword(stswin, active);

	    ch = wgetch(stswin);
	    show_opaque(stswin, txtwin, TRUE, active);
	    if (Quit(ch))
		break;

	    switch (ch) {
	    case '\t':
		in_status = FALSE;
		break;
	    case KEY_DOWN:
	    case 'j':
		if (active < (int) SIZEOF(bool_funcs) - 1)
		    active++;
		else
		    beep();
		break;
	    case KEY_UP:
	    case 'k':
		if (active > 0)
		    active--;
		else
		    beep();
		break;
	    case ' ':
		bool_funcs[active].func(txtwin,
					!bool_funcs[active].func(txtwin, -1));
		break;
	    default:
		beep();
		break;
	    }
	    show_opaque(stswin, txtwin, FALSE, in_status ? active : -1);
	} else {
	    ch = mvwgetch(txtwin, txt_y, txt_x);
	    show_opaque(stswin, txtwin, TRUE, -1);
	    if (Quit(ch))
		break;

	    switch (ch) {
	    case '\t':
		in_status = TRUE;
		break;
	    case KEY_DOWN:
	    case 'j':
		if (txt_y < getmaxy(txtwin) - 1)
		    txt_y++;
		else
		    beep();
		break;
	    case KEY_UP:
	    case 'k':
		if (txt_y > base_y)
		    txt_y--;
		else
		    beep();
		break;
	    case KEY_LEFT:
	    case 'h':
		if (txt_x > 0)
		    txt_x--;
		else
		    beep();
		break;
	    case KEY_RIGHT:
	    case 'l':
		if (txt_x < getmaxx(txtwin) - 1)
		    txt_x++;
		else
		    beep();
		break;
	    case 'w':
		test_opaque(level + 1, argv, stswin);
		if (txtbox != 0) {
		    touchwin(txtbox);
		    wnoutrefresh(txtbox);
		} else {
		    touchwin(txtwin);
		    wnoutrefresh(txtwin);
		}
		break;
	    default:
		beep();
		napms(100);
		break;
	    }

	    show_opaque(stswin, txtwin, FALSE, -1);
	}
    }
    if (level > 1) {
	delwin(txtwin);
	delwin(txtbox);
    }
    return TRUE;
}
Exemplo n.º 27
0
int main(void)
{
        WINDOW *win1;
        int x, y, i, j, k, tmp;	// j, k not used yet.
	int ridx;
	float ymufin=0.0, ftemp = 0.0, deltamu = 0.0, deltavar = 0.0;
	float ymu[3500] = {}, yvar[3500] = {};
	int xrnd[3500] = {}, yhts[100] = {};
	int scnarr[35][100] = {};
	int slowness = 0;

        initscr();
        cbreak();               // Line buffering disabled
        keypad(stdscr, TRUE);   // allow softkeys
        noecho();               // don't display input when (w)getch();
	curs_set(0);		// don't display the cursor.
        getmaxyx(stdscr,y,x);

	srand((unsigned)(int)time(NULL));

	win1 = newwin(y,x,0,0);

	for (i=0; i<3500; i++) {				// xrnd[index]=rand(0:99)
		xrnd[i] = rand()%100;
	}
	for (i=0; i<3500; i++) {				// i == xrnd[] index
		ridx = i-1;
		tmp = xrnd[i];
		if (scnarr[0][xrnd[i]])
			break;
		for (j=0; j<35; j++) {
			if (j == 34) {
				yhts[xrnd[i]] = 1;
				scnarr[j][tmp] = 1;
 				for (k=0; k<35; k++) {
					if (k>0)	mvwprintw(win1,k-1,tmp," ");
					mvwaddch(win1,k,tmp,ACS_CKBOARD);
					wrefresh(win1);
  // Enable This Line when running from localhost (not over ssh):
  // 					waitmics(slowness);
				}
			}else if (
					((tmp>0)&&(scnarr[j][tmp-1]==1)) ||
					(scnarr[j+1][tmp]==1) ||
					((tmp<99)&&(scnarr[j][tmp+1]==1))
				) {
				yhts[tmp] = 1;
				scnarr[j][tmp] = 1;
 				for (k=0; k<=j; k++) {
					if (k>0)	mvwprintw(win1,k-1,tmp," ");
					mvwaddch(win1,k,tmp,ACS_CKBOARD);
					wrefresh(win1);
  // Enable This Line when running from localhost (not over ssh):
  //					waitmics(slowness);
				}
				break;
			}
		}
	}
	wrefresh(win1);

	ymufin = ((float)ridx)/100;	// final y_mu

	for (i=0; i<=ridx; i++) {
		yhts[xrnd[i]]++;
		if (i < 1) {
			ymu[0] = 0.0;
			yvar[0] = 0.0;
		} else {
			ymu[i] = (float)(i)/100;
			yvar[i] = 0;
			for (j=0; j<100; j++) {
				ftemp = ((float)yhts[j] - ymu[i]);	//(xi-mu)
				ftemp = ftemp * ftemp;		//(xi-mu)^2
				yvar[i] =yvar[i]+ftemp;		//sum of squares
			}
			yvar[i] = yvar[i]/100;			//variance (indexed)
		//deltavar[i] = 
		}
	}
	wgetch(win1);
	wclear(win1);
	/*
***********************************************************************************************
	*/
	wrefresh(win1);
	while (1) {
		k = wgetch(win1);
		if (k == 27) {				//clear BS input, keep good stuff
			k = wgetch(win1); //k == 91
			k = wgetch(win1); //k==50s+getch: pgup/pgdn; k==60s up/dn/l/r
			if (k/10 == 5) wgetch(win1); //ignore extra getch sent
		}

//if KEY_LEFT, print generatied ballistic deposition map
		if (k == 68) {
			wclear(win1);
/* deposition	*/	for (i=0; i<100; i++) {
/* map:		*/		for (j=34; j>=0; j--) {
					if (scnarr[j][i] == 1)	mvwaddch(win1,j,i,ACS_CKBOARD);

				}
			}
/* average	*/	if (ymufin-((int)ymufin) < .5) {
/* indicator:	*/		for (i=0; i<100; i++) {
					if (scnarr[35-(int)ymufin][i]==0)
						mvwaddch(win1,36-ymufin,i,ACS_HLINE);
					if (scnarr[35-(int)ymufin][i]==1)
						mvwaddch(win1,36-ymufin,i,ACS_CKBOARD);
				}
				mvwprintw(win1,1,2,"y_mu: %.2f", ymufin);
				mvwprintw(win1,2,2,"y_mu_remainder < .5");
				mvwprintw(win1,35-(int)ymufin,0,"[%d]", (int)ymufin);
			} else {
				for (i=0; i<100; i++) {
					if (scnarr[34-(int)ymufin][i]==0)
						mvwaddch(win1,35-ymufin,i,ACS_HLINE);
					if (scnarr[34-(int)ymufin][i]==1)
						mvwaddch(win1,35-ymufin,i,ACS_CKBOARD);
				}
				mvwprintw(win1,1,2,"y_mu: %f", ymufin);
				mvwprintw(win1,2,2,"y_mu_remainder >= .5");
				mvwprintw(win1,34-(int)ymufin,0,"[%d]", (int)ymufin+1);
			}
			wrefresh(win1);

//if KEY_RIGHT, print statistics and graphs:
 		} else if (k == 67) {
			wclear(win1);
			mvwprintw(win1, 0, 0," N=%d \twidth=100\tmu_final=%.3f"
				"\t\tvar_final=%.3f",ridx,ymu[ridx],yvar[ridx]);
			mvwprintw(win1, 1, 0,"\t\t\t\tdelta_mu=%.5f\tdelta_var=%.5f"
				,(ridx,ymu[ridx]/ridx),(yvar[ridx]/ridx));
			//mvwprintw(win1, 1, 25, "delta_var[%d]=%.3f", ridx,
			mvwprintw(win1, 3, 0," ymu[0:%d] (by 10%% bins):",ridx);
			mvwprintw(win1, 4, 0," yvar[0:%d] (by 10%% bins):",ridx);
			for (i=0; i<=10; i++) {
				ftemp = (float)ridx/10;
				mvwprintw(win1,34,i*9+3,"%02d%%",i*10);
				mvwprintw(win1,33-(int)ymu[(int)(i*ftemp)],i*9+2,"%.2f",
					ymu[(int)(i*ftemp)]);
				mvwprintw(win1,34-(int)ymu[(int)(i*ftemp)],i*9+2,"%.2f",
					yvar[(int)(i*ftemp)]);
			}
			wrefresh(win1);

//if KEY_UP, debug:
		} else if (k==65) {
			wclear(win1);
			mvwprintw(win1,0,0,"i:");
			mvwprintw(win1,7,0,"yhts[i]:\t(final)");
			mvwprintw(win1,14,0,"ymu[1:%d]:\t(ymu, %%-wise)",ridx);
			mvwprintw(win1,21,0,"yvar[0:%d]:\t(yvar, %%-wise)",ridx);
			for (i=0; i<100; i++){
				mvwprintw(win1,1+i/20,(i%20)*5," %2d",i);
				mvwprintw(win1,8+i/20,(i%20)*5," %2d",yhts[i]);
				mvwprintw(win1,15+i/20,(i%20)*5,"%4.1f",
					ymu[((i+1)*ridx)/100]);
				mvwprintw(win1,22+i/20,(i%20)*5,"%4.1f",
					yvar[((i+1)*ridx)/100]);
			}
			wrefresh(win1);


//if ENTER, end:
		} else if (k == 10) {
		        delwin(win1);
			endwin();
			system("clear");
			break;
		}
	}
	return k;
	/*
***********************************************************************************************
	*/
	delwin(win1);
	endwin();
	system("clear");
        return 0;
}
Exemplo n.º 28
0
int main(void)
{
  int ch, i;

  initscr();
  atexit(quit);
  clear();
  noecho();
  cbreak();
  keypad(stdscr, TRUE);
  start_color();

  init_pair(1, COLOR_YELLOW, COLOR_BLUE);
  init_pair(2, COLOR_BLACK, COLOR_WHITE);

  bkgd(COLOR_PAIR(1));

  fi = (FIELD **)calloc(4, sizeof(FIELD *));
  fi[0] = new_field(1, 10, 2, 3, 0, 0);
  fi[1] = new_field(1, 10, 2, 18, 0, 0);
  fi[2] = new_field(1, 15, 2, 33, 0, 0);
  fi[3] = 0;

  for(i=0; i<3; i++)
  {
    set_field_fore(fi[i], COLOR_PAIR(2));
    set_field_back(fi[i], COLOR_PAIR(2));
  }

  fo = new_form(fi);
  post_form(fo);        

  mvaddstr(2, 15, "+");
  mvaddstr(2, 30, "=");
  mvaddstr(5, 3, "Programm mittels F1-Funktionstaste beenden");

  refresh();
 
  while((ch=getch()) != KEY_F(1))
  {
    switch(ch)
    {
      case KEY_RIGHT:
      { 
        char str[20];
                                                        
        form_driver(fo, REQ_NEXT_FIELD);

        if(field_index(current_field(fo)) == 2)
        {
          snprintf(str, 20, "%s%s", field_buffer(fi[0], 0), field_buffer(fi[1], 0));
          set_field_buffer(fi[2], 0, str);
          refresh();
        }
        break;
      }
      case KEY_LEFT:
        form_driver(fo, REQ_PREV_FIELD);
        break;
      default: /* Feldeingabe */        
        form_driver(fo, ch);
    }
  }   
  return (0);  
}
Exemplo n.º 29
0
void ui_thread_func(thread_t *thread)
{
	
	mutex_init(&ui_mutex);
	
	initscr();
#if ALLOW_CONTROL_C
	cbreak();
#else
	raw();
#endif
	noecho();
	keypad(stdscr,TRUE);
	
	curs_set(0);

	getmaxyx(stdscr, screen_height, screen_width);
	
	uint8_t shutdown=false;
	do {
		
		ui_lock();
		
		shutdown=hasflag(ui_flags,UI_FLAG_SHUTDOWN);
		
		for (int ii=0;ii<uiblocks_count;ii++) {
			uiblock_t *uiblock=uiblocks[ii];
			mutex_lock(&uiblock->mutex);
			
			if (shutdown||hasflag(uiblock->flags,UIBLOCK_FLAG_DESTROY)) {
				wborder(uiblock->window, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
				wrefresh(uiblock->window);
				delwin(uiblock->window);
				mutex_destroy(&uiblock->mutex);
				free(uiblock);
				int iii=ii;
				while (iii<uiblocks_count-1) {
					uiblocks[iii]=uiblocks[iii+1];
					iii++;
				}
				uiblocks_count--;
				ii--;
				continue;
			}
			
			if (hasflag(uiblock->flags,UIBLOCK_FLAG_REALIGN)) {
				unsetflag(uiblock->flags,UIBLOCK_FLAG_REALIGN);
				
				box_t oldbox=uiblock->box;
				uiblock_event(UI_EVENT_REALIGN,uiblock);
				
				if (!box_equal(oldbox,uiblock->box)) {
					
					int16_t width=uiblock->box.bottomright.x-uiblock->box.topleft.x;
					int16_t height=uiblock->box.bottomright.y-uiblock->box.topleft.y;
					
					if (width<0)
						width=0;
					if (height<0)
						height=0;

					if (uiblock->window!=NULL) {
						//wborder(uiblock->window, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
						//wrefresh(uiblock->window);
						delwin(uiblock->window);
					}
					uiblock->window=newwin(height,width,uiblock->box.topleft.y,uiblock->box.topleft.x);

					scrollok(uiblock->window,TRUE);
					
					uiblock_redraw(uiblock);
				}

				uiblock_setflag_children(uiblock,UIBLOCK_FLAG_REALIGN);
			}
			
			if (hasflag(uiblock->flags,UIBLOCK_FLAG_REDRAW)) {
				unsetflag(uiblock->flags,UIBLOCK_FLAG_REDRAW);
				
				uiblock_event(UI_EVENT_REDRAW,uiblock);

				//wborder(uiblock->window, '|', '|', '-', '-', '+', '+', '+', '+');

				wrefresh(uiblock->window);

				uiblock_setflag_children(uiblock,UIBLOCK_FLAG_REDRAW);
			}
			
			mutex_unlock(&uiblock->mutex);
		}
		
		ui_unlock();
		
		
		pi_usleep(10000);
	} while (!shutdown);

	endwin();
	
	mutex_destroy(&ui_mutex);
}
Exemplo n.º 30
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_all_mods = false;

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    PATH_INFO::init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#ifdef USE_HOME_DIR
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standart_filenames();

    MAP_SHARING::setDefaults();

    // Process CLI arguments
    int saved_argc = --argc; // skip program name
    char **saved_argv = ++argv;

    while (argc) {
        if(std::string(argv[0]) == "--seed") {
            argc--;
            argv++;
            if(argc) {
                seed = djb2_hash((unsigned char *)argv[0]);
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--jsonverify") {
            argc--;
            argv++;
            verifyexit = true;
        } else if(std::string(argv[0]) == "--check-mods") {
            argc--;
            argv++;
            check_all_mods = true;
        } else if(std::string(argv[0]) == "--basepath") {
            argc--;
            argv++;
            if(argc) {
                PATH_INFO::init_base_path(std::string(argv[0]));
                PATH_INFO::set_standart_filenames();
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--userdir") {
            argc--;
            argv++;
            if (argc) {
                PATH_INFO::init_user_dir( argv[0] );
                PATH_INFO::set_standart_filenames();
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--username") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::setUsername(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--addadmin") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::addAdmin(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--adddebugger") {
            argc--;
            argv++;
            if (argc) {
                MAP_SHARING::addDebugger(std::string(argv[0]));
                argc--;
                argv++;
            }
        } else if(std::string(argv[0]) == "--shared") {
            argc--;
            argv++;
            MAP_SHARING::setSharing(true);
            MAP_SHARING::setCompetitive(true);
            MAP_SHARING::setWorldmenu(false);
        } else if(std::string(argv[0]) == "--competitive") {
            argc--;
            argv++;
            MAP_SHARING::setCompetitive(true);
        } else { // Skipping other options.
            argc--;
            argv++;
        }
    }
    while (saved_argc) {
        // All paths will decrement saved_argc and do not depend on it before this operation, so it is safe to do it in
        // just one place, avoiding repeated code.
        saved_argc--;
        if(std::string(saved_argv[0]) == "--worldmenu") {
            saved_argv++;
            MAP_SHARING::setWorldmenu(true);
        } else if(std::string(saved_argv[0]) == "--datadir") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("datadir", std::string(saved_argv[0]));
                PATH_INFO::update_datadir();
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--savedir") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("savedir", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--configdir") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("config_dir", std::string(saved_argv[0]));
                PATH_INFO::update_config_dir();
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--optionfile") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("options", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--keymapfile") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("keymap", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--autopickupfile") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("autopickup", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else if(std::string(saved_argv[0]) == "--motdfile") {
            saved_argv++;
            if(saved_argc) {
                PATH_INFO::update_pathname("motd", std::string(saved_argv[0]));
                saved_argc--;
                saved_argv++;
            }
        } else {
            // Unknown arguments are ignored.
            saved_argv++;
        }
    }

    setupDebug();
    // Options strings loaded with system locale
    initOptions();
    load_options();

    set_language(true);

    if (initscr() == NULL) { // Initialize ncurses
        DebugLog( D_ERROR, DC_ALL ) << "initscr failed!";
        return 1;
    }
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
            debugmsg("Can't open or create %s. Check permissions.",
                     FILENAMES["user_dir"].c_str());
            exit_handler(-999);
        }
        g->load_static_data();
        if (verifyexit) {
            if(g->game_error()) {
                exit_handler(-999);
            }
            exit_handler(0);
        }
        if (check_all_mods) {
            // Here we load all the mods and check their
            // consistency (both is done in check_all_mod_data).
            g->init_ui();
            popup_nowait("checking all mods");
            g->check_all_mod_data();
            if(g->game_error()) {
                exit_handler(-999);
            }
            // At this stage, the mods (and core game data)
            // are find and we could start playing, but this
            // is only for verifying that stage, so we exit.
            exit_handler(0);
        }
    } catch(std::string &error_message) {
        if(!error_message.empty()) {
            debugmsg("%s", error_message.c_str());
        }
        exit_handler(-999);
    }

    // Now we do the actual game.

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#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

    bool quit_game = false;
    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}