Exemple #1
0
void
initkbd()
{
    keypad(stdscr, TRUE);
    notimeout(stdscr,TRUE);
}
int main() {
	int key, menuitem, ent, id;
	menuitem = 0;
	initscr();
	drawmenu(menuitem);
	keypad(stdscr,TRUE);
	
	noecho();
	do {
		key = getch();
		switch(key) {
			case KEY_DOWN: menuitem++;
			if(menuitem > MENUMAX-1) 
				menuitem = 0;
			break;

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

			default: 
			break;

		}

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

}
Exemple #3
0
/*
 * Display a menu for choosing among a number of options
 */
int
dialog_menu (const char *title, const char *prompt, int height, int width,
		int menu_height, const char *current, int item_no,
		struct dialog_list_item ** items)
{
    int i, j, x, y, box_x, box_y;
    int key = 0, button = 0, scroll = 0, choice = 0, first_item = 0, max_choice;
    WINDOW *dialog, *menu;
    FILE *f;

    max_choice = MIN (menu_height, item_no);

    /* center dialog box on screen */
    x = (COLS - width) / 2;
    y = (LINES - height) / 2;

    draw_shadow (stdscr, y, x, height, width);

    dialog = newwin (height, width, y, x);
    keypad (dialog, TRUE);

    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);
    wattrset (dialog, border_attr);
    mvwaddch (dialog, height - 3, 0, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
	waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    wbkgdset (dialog, dialog_attr & A_COLOR);
    waddch (dialog, ACS_RTEE);

    if (title != NULL && strlen(title) >= width-2 ) {
	/* truncate long title -- mec */
	char * title2 = malloc(width-2+1);
	memcpy( title2, title, width-2 );
	title2[width-2] = '\0';
	title = title2;
    }

    if (title != NULL) {
	wattrset (dialog, title_attr);
	mvwaddch (dialog, 0, (width - strlen(title))/2 - 1, ' ');
	waddstr (dialog, (char *)title);
	waddch (dialog, ' ');
    }

    wattrset (dialog, dialog_attr);
    print_autowrap (dialog, prompt, width - 2, 1, 3);

    menu_width = width - 6;
    box_y = height - menu_height - 5;
    box_x = (width - menu_width) / 2 - 1;

    /* create new window for the menu */
    menu = subwin (dialog, menu_height, menu_width,
		y + box_y + 1, x + box_x + 1);
    keypad (menu, TRUE);

    /* draw a box around the menu items */
    draw_box (dialog, box_y, box_x, menu_height + 2, menu_width + 2,
	      menubox_border_attr, menubox_attr);

    /*
     * Find length of longest item in order to center menu.
     * Set 'choice' to default item. 
     */
    item_x = 0;
    for (i = 0; i < item_no; i++) {
	item_x = MAX (item_x, MIN(menu_width, strlen (items[i]->name) + 2));
	if (strcmp(current, items[i]->tag) == 0) choice = i;
    }

    item_x = (menu_width - item_x) / 2;

    /* get the scroll info from the temp file */
    if ( (f=fopen("lxdialog.scrltmp","r")) != NULL ) {
	if ( (fscanf(f,"%d\n",&scroll) == 1) && (scroll <= choice) &&
	     (scroll+max_choice > choice) && (scroll >= 0) &&
	     (scroll+max_choice <= item_no) ) {
	    first_item = scroll;
	    choice = choice - scroll;
	    fclose(f);
	} else {
	    scroll=0;
	    remove("lxdialog.scrltmp");
	    fclose(f);
	    f=NULL;
	}
    }
    if ( (choice >= max_choice) || (f==NULL && choice >= max_choice/2) ) {
	if (choice >= item_no-max_choice/2)
	    scroll = first_item = item_no-max_choice;
	else
	    scroll = first_item = choice - max_choice/2;
	choice = choice - scroll;
    }

    /* Print the menu */
    for (i=0; i < max_choice; i++) {
	print_item (menu, items[first_item + i]->name, i, i == choice,
                    (items[first_item + i]->tag[0] != ':'));
    }

    wnoutrefresh (menu);

    print_arrows(dialog, item_no, scroll,
		 box_y, box_x+item_x+1, menu_height);

    print_buttons (dialog, height, width, 0);
    wmove (menu, choice, item_x+1);
    wrefresh (menu);

    while (key != ESC) {
	key = wgetch(menu);

	if (key < 256 && isalpha(key)) key = tolower(key);

	if (strchr("ynm", key))
		i = max_choice;
	else {
        for (i = choice+1; i < max_choice; i++) {
		j = first_alpha(items[scroll + i]->name, "YyNnMm>");
		if (key == tolower(items[scroll + i]->name[j]))
                	break;
	}
	if (i == max_choice)
       		for (i = 0; i < max_choice; i++) {
			j = first_alpha(items[scroll + i]->name, "YyNnMm>");
			if (key == tolower(items[scroll + i]->name[j]))
                		break;
		}
	}

	if (i < max_choice || 
            key == KEY_UP || key == KEY_DOWN ||
            key == '-' || key == '+' ||
            key == KEY_PPAGE || key == KEY_NPAGE) {

            print_item (menu, items[scroll + choice]->name, choice, FALSE,
                       (items[scroll + choice]->tag[0] != ':'));

	    if (key == KEY_UP || key == '-') {
                if (choice < 2 && scroll) {
	            /* Scroll menu down */
                    scrollok (menu, TRUE);
                    wscrl (menu, -1);
                    scrollok (menu, FALSE);

                    scroll--;

                    print_item (menu, items[scroll]->name, 0, FALSE,
                               (items[scroll]->tag[0] != ':'));
		} else
		    choice = MAX(choice - 1, 0);

	    } else if (key == KEY_DOWN || key == '+')  {

		print_item (menu, items[scroll + choice]->name, choice, FALSE,
                                (items[scroll + choice]->tag[0] != ':'));

                if ((choice > max_choice-3) &&
                    (scroll + max_choice < item_no)
                   ) {
		    /* Scroll menu up */
		    scrollok (menu, TRUE);
                    scroll (menu);
                    scrollok (menu, FALSE);

                    scroll++;

                    print_item (menu, items[scroll + max_choice - 1]->name,
                               max_choice-1, FALSE,
                               (items[scroll + max_choice - 1]->tag[0] != ':'));
                } else
                    choice = MIN(choice+1, max_choice-1);

	    } else if (key == KEY_PPAGE) {
	        scrollok (menu, TRUE);
                for (i=0; (i < max_choice); i++) {
                    if (scroll > 0) {
                	wscrl (menu, -1);
                	scroll--;
                	print_item (menu, items[scroll]->name, 0, FALSE,
                	(items[scroll]->tag[0] != ':'));
                    } else {
                        if (choice > 0)
                            choice--;
                    }
                }
                scrollok (menu, FALSE);

            } else if (key == KEY_NPAGE) {
                for (i=0; (i < max_choice); i++) {
                    if (scroll+max_choice < item_no) {
			scrollok (menu, TRUE);
			scroll(menu);
			scrollok (menu, FALSE);
                	scroll++;
                	print_item (menu, items[scroll + max_choice - 1]->name,
			            max_choice-1, FALSE,
			            (items[scroll + max_choice - 1]->tag[0] != ':'));
		    } else {
			if (choice+1 < max_choice)
			    choice++;
		    }
                }

            } else
                choice = i;

            print_item (menu, items[scroll + choice]->name, choice, TRUE,
                       (items[scroll + choice]->tag[0] != ':'));

            print_arrows(dialog, item_no, scroll,
                         box_y, box_x+item_x+1, menu_height);

            wnoutrefresh (dialog);
            wrefresh (menu);

	    continue;		/* wait for another key press */
        }

	switch (key) {
	case KEY_LEFT:
	case TAB:
	case KEY_RIGHT:
	    button = ((key == KEY_LEFT ? --button : ++button) < 0)
			? 2 : (button > 2 ? 0 : button);

	    print_buttons(dialog, height, width, button);
	    wrefresh (menu);
	    break;
	case ' ':
	case 's':
	case 'y':
	case 'n':
	case 'm':
	    /* save scroll info */
	    if ( (f=fopen("lxdialog.scrltmp","w")) != NULL ) {
		fprintf(f,"%d\n",scroll);
		fclose(f);
	    }
	    delwin (dialog);
            items[scroll + choice]->selected = 1;
            switch (key) {
            case 's': return 3;
            case 'y': return 3;
            case 'n': return 4;
            case 'm': return 5;
            case ' ': return 6;
            }
	    return 0;
	case 'h':
	case '?':
	    button = 2;
	case '\n':
	    delwin (dialog);
	    items[scroll + choice]->selected = 1;

	    remove("lxdialog.scrltmp");
	    return button;
	case 'e':
	case 'x':
	    key = ESC;
	case ESC:
	    break;
	}
    }

    delwin (dialog);
    remove("lxdialog.scrltmp");
    return -1;			/* ESC pressed */
}
int window_sessions_list_run_command(gui_t* gui, int c)
{
	int busylines[MAX_SIPUA_LINES];
	int nbusy;

	ogmp_curses_t* ocui = gui->topui;

	ocui->sipua->lock_lines(ocui->sipua);
	nbusy = ocui->sipua->busylines(ocui->sipua, busylines, MAX_SIPUA_LINES);
	ocui->sipua->unlock_lines(ocui->sipua);

	curseson(); cbreak(); noecho(); nonl(); keypad(stdscr,TRUE);
	/*
	i = jcall_get_number_of_pending_calls();
	if (i<max) 
		max=i;
	*/
	switch (c)
    {
		sipua_set_t* call;

		case KEY_DOWN:
		{
			int n = 0;
			while(busylines[n] != calllist_line) n++;

			if(n+1==nbusy)
			{
				beep();
				break;
			}

			calllist_line = busylines[++n];
			break;
		}
		case KEY_UP:
		{
			int n = 0;
			while(busylines[n] != calllist_line) n++;

			if(n==0)
			{
				beep();
				break;
			}

			calllist_line = busylines[--n];
			break;
		}
		case 3:  /* Ctrl-C */
		{
			gui_hide_window(gui);

			break;
		}
		case 'c':
		{
			int n = 0;

			call = ocui->sipua->session(ocui->sipua);

			ocui->sipua->bye(ocui->sipua, call);
			
			while(busylines[n] != calllist_line) 
				n++;

			if(n > 0)
				calllist_line = busylines[--n];
			else
			{
				if(nbusy > 1)
					calllist_line = busylines[++n];
				else
					calllist_line = -1;
			}
/*
			eXosip_lock();
			i = eXosip_terminate_call(ca->cid, ca->did);
			if (i==0) jcall_remove(ca);
			eXosip_unlock();
*/
			gui->gui_print(gui, gui->parent);
			break;
		}
		case 'a':
		{
			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->answer(ocui->sipua, call, SIPUA_STATUS_ANSWER);
/*
			eXosip_lock();
			eXosip_answer_call(ca->did, 200, 0);
			eXosip_unlock();
*/
			break;
		}
		case 'r':
		{
			int n = 0;

			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->answer(ocui->sipua, call, SIPUA_STATUS_REJECT);

			while(busylines[n] != calllist_line) 
				n++;

			if(n > 0)
				calllist_line = busylines[--n];
			else
			{
				if(nbusy > 1)
					calllist_line = busylines[++n];
				else
					calllist_line = -1;
			}
/*
			eXosip_lock();
			i = eXosip_answer_call(ca->did, 480, 0);
			if (i==0) jcall_remove(ca);
			eXosip_unlock();
*/
			gui->gui_print(gui, gui->parent);
			break;
		}
		case 'd':
		{
			int n = 0;

			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->answer(ocui->sipua, call, SIPUA_STATUS_DECLINE);
			
			while(busylines[n] != calllist_line) 
				n++;

			if(n > 0)
				calllist_line = busylines[--n];
			else
			{
				if(nbusy > 1)
					calllist_line = busylines[++n];
				else
					calllist_line = -1;
			}
/*
			eXosip_lock();
			i = eXosip_answer_call(ca->did, 603, 0);
			if (i==0) jcall_remove(ca);
			eXosip_unlock();
*/
			gui->gui_print(gui, gui->parent);
			break;
		}
		case 'b':
		{
			int n = 0;

			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->answer(ocui->sipua, call, SIPUA_STATUS_BUSY);
			
			while(busylines[n] != calllist_line) 
				n++;

			if(n > 0)
				calllist_line = busylines[--n];
			else
			{
				if(nbusy > 1)
					calllist_line = busylines[++n];
				else
					calllist_line = -1;
			}
/*
			eXosip_lock();
			i = eXosip_answer_call(ca->did, 486, 0);
			if (i==0) jcall_remove(ca);
			eXosip_unlock();
*/
			gui->gui_print(gui, gui->parent);
			break;
		}
		case 'h':
		{
			call = ocui->sipua->session(ocui->sipua);

			calllist_line = ocui->sipua->hold(ocui->sipua, call);
/*
			eXosip_lock();
			eXosip_on_hold_call(ca->did);
			eXosip_unlock();
*/
			break;
		}
		case 'u':
		{
			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->answer(ocui->sipua, call, SIPUA_STATUS_ANSWER);
/*
			eXosip_lock();
			eXosip_off_hold_call(ca->did);
			eXosip_unlock();
*/
			break;
		}
		case 'o':
		{
			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			ocui->sipua->options_call(ocui->sipua, call);
/*
			eXosip_lock();
			eXosip_options_call(ca->did);
			eXosip_unlock();
*/
			break;
		}
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		case '#':
		case '*':
		{
			char dtmf_body[1000];

			call = ocui->sipua->pick(ocui->sipua, calllist_line);
			if (!call) 
			{ 
				beep(); 
				break; 
			}

			snprintf(dtmf_body, 999, "Signal=%c\r\nDuration=250\r\n", c);

			ocui->sipua->info_call(ocui->sipua, call, "application/dtmf-relay", dtmf_body);
/*
			eXosip_lock();
			eXosip_info_call(ca->did, "application/dtmf-relay", dtmf_body);
			eXosip_unlock();
*/
			break;
		}
		default:
			beep();
			return -1;
    }

	gui->gui_print(gui, gui->parent);

	return 0;
}
/* Enter in the tui mode (curses).
   When in normal mode, it installs the tui hooks in gdb, redirects
   the gdb output, configures the readline to work in tui mode.
   When in curses mode, it does nothing.  */
void
tui_enable (void)
{
  if (!tui_allowed_p ())
    error (_("TUI mode not allowed"));

  if (tui_active)
    return;

  /* To avoid to initialize curses when gdb starts, there is a defered
     curses initialization.  This initialization is made only once
     and the first time the curses mode is entered.  */
  if (tui_finish_init)
    {
      WINDOW *w;

      w = initscr ();
  
      cbreak ();
      noecho ();
      /* timeout (1); */
      nodelay(w, FALSE);
      nl();
      keypad (w, TRUE);
      rl_initialize ();
      tui_set_term_height_to (LINES);
      tui_set_term_width_to (COLS);
      def_prog_mode ();

      tui_show_frame_info (0);
      tui_set_layout (SRC_COMMAND, TUI_UNDEFINED_REGS);
      tui_set_win_focus_to (TUI_SRC_WIN);
      keypad (TUI_CMD_WIN->generic.handle, TRUE);
      wrefresh (TUI_CMD_WIN->generic.handle);
      tui_finish_init = 0;
    }
  else
    {
     /* Save the current gdb setting of the terminal.
        Curses will restore this state when endwin() is called.  */
     def_shell_mode ();
     clearok (stdscr, TRUE);
   }

  /* Install the TUI specific hooks.  */
  tui_install_hooks ();
  rl_startup_hook = tui_rl_startup_hook;

  tui_update_variables ();
  
  tui_setup_io (1);

  tui_active = 1;
  if (deprecated_safe_get_selected_frame ())
     tui_show_frame_info (deprecated_safe_get_selected_frame ());

  /* Restore TUI keymap.  */
  tui_set_key_mode (tui_current_key_mode);
  tui_refresh_all_win ();

  /* Update gdb's knowledge of its terminal.  */
  target_terminal_save_ours ();
  tui_update_gdb_sizes ();
}
Exemple #6
0
/*
 * This function creates a widget.
 */
CDKDSCALE *newCDKDScale (CDKSCREEN *cdkscreen,
			   int xplace,
			   int yplace,
			   char *title,
			   char *label,
			   chtype fieldAttr,
			   int fieldWidth,
			   double start,
			   double low,
			   double high,
			   double inc,
			   double fastInc,
			   int digits,
			   boolean Box,
			   boolean shadow)
{
   CDKDSCALE *widget	= 0;
   int parentWidth	= getmaxx(cdkscreen->window);
   int parentHeight	= getmaxy(cdkscreen->window);
   int boxHeight;
   int boxWidth;
   int horizontalAdjust, oldWidth;
   int xpos		= xplace;
   int ypos		= yplace;
   int x, junk;

   static const struct { int from; int to; } bindings[] = {
		{ 'u',		KEY_UP },
		{ 'U',		KEY_PPAGE },
		{ CDK_BACKCHAR,	KEY_PPAGE },
		{ CDK_FORCHAR,	KEY_NPAGE },
		{ 'g',		KEY_HOME },
		{ '^',		KEY_HOME },
		{ 'G',		KEY_END },
		{ '$',		KEY_END },
   };

   if ((widget = newCDKObject(CDKDSCALE, &my_funcs)) == 0)
      return (0);

   setCDKDScaleBox (widget, Box);

   boxHeight		= (BorderOf(widget) * 2) + 1;
   boxWidth		= fieldWidth + 2*BorderOf(widget);

   /* Set some basic values of the widget's data field. */
   widget->label	= 0;
   widget->labelLen	= 0;
   widget->labelWin	= 0;

  /*
   * If the fieldWidth is a negative value, the fieldWidth will
   * be COLS-fieldWidth, otherwise, the fieldWidth will be the
   * given width.
   */
   fieldWidth = setWidgetDimension (parentWidth, fieldWidth, 0);
   boxWidth = fieldWidth + 2*BorderOf(widget);

   /* Translate the label char *pointer to a chtype pointer. */
   if (label != 0)
   {
      widget->label	= char2Chtype (label, &widget->labelLen, &junk);
      boxWidth		= widget->labelLen + fieldWidth + 2;
   }

   oldWidth = boxWidth;
   boxWidth = setCdkTitle(ObjOf(widget), title, boxWidth);
   horizontalAdjust = (boxWidth - oldWidth) / 2;

   boxHeight += TitleLinesOf(widget);

  /*
   * Make sure we didn't extend beyond the dimensions of the window.
   */
   boxWidth = (boxWidth > parentWidth ? parentWidth : boxWidth);
   boxHeight = (boxHeight > parentHeight ? parentHeight : boxHeight);
   fieldWidth = (fieldWidth > (boxWidth - widget->labelLen - 2*BorderOf(widget))
   		 ? (boxWidth - widget->labelLen - 2*BorderOf(widget))
		 : fieldWidth);

   /* Rejustify the x and y positions if we need to. */
   alignxy (cdkscreen->window, &xpos, &ypos, boxWidth, boxHeight);

   /* Make the widget's window. */
   widget->win = newwin (boxHeight, boxWidth, ypos, xpos);

   /* Is the main window null??? */
   if (widget->win == 0)
   {
      destroyCDKObject(widget);
      return (0);
   }

   /* Create the widget's label window. */
   if (widget->label != 0)
   {
      widget->labelWin = subwin (widget->win,
				 1, widget->labelLen,
				 ypos + TitleLinesOf(widget) + BorderOf(widget),
				 xpos + horizontalAdjust + BorderOf(widget));
      if (widget->labelWin == 0)
      {
	 destroyCDKObject(widget);
	 return (0);
      }
   }

   /* Create the widget's data field window. */
   widget->fieldWin = subwin (widget->win,
			      1, fieldWidth,
			      ypos + TitleLinesOf(widget) + BorderOf(widget),
			      xpos + widget->labelLen + horizontalAdjust + BorderOf(widget));
   if (widget->fieldWin == 0)
   {
      destroyCDKObject(widget);
      return (0);
   }
   keypad (widget->fieldWin, TRUE);
   keypad (widget->win, TRUE);

   /* Create the widget's data field. */
   ScreenOf(widget)		= cdkscreen;
   widget->parent		= cdkscreen->window;
   widget->shadowWin		= 0;
   widget->boxWidth		= boxWidth;
   widget->boxHeight		= boxHeight;
   widget->fieldWidth		= fieldWidth;
   widget->fieldAttr		= (chtype)fieldAttr;
   widget->current		= low;
   widget->low			= low;
   widget->high			= high;
   widget->current		= start;
   widget->inc			= inc;
   widget->fastinc		= fastInc;
   widget->digits		= digits;
   initExitType(widget);
   ObjOf(widget)->acceptsFocus	= TRUE;
   ObjOf(widget)->inputWindow	= widget->win;
   widget->shadow		= shadow;

   /* Do we want a shadow??? */
   if (shadow)
   {
      widget->shadowWin = newwin (boxHeight, boxWidth, ypos + 1, xpos + 1);
      if (widget->shadowWin == 0)
      {
	 destroyCDKObject(widget);
	 return (0);
      }
   }

   /* Setup the key bindings. */
   for (x = 0; x < (int) SIZEOF(bindings); ++x)
      bindCDKObject (vDSCALE, widget, bindings[x].from, getcCDKBind, (void *)(long)bindings[x].to);

   registerCDKObject (cdkscreen, vDSCALE, widget);

   return (widget);
}
Exemple #7
0
int main(int argc, char *argv[])
{
    RedditUserLogged *user = NULL;
    char *subreddit = NULL;
    char *password = NULL, *username = NULL;
    optParser parser;

    DEBUG_START(DEBUG_FILE, DEBUG_FILENAME);

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

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

    optAddOptions (&parser, mainOptions, MOPT_ARG_COUNT);

    handleArguments(&parser);

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

    optClearParser(&parser);

    setlocale(LC_CTYPE, "");


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

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

    /* Start libreddit */
    redditGlobalInit();

    globalState = redditStateNew();

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

    redditStateSet(globalState);

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

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

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

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

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

    DEBUG_END(DEBUG_FILE);
    return 0;
}
Exemple #8
0
int main(int argc, char *argv[])
{
  if( !UP3D_Open() )
    return -1;

  signal(SIGINT, sigfinish);   // set sigint handler
#ifdef SIGWINCH
  signal(SIGWINCH, sigwinch);  // set sigint handler
#endif

  initscr();                   // initialize the curses library
  raw();                       // line buffering disabled
  keypad(stdscr, TRUE);        // enable keyboard mapping
  nonl();                      // tell curses not to do NL->CR/NL on output
  cbreak();                    // take input chars one at a time, no wait for \n
  noecho();                    // getch no echo
  nodelay(stdscr, TRUE);       // getch nonblocking
  curs_set(0);                 // no visible cursor
  
  if( has_colors() )
  {
    start_color();
    use_default_colors();
    init_pair(1, -1, -1);
    init_pair(2, COLOR_RED,     -1);
    init_pair(3, COLOR_GREEN,   -1);
    init_pair(4, COLOR_YELLOW,  -1);
    init_pair(5, COLOR_BLUE,    -1);
    init_pair(6, COLOR_CYAN,    -1);
    init_pair(7, COLOR_MAGENTA, -1);
    init_pair(8, COLOR_WHITE,   COLOR_BLACK);

    bkgd(COLOR_PAIR(1));
  }

  //initial draw
  update_state(true);

  //the loop
  for(;;)
  {
    int c = getch();

    switch( c )
    {
      case 0x12: update_state(true); break; // CTRL-R

      case 'p':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_Power(&blk,true);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
         UP3D_SetParameter(0x94,999); //set best accuracy for reporting position
       }
       break;
      case 'q':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_Power(&blk,false);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
         sigfinish(0);
       }
       break;

      case '0':
       {
         UP3D_ClearProgramBuf();
         UP3D_InsertRomProgram(0);
         UP3D_StartResumeProgram();
       }
       break;

      case 'b':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_Beeper(&blk,true);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Pause(&blk,100);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Beeper(&blk,false);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Pause(&blk,100);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Beeper(&blk,true);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Pause(&blk,100);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Beeper(&blk,false);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case 'h':
       {
         UP3D_BLK blk;
         UP3D_BLK blksHome[2];
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_Z ); UP3D_WriteBlocks(blksHome,2);
         UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_Y ); UP3D_WriteBlocks(blksHome,2);
         UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_X ); UP3D_WriteBlocks(blksHome,2);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '1':
       {
         UP3D_BLK blk;
         UP3D_BLK blksMoveF[2];
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_MoveF( blksMoveF,-150,-60.0,-150,60.0,0,0,0,0);
         UP3D_WriteBlocks(blksMoveF,2);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '2':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '3':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
UP3D_PROG_BLK_MoveL(&blk,21,23809,-7,0,0,-495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,-10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,-10403,0,0,495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,7,0,0,495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,10403,0,0,-495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '4':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
/*        
UP3D_PROG_BLK_MoveL(&blk,21,23809,-7,0,0,-495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,-10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
//UP3D_PROG_BLK_MoveL(&blk,21,23809,-10403,0,0,495,0,0);UP3D_WriteBlock(&blk);
//UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,-10403+24,0,0,495,0,0);UP3D_WriteBlock(&blk);
*/
UP3D_PROG_BLK_MoveL(&blk,21,23809,5,0,0,-495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,-10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,-10391,0,0,495,0,0);UP3D_WriteBlock(&blk);

         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '5':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();
/*
UP3D_PROG_BLK_MoveL(&blk,21,23809,7,0,0,495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
//UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
//UP3D_PROG_BLK_MoveL(&blk,21,23809,10403,0,0,-495,0,0);UP3D_WriteBlock(&blk);
//UP3D_PROG_BLK_MoveL(&blk,1,100,512,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,10403+48,0,0,-495,0,0);UP3D_WriteBlock(&blk);
*/
UP3D_PROG_BLK_MoveL(&blk,21,23809,19,0,0,495,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,1581,24984,10924,0,0,0,0,0);UP3D_WriteBlock(&blk);
UP3D_PROG_BLK_MoveL(&blk,21,23809,10440,0,0,-495,0,0);UP3D_WriteBlock(&blk);

         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '6':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();

         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '7':
       {
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();

         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
         UP3D_StartResumeProgram();
       }
       break;

      case '8':
       {
/*
         UP3D_BLK blk;
         UP3D_ClearProgramBuf();

  UP3D_UseSDProgramBuf( 3, true );
  
  UP3D_BLK blksHome[2];
  UP3D_ClearProgramBuf();
  UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_Z ); UP3D_WriteBlocks(blksHome,2);
  UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_Y ); UP3D_WriteBlocks(blksHome,2);
  UP3D_PROG_BLK_Home( blksHome, UP3DAXIS_X ); UP3D_WriteBlocks(blksHome,2);

  UP3D_BLK blks[2];
  UP3D_PROG_BLK_MoveF( blks,-1000,0,-1000,0,-1000,-100,-1000,0);
  UP3D_WriteBlocks(blks,2);
  
         UP3D_PROG_BLK_Stop(&blk);UP3D_WriteBlock(&blk);
*/

         UP3D_ClearProgramBuf();
         UP3D_UseSDProgramBuf( 3, false );
         UP3D_StartResumeProgram();
       }
       break;

      case '9':
       {
         UP3D_BLK blk;
         UP3D_SetPrintJobInfo( 9, 0, 0 );
         UP3D_ClearProgramBuf();
         UP3D_UseSDProgramBuf( 9, true );

         UP3D_PROG_BLK_Power(&blk,true);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_SetParameter(&blk,PARA_BED_TEMP,100);UP3D_WriteBlock(&blk);
         UP3D_PROG_BLK_SetParameter(&blk,PARA_HEATER_BED_ON,1);UP3D_WriteBlock(&blk);

         UP3D_BLK sblk[3];
         UP3D_PROG_BLK_Stop(&sblk[0]);
         UP3D_PROG_BLK_Stop(&sblk[1]);
         UP3D_PROG_BLK_Stop(&sblk[2]);
         UP3D_WriteBlocks(sblk,3);
         UP3D_WriteBlocks(sblk,3);

         UP3D_SetPrintJobInfo( 9, 1, 0 );

         UP3D_UseSDProgramBuf( 9, false );
         UP3D_ClearProgramBuf();
//         UP3D_StartResumeProgram();
       }
       break;


      case 'a':
       UP3D_SetParameter(0x94,99); //set smaller accuracy
       break;


      case 't':
       UP3D_SetParameter(0x39,65);  //NOZZLE1 SET TEMP
       UP3D_SetParameter(0x3A,65);  //NOZZLE2 SET TEMP
       UP3D_SetParameter(0x3B,102); //BED SET TEMP
       UP3D_SetParameter(0x3C,101); //TEMP4 SET TEMP 
       break;

      case 's':
       UP3D_SetParameter(0x10,2);
       break;

      case 'x':
       UP3D_SetParameter(0x14,0); //NOZZLE1 OFF
       UP3D_SetParameter(0x15,0); //NOZZLE1 OFF
       UP3D_SetParameter(0x16,0); //BED OFF
       break;
 
      case 'n':
       UP3D_SetParameter(0x14,1); //NOZZLE1 ON
       break;
      case 'm':
       UP3D_SetParameter(0x16,1); //BED ON
       break;

    }

    update_state(false);

    napms(20);
  }

  sigfinish(0);
  return 0;
}
Exemple #9
0
int main(int argc, char** argv)
{
	int i = 0, params_valid = 1;
	char c, *udp_addr;
	gametable* game = NULL;
	
	int udp_sockfd,n, udp_port;
	struct sockaddr_in udp_servaddr,cliaddr;
	char sendline[1000];
	char recvline[1000];
	
	for(i = 0; i < argc; i++) {
		if(strcmp(argv[i], "-h") == 0) {
			if(i + 1 <= argc) {
				udp_addr = argv[++i];
			}
		} else if(strcmp(argv[i], "-u") == 0) {
			if(i + 1 <= argc) {
				udp_port = atoi(argv[++i]);
			}
		} /*else if(strcmp(argv[i], "-t") == 0) {
			if(i + 1 <= argc) {
				param_tcpport = argv[++i];
			}
		} */
	}
    
    if(udp_addr == NULL) {
        printf("hostname's not set, use -h <hostname> to set one\n");
        params_valid = 0;
    }
    
    if(udp_port == NULL) {
        printf("udp port's not set, use -u <port> to set one\n");
        params_valid = 0;
    }
    /*
    if(param_tcpport == NULL) {
        printf("tcp port's not set, use -t <port> to set one\n");
        params_valid = 0;
    }*/
    
    if(!params_valid) {
        printf("Couldn't run server due to mis-configuration. Quitting.\n");
        return 1;
    }
	
	initscr();
	intrflush(stdscr, FALSE); // Prevent interrupt flush
	keypad(stdscr,TRUE);
	timeout(0);
	
	start_color();
	init_pair(1, COLOR_RED, COLOR_BLACK);
	init_pair(2, COLOR_YELLOW, COLOR_BLACK);
	init_pair(3, COLOR_GREEN, COLOR_BLACK);
	init_pair(4, COLOR_BLUE, COLOR_BLACK);
	
	// client
	udp_sockfd=socket(AF_INET,SOCK_DGRAM,0);

	int flags = fcntl(udp_sockfd, F_GETFL);
	flags |= O_NONBLOCK;
	fcntl(udp_sockfd, F_SETFL, flags);
	
	bzero(&udp_servaddr,sizeof(udp_servaddr));
	udp_servaddr.sin_family = AF_INET;
	udp_servaddr.sin_addr.s_addr=inet_addr(udp_addr);
	udp_servaddr.sin_port=htons(udp_port);

	//printw("%s %d", udp_addr, udp_port);
	printw("Commands: /join, /ready, /area, /place <column>, /chat <message>, /quit\n");
	
	char c_input[100], c_input_copy[100];
	
	while (1) {
		sleep(0.01);
		
		// try receiving packet from server
		struct connect_four_packet_common * packet_recv = recvline;
    
        n=recvfrom(udp_sockfd,packet_recv,10000,0,NULL,NULL);
        recvline[n]=0;

        if (n > 2)
		{
			//printw("Got packet code %lu\n", packet_recv->msg_code);
			// parse packet
			switch(packet_recv->msg_code)
			{
				case 1000:
					printw(" %s\n", ((struct connect_four_packet_error *)packet_recv)->message);
					break;
				case 1:
					printw("Game joined. Type /ready when you're ready.\n");
					break;
				case 3:
					{
						struct connect_four_packet_start * packet_start = packet_recv;
						game = newGame(packet_start->column_count, packet_start->row_count);
						printw("Game started. %d players, game size %dx%d.\n", packet_start->player_count, game->width, game->height);
					}
					break;
				case 4:
					printw("Your turn. Select column with /place <number>\n");
					break;
				case 6:
				{
					struct connect_four_packet_area * packet_area = packet_recv;
					printw("%s", packet_area->area);
					strcpy(game->array, packet_area->area);
					drawTable(game);
					break;
				}
				case 7:
					printw("Player %d won!\n", ((struct connect_four_packet_winner *)packet_recv)->winner_id);
					printw("Type /join for a new game.\n");
					break;
				case 11:
					printw("%d: %s\n",((struct connect_four_packet_chat_server *)packet_recv)->player_id, ((struct connect_four_packet_chat_server *)packet_recv)->msg);
					break;
				case 20:
				{
					struct connect_four_packet_pong *packet_pong = malloc(sizeof(struct connect_four_packet_pong));
					packet_pong->msg_code = 21;
					sendto(udp_sockfd, packet_pong, sizeof(*packet_pong), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
					free(packet_pong);
				}
			}
		}
		// if there's input, deactivate non-blocking input and read a line
		c = getch();
		if (c == ERR)
			continue;
		else 
			timeout(-1);
		getstr(c_input);
		//printw("%s\n", c_input);
		timeout(0);
		strcpy(c_input_copy, c_input);
		
		char *command = strtok(c_input_copy, " ");
		
		// parse commands, assign message codes based on them and send a packet
		if (strcmp(command, "quit") == 0)
		{
			struct connect_four_packet_quit *packet_quit = malloc(sizeof(struct connect_four_packet_quit));
			packet_quit->msg_code = 8;
			sendto(udp_sockfd, packet_quit, sizeof(*packet_quit), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
			free(packet_quit);
			break;
		}
		else if (strcmp(command, "join") == 0)
		{
			struct connect_four_packet_join *packet_join = malloc(sizeof(struct connect_four_packet_join));
			packet_join->msg_code = 0;
			sendto(udp_sockfd, packet_join, sizeof(*packet_join), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
			free(packet_join);
		}
		else if (strcmp(command, "ready") == 0)
		{
			struct connect_four_packet_ready *packet_ready = malloc(sizeof(struct connect_four_packet_ready));
			packet_ready->msg_code = 2;
			sendto(udp_sockfd, packet_ready, sizeof(*packet_ready), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
			free(packet_ready);
		}
		else if (strcmp(command, "place") == 0)
		{
			struct connect_four_packet_column *packet_column = malloc(sizeof(struct connect_four_packet_column));
			packet_column->msg_code = 5;
			packet_column->selected_column = atoi(strtok(NULL, " "));
			sendto(udp_sockfd, packet_column, sizeof(*packet_column), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
			free(packet_column);
		}
		else if (strcmp(command, "chat") == 0)
		{
			char* text = c_input;
			text = text + 5;
			
			struct connect_four_packet_chat_client *packet_chat_client = malloc(sizeof(struct connect_four_packet_chat_client));
			packet_chat_client->msg_code = 10;
			strcpy(packet_chat_client->msg, text);
			packet_chat_client->length = strlen(text);
			sendto(udp_sockfd, packet_chat_client, sizeof(*packet_chat_client), 0,  (struct sockaddr *)&udp_servaddr, sizeof(udp_servaddr));
			free(packet_chat_client);
		}
	}
	endwin();
}
void list_tracks()
{
    FILE *tracks_fp;
    char entry[MAX_ENTRY];
    int cat_length;
    int lines_op = 0;
    WINDOW *track_pad_ptr;
    int tracks = 0;
    int key;
    int first_line = 0;

    if (current_cd[0] == '\0') {
        mvprintw(ERROR_LINE, 0, "You must select a CD first.");
        get_return();
        return;
    }
    clear_all_screen();
    cat_length = strlen(current_cat);

    /* First count the number of tracks for the current CD */
    tracks_fp = fopen(TRACKS_FILE, "r");
    if (!tracks_fp) {
        return;
    }
    while (fgets(entry, MAX_ENTRY, tracks_fp)) {
        if (strncmp(current_cat, entry, cat_length) == 0) {
            tracks++;
        }
    }
    fclose(tracks_fp);

    /* Make a new pad, ensure that even if there is only a single
       track the PAD is large enough so the later prefresh() is always valid  */
    track_pad_ptr = newpad(tracks + 1 + BOXED_LINES, BOXED_ROWS + 1);
    if (!track_pad_ptr)
	return;

    tracks_fp = fopen(TRACKS_FILE, "r");
    if (!tracks_fp)
	return;

    mvprintw(4, 0, "CD Track Listing\n");

    /* write the track information into the pad */
    while (fgets(entry, MAX_ENTRY, tracks_fp)) {
        /* Compare catalog number and output rest of entry */
        if (strncmp(current_cat, entry, cat_length) == 0) {
            mvwprintw(track_pad_ptr, lines_op++, 0, "%s", entry + cat_length + 1);
        }
    }
    fclose(tracks_fp);

    if (lines_op > BOXED_LINES) {
        mvprintw(MESSAGE_LINE, 0, "Cursor keys to scroll, RETURN or q to exit");
    } else {
        mvprintw(MESSAGE_LINE, 0, "RETURN or q to exit");
    }
    wrefresh(stdscr);
    keypad(stdscr, TRUE);
    cbreak();
    noecho();
    key = 0;
    while (key != 'q' && key != KEY_ENTER && key != '\n') {
        if (key == KEY_UP) {
            if (first_line > 0) {
                first_line--;
            }
        }
        if (key == KEY_DOWN) {
            if (first_line + BOXED_LINES + 1 < tracks) {
                first_line++;
            }
        }
        /* now draw the appropriate part of the pad on the screen */
        prefresh(track_pad_ptr, first_line, 0,
                 BOX_LINE_POS, BOX_ROW_POS,
                 BOX_LINE_POS + BOXED_LINES, BOX_ROW_POS + BOXED_ROWS);
        key = getch();
    }

    delwin(track_pad_ptr);
    keypad(stdscr, FALSE);
    nocbreak();
    echo();
}
Exemple #11
0
/* Begin the curses subsystem. It sets up the keyboard, puts everything in
   raw mode, and attempts to set up our colors. This function is safe to
   call multiple times. */
void start_ui( void )
{
    /* Set up the window if we haven't done so already. */
    if ( wnd == NULL )
        wnd = initscr();
    
    keypad(stdscr, TRUE);           /* Set up keyboard macros. */
    cbreak();                       /* Set input to 'raw' mode. */
    noecho();                       /* Disable key echo. */
    nonl();                         /* Disable the translated newline. */
    scrollok(stdscr, FALSE);        /* No scrolling! */
    curs_set(0);                    /* No cursor. */
    leaveok(stdscr, TRUE);          /* Cursor doesn't matter. */
    timeout(0);                     /* No waiting for input. */
    
    /* Color setup. */
    if ( has_colors() )
    {
        int c1, c2, i, j, n;    /*< Counters. */
        start_color();
        
        c1 = COLOR_BLACK;
        c2 = COLOR_BLACK;
        n = 0;
        
        /* Set up all of the color pairs. In order to ensure colors do not
           change across platforms, we force OUR color values. */
        for (i = 0; i < 8; i++)
        {
            switch (i)
            {
                case 0: c1 = COLOR_BLACK; break;
                case 1: c1 = COLOR_RED; break;
                case 2: c1 = COLOR_YELLOW; break;
                case 3: c1 = COLOR_GREEN; break;
                case 4: c1 = COLOR_CYAN; break;
                case 5: c1 = COLOR_BLUE; break;
                case 6: c1 = COLOR_MAGENTA; break;
                case 7: c1 = COLOR_WHITE; break;
            }
            
            for (j = 0; j < 8; j++)
            {
                switch (j)
                {
                    case 0: c2 = COLOR_BLACK; break;
                    case 1: c2 = COLOR_RED; break;
                    case 2: c2 = COLOR_YELLOW; break;
                    case 3: c2 = COLOR_GREEN; break;
                    case 4: c2 = COLOR_CYAN; break;
                    case 5: c2 = COLOR_BLUE; break;
                    case 6: c2 = COLOR_MAGENTA; break;
                    case 7: c2 = COLOR_WHITE; break;
                }
                
                n++;
                init_pair( n, c1, c2 );
            }

        }
        
        colors = 1;
    }
    
    /* We've done everything! Now clear the screen and move on. */
    reset_color();
    clear();
    refresh();
}
static void
show_panels(PANEL * px[MAX_PANELS + 1])
{
    static const char *help[] =
    {
	"",
	"Commands are letter/digit pairs.  Digits are the panel number.",
	"",
	"  b - put the panel on the bottom of the stack",
	"  c - create the panel",
	"  d - delete the panel",
	"  h - hide the panel",
	"  m - move the panel (M for continuous move)",
	"  r - resize the panel",
	"  s - show the panel",
	"  b - put the panel on the top of the stack"
    };

    struct {
	bool valid;
	bool hidden;
	PANEL *above;
	PANEL *below;
    } table[MAX_PANELS + 1];

    WINDOW *win;
    PANEL *pan;
    int j;

    memset(table, 0, sizeof(table));
    for (j = 1; j <= MAX_PANELS; ++j) {
	table[j].valid = (px[j] != 0);
	if (table[j].valid) {
	    table[j].hidden = panel_hidden(px[j]);
	    table[j].above = panel_above(px[j]);
	    table[j].below = panel_below(px[j]);
	}
    }

    if ((win = newwin(LINES - 1, COLS, 0, 0)) != 0) {
	keypad(win, TRUE);
	if ((pan = new_panel(win)) != 0) {
	    werase(win);
	    MvWPrintw(win, 0, 0, "Panels:\n");
	    for (j = 1; j <= MAX_PANELS; ++j) {
		if (table[j].valid) {
		    wprintw(win, " %d:", j);
		    if (table[j].hidden) {
			waddstr(win, " hidden");
		    } else {
			if (table[j].above) {
			    wprintw(win, " above %d",
				    which_panel(px, table[j].above));
			}
			if (table[j].below) {
			    wprintw(win, "%s below %d",
				    table[j].above ? "," : "",
				    which_panel(px, table[j].below));
			}
		    }
		    waddch(win, '\n');
		}
	    }
	    for (j = 0; j < (int) SIZEOF(help); ++j) {
		if (wprintw(win, "%s\n", help[j]) == ERR)
		    break;
	    }
	    wgetch(win);
	    del_panel(pan);
	    pflush();
	}
	delwin(win);
    }
}
Exemple #13
0
void
resetkbd()
{
    keypad(stdscr, FALSE);
    notimeout(stdscr, FALSE);
}
Exemple #14
0
void
kbd_again()
{
    keypad(stdscr, TRUE);
    notimeout(stdscr,TRUE);
}
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, ftmp2 = 0.0, deltamu = 0.0, deltavar = 0.0, yvarmax = 0.0;
	float ymu[3500] = {}, yvar[3500] = {};
	int xrnd[3500] = {}, yhts[100] = {};
	int scnarr[35][100] = {};
	int slowness = 1000;

        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) {
				scnarr[j][tmp] = 1;

				yhts[tmp] = 1;
				yvar[i] = 0;
				for (k=0; k<100; k++) {
					ymu[i] = ymu[i]+(float)yhts[k]/100;	//ymu[i]
				}
				ymufin = ymu[i];
				for (k=0; k<100; k++) {
					ftemp = ((float)yhts[k] - ymufin);	//(xi-mu)
					ftemp = ftemp * ftemp;		//(xi-mu)^2
					yvar[i] =yvar[i]+ftemp;		//sum of squares
				}
				yvar[i] = yvar[i]/100;			//variance (indexed)
				if (yvar[i] > yvarmax)
					yvarmax = yvar[i];

 				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))
				) {
				scnarr[j][tmp] = 1;

				yhts[tmp] = 35-j;
				yvar[i] = 0;
				for (k=0; k<100; k++) {
					ymu[i] = ymu[i]+(float)yhts[k]/100;
				}
				ymufin = ymu[i];
				for (k = 0; k<100; k++) {
					ftemp = ((float)yhts[k] - ymufin);	//(xi-mu)
					ftemp = ftemp*ftemp;		//(xi-mu)^2
					yvar[i] = yvar[i] + ftemp;	//sum of squares
				}
				yvar[i] = yvar[i]/100;			//variance (indexed)
				if (yvar[i] > yvarmax)
					yvarmax = yvar[i];

 				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);

	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);

				}
			}
/* top value	*/	for (i=0; i<100; i++) {
				mvwaddch(win1,35-yhts[i],i,ACS_HLINE);
			}
/* 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);
    /*  headers */	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, 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 = 35*(int)ymu[(int)(i*ridx/10)]/ymu[ridx];
				ftmp2 = 35*(int)yvar[(int)(i*ridx/10)]/yvarmax;
    /*  graph ymu[t]    */	mvwprintw(win1,33-ftemp,i*9+2,"%.2f",ymu[(int)(i*ridx/10)]);
				wattron(win1,A_STANDOUT);
    /*  graph yvar[y]   */	mvwprintw(win1,34-ftmp2,i*9+2,"%.2f",yvar[(int)(i*ridx/10)]);
				wattroff(win1,A_STANDOUT);
    /*  plot x axis(%)  */ 	mvwprintw(win1,34,i*9+3,"%02d%%",i*10);
			}
			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;
}
Exemple #16
0
int main()
{
	int ch, done;
	ITEM *cur;
	
	/* coreboot data structures */
	lib_get_sysinfo();

	struct cb_cmos_option_table *opttbl = get_system_option_table();

	if (opttbl == NULL) {
		printf("Could not find coreboot option table\n");
		halt();
	}

	/* display initialization */
	initscr();
	keypad(stdscr, TRUE);
	cbreak();
	noecho();
	start_color();
	leaveok(stdscr, TRUE);
	curs_set(1);

	erase();
	box(stdscr, 0, 0);
	mvaddstr(0, 2, "coreboot configuration utility");

	/* prep CMOS layout into libcurses data structures */
	
	/* determine number of options, and maximum option name length */
	int numopts=0;
	int maxlength=0;
	struct cb_cmos_entries *option = first_cmos_entry(opttbl);
	while (option) {
		if ((option->config != 'r') && (strcmp("check_sum", option->name) != 0)) {
			maxlength = max(maxlength, strlen(option->name));
			numopts++;
		}
		option = next_cmos_entry(option);
	}
	if (numopts == 0) {
		printf("NO CMOS OPTIONS FOUND. EXITING!!!");
		return 1;
	}
	FIELD **fields = malloc(sizeof(FIELD*)*(2*numopts+1));
	int i;

	/* walk over options, fetch details */
	option = first_cmos_entry(opttbl);
	for (i=0;i<numopts;i++) {
		while ((option->config == 'r') || (strcmp("check_sum", option->name) == 0)) {
			option = next_cmos_entry(option);
		}
		fields[2*i] = new_field(1, strlen(option->name), i*2, 1, 0, 0);
		set_field_buffer(fields[2*i], 0, option->name);
		field_opts_off(fields[2*i], O_ACTIVE);

		fields[2*i+1] = new_field(1, 40, i*2, maxlength+2, 0, 0);
		char *buf = NULL;
		int fail = get_option_as_string(use_nvram, opttbl, &buf, option->name);
		switch (option->config) {
		case 'h': {
			set_field_type(fields[2*i+1], TYPE_INTEGER, 0, 0, (1<<option->length)-1);
			field_opts_on(fields[2*i+1], O_BLANK);
			break;
			  }
		case 's': {
			set_max_field(fields[2*i+1], option->length/8);
			field_opts_off(fields[2*i+1], O_STATIC);
			break;
			  }
		case 'e': {
			int numvals = 0;
			struct cb_cmos_enums *cmos_enum = first_cmos_enum_of_id(opttbl, option->config_id);

			/* if invalid data in CMOS, set buf to first enum */
			if (fail && cmos_enum) {
				buf = cmos_enum->text;
			}

			while (cmos_enum) {
				numvals++;
				cmos_enum = next_cmos_enum_of_id(cmos_enum, option->config_id);
			}

			char **values = malloc(sizeof(char*)*numvals + 1);
			int cnt = 0;

			cmos_enum = first_cmos_enum_of_id(opttbl, option->config_id);
			while (cmos_enum) {
				values[cnt] = cmos_enum->text;
				cnt++;
				cmos_enum = next_cmos_enum_of_id(cmos_enum, option->config_id);
			}
			values[cnt] = NULL;
			field_opts_off(fields[2*i+1], O_EDIT);
			set_field_type(fields[2*i+1], TYPE_ENUM, values, 1, 1);
			free(values); // copied by set_field_type
			break;
			  }
		default:
			  break;
		}
		if (buf) set_field_buffer(fields[2*i+1], 0, buf);
#if HOSTED
// underline is non-trivial on VGA text
		set_field_back(fields[2*i+1], A_UNDERLINE);
#endif
		field_opts_off(fields[2*i+1], O_BLANK | O_AUTOSKIP | O_NULLOK);

		option = next_cmos_entry(option);
	}
	fields[2*numopts]=NULL;

	FORM *form = new_form(fields);
	int numlines = min(numopts*2, 16);
	WINDOW *w = newwin(numlines+2, 70, 2, 1);
	WINDOW *inner_w = newpad(numopts*2, 68);
	box(w, 0, 0);
	mvwaddstr(w, 0, 2, "Press F1 when done");
	set_form_win(form, w);
	set_form_sub(form, inner_w);
	post_form(form);

	done = 0;
	while(!done) {
		ch=getch();
		if (ch == ERR) continue;
		switch (ch) {
		case KEY_DOWN:
			form_driver(form, REQ_NEXT_FIELD);
			break;
		case KEY_UP:
			form_driver(form, REQ_PREV_FIELD);
			break;
		case KEY_LEFT:
			if (field_type(current_field(form)) == TYPE_ENUM) {
				form_driver(form, REQ_PREV_CHOICE);
			} else {
				form_driver(form, REQ_LEFT_CHAR);
			}
			break;
		case KEY_RIGHT:
			if (field_type(current_field(form)) == TYPE_ENUM) {
				form_driver(form, REQ_NEXT_CHOICE);
			} else {
				form_driver(form, REQ_RIGHT_CHAR);
			}
			break;
		case KEY_BACKSPACE:
		case '\b':
			form_driver(form, REQ_DEL_PREV);
			break;
		case KEY_DC:
			form_driver(form, REQ_DEL_CHAR);
			break;
		case KEY_F(1):
			done=1;
			break;
		default:
			form_driver(form, ch);
			break;
		}
		render_form(form);
	}

	for (i = 0; i < numopts; i++) {
		char *name = field_buffer(fields[2*i], 0);
		char *value = field_buffer(fields[2*i+1], 0);
		char *ptr;
		for (ptr = value + strlen (value) - 1;
		     ptr >= value && *ptr == ' '; ptr--);
		ptr[1] = '\0';
		set_option_from_string(use_nvram, opttbl, value, name);
	}

	unpost_form(form);
	free_form(form);
	touchwin(stdscr);
	refresh();

	endwin();
	/* TODO: reboot */
	halt();
}
Exemple #17
0
int Util::help()
{
	FILE* fp = fopen("README.txt", "r");
	
	if(!fp)
	{
		fprintf(stderr, "README.txt not found\n");
		return -1;
	}
		
	const int buf_size = 80;

	char buf[buf_size];

	// skip lines before user manual
	while(1)
	{
		fgets(buf, buf_size, fp);
		if(*buf=='/' && *(buf+1)=='/')
			break;
	}
	
	// ncurses stuff
	initscr();
	start_color();
	raw();
	noecho();
	curs_set(0);
	keypad(stdscr, TRUE);
	
	int r = 0, c = 0;
	char buffer[255][80];
	while(fgets(buffer[r++], 80, fp));
	fclose(fp);

	int rmax = r;

	int from = 0;

	while(1)
	{
		clear();

		char tmp[80];
		char *p;

		for (r=0; r<22; r++)
		{
			p = tmp;

			for (c=0; c<80; c++)
			{
				if ('\t'==buffer[from+r][c])
				{
					sprintf(p, "    ");
					p+=4;
				}
				else *p++ = buffer[from+r][c];
			}
			mvprintw(r, 0, "%s", tmp);
		}

		int color;
		init_pair(color = 9, COLOR_GREEN, COLOR_BLACK);

		attron(COLOR_PAIR(color));

		mvprintw(24-1, 0, 
		"Use arrow keys to scroll up and down. Press Q to quit.");

		attroff(COLOR_PAIR(color));

		refresh();

		int ch = getch();
		if (ch=='Q' || ch=='q') break;
		if (ch==KEY_DOWN) 
			if (from+22<rmax) 
				from++;
		if (ch==KEY_UP)   
			if (from>0)
				from--;
	}
		
	endwin();

	return 0;
}
Exemple #18
0
int main(int argc, char *argv[])
{
    struct vrmr_ctx vctx;

    int retval = 0, optch = 0;

    static char optstring[] = "c:d:hVW";
    struct option long_options[] = {
            {"configfile", required_argument, NULL, 'c'},
            {"debug", required_argument, NULL, 'd'},
            {"help", no_argument, NULL, 'h'},
            {"version", no_argument, NULL, 'V'},
            {"wizard", no_argument, NULL, 'W'},
            {0, 0, 0, 0},
    };
    int longopt_index = 0;

    int debug_level = NONE;
    PANEL *main_panels[5];
    char *s = NULL;

    /* some defaults */
    vuurmuur_semid = -1;
    vuurmuur_shmid = -1;
    vuurmuurlog_semid = -1;
    vuurmuurlog_shmid = -1;

    /* create the version string */
    snprintf(version_string, sizeof(version_string),
            "%s (using libvuurmuur %s)", VUURMUURCONF_VERSION,
            libvuurmuur_get_version());

    /* some initilization */
    if (vrmr_init(&vctx, "vuurmuur_conf") < 0)
        exit(EXIT_FAILURE);

    /* settings file */
    memset(vccnf.configfile_location, 0, sizeof(vccnf.configfile_location));
    if (vctx.conf.etcdir[0] == '\0')
        (void)strlcpy(vccnf.configfile_location, VUURMUURCONF_CONFIGFILE,
                sizeof(vccnf.configfile_location));
    else
        (void)snprintf(vccnf.configfile_location,
                sizeof(vccnf.configfile_location),
                "%s/vuurmuur/vuurmuur_conf.conf", vctx.conf.etcdir);

#ifdef ENABLE_NLS
    setlocale(LC_ALL, "");
    setlocale(LC_TIME, "");
    setlocale(LC_MESSAGES, "");
    setlocale(LC_COLLATE, "");
    setlocale(LC_CTYPE, "");
    setlocale(LC_MONETARY, "");
    setlocale(LC_NUMERIC, "");
#endif

    /* check if we are in utf-8 mode */
    utf8_mode = 0;

    if ((s = getenv("LC_ALL")) || (s = getenv("LC_CTYPE")) ||
            (s = getenv("LANG"))) {
        if (strstr(s, "UTF-8"))
            utf8_mode = 1;
    }

#ifdef ENABLE_NLS
    bindtextdomain("vuurmuur", xstr(VRMR_LOCALEDIR));
    textdomain("vuurmuur");
#endif

    /* process commandline options */
    while ((optch = getopt_long(argc, argv, optstring, long_options,
                    &longopt_index)) != -1) {
        switch (optch) {
            case 'h':
                print_commandline_args();
                break;

            /* configfile */
            case 'c':

                if (strlcpy(vctx.conf.configfile, optarg,
                            sizeof(vctx.conf.configfile)) >=
                        sizeof(vctx.conf.configfile)) {
                    vrmr_error(EXIT_FAILURE, VR_ERR,
                            gettext("commandline argument too long for option "
                                    "-c."));
                    exit(EXIT_FAILURE);
                }
                break;

            case 'd':

                /* convert the debug string and check the result */
                debug_level = atoi(optarg);
                if (debug_level < 0 || debug_level > HIGH) {
                    vrmr_error(EXIT_FAILURE, VR_ERR,
                            gettext("commandline debuglevel out of range."));
                    exit(EXIT_FAILURE);
                }
                vrmr_debug_level = debug_level;

                fprintf(stdout, "vuurmuur_conf: debugging enabled.\n");
                fprintf(stdout, "vuurmuur_conf: debug level: %d\n",
                        debug_level);
                break;

            case 'V':
                /* print version */
                fprintf(stdout, "Vuurmuur_conf %s\n", version_string);
                fprintf(stdout, "%s\n", VUURMUUR_COPYRIGHT);

                exit(EXIT_SUCCESS);

            case 'W': {
                char wizard_path[512] = "";
                snprintf(wizard_path, sizeof(wizard_path),
                        "%s/scripts/vuurmuur-wizard.sh", vctx.conf.datadir);
                printf("Running %s...\n", wizard_path);
                exec_wizard(wizard_path);
                exit(EXIT_SUCCESS);
            }
            default:

                vrmr_error(EXIT_FAILURE, VR_ERR,
                        gettext("unknown commandline option."));
                exit(EXIT_FAILURE);
        }
    }

    /*  close the STDERR_FILENO because it gives us annoying "Broken
        Pipe" errors on some systems with bash3. Let's see if this
        has negative side-effects. */
    close(STDERR_FILENO);

    /* init vuurmuur_conf config already to get background */
    (void)init_vcconfig(&vctx.conf, vccnf.configfile_location, &vccnf);

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

    setup_colors();

    /* create the three main windows */
    if (!(status_frame_win = create_newwin(
                  3, COLS, LINES - 3, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(status_win = create_newwin(
                  1, COLS - 4, LINES - 2, 2, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(top_win = create_newwin(3, COLS, 0, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(main_win = create_newwin(
                  LINES - 6, COLS, 3, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(mainlog_win = newwin(LINES - 8, COLS - 2, 4, 1)))
        exit(EXIT_FAILURE);

    (void)wbkgd(mainlog_win, vccnf.color_bgd);

    wattron(status_frame_win, vccnf.color_bgd);
    mvwprintw(status_frame_win, 0, 2, " %s ", gettext("Status"));
    mvwprintw(status_frame_win, 2,
            (int)(COLS - 4 - StrLen(vctx.user_data.realusername) - 6),
            " user: %s ", vctx.user_data.realusername);
    wattroff(status_frame_win, vccnf.color_bgd);

    /* Attach a panel to each window */
    main_panels[0] = new_panel(top_win);
    main_panels[1] = new_panel(main_win);
    main_panels[2] = new_panel(status_win);
    main_panels[3] = new_panel(mainlog_win);
    main_panels[4] = new_panel(status_frame_win);

    (void)update_panels();
    (void)doupdate();

    /* init the vrprint functions for the Gui */
    vrprint.error = vuumuurconf_print_error;
    vrprint.warning = vuumuurconf_print_warning;
    vrprint.info = vuumuurconf_print_info;

    if (status_print(status_win, gettext("This is Vuurmuur_conf %s, %s"),
                version_string, VUURMUUR_COPYRIGHT) < 0)
        exit(EXIT_FAILURE);

    /* setup the global busywin */
    VrBusyWinCreate();
    VrBusyWinHide();

    // form_test();

    /* startup_screen inits the config, loads the zones, rules, etc */
    if (startup_screen(&vctx, &vctx.rules, &vctx.zones, &vctx.services,
                &vctx.interfaces, &vctx.blocklist, &vctx.reg) < 0) {
        /* failure! Lets quit. */

        /* delete panels and windows */
        (void)del_panel(main_panels[0]);
        (void)del_panel(main_panels[1]);
        (void)del_panel(main_panels[2]);
        (void)del_panel(main_panels[3]);
        (void)del_panel(main_panels[4]);
        (void)destroy_win(top_win);
        (void)destroy_win(main_win);
        (void)destroy_win(status_win);
        (void)destroy_win(status_frame_win);
        /* clear screen */
        (void)refresh();
        /* end ncurses mode */
        (void)endwin();

        exit(EXIT_FAILURE);
    }

    /* setup statuslist */
    (void)setup_statuslist();

    status_print(status_win, STR_READY);

    mm_status_checkall(&vctx, NULL, &vctx.rules, &vctx.zones, &vctx.interfaces,
            &vctx.services);
    /* main menu loop */
    while (main_menu(&vctx, &vctx.rules, &vctx.zones, &vctx.interfaces,
                   &vctx.services, &vctx.blocklist, &vctx.reg) == 1)
        ;
    /* clean up the status list */
    vrmr_list_cleanup(&vuurmuur_status.StatusList);

    /* detach from shared memory, if we were attached */
    if (vuurmuur_shmp != NULL && vuurmuur_shmp != (char *)(-1) &&
            vuurmuur_shmtable != 0) {
        if (vrmr_lock(vuurmuur_semid)) {
            vuurmuur_shmtable->configtool.connected = 3;
            vrmr_unlock(vuurmuur_semid);
        }
        (void)shmdt(vuurmuur_shmp);
    }
    if (vuurmuurlog_shmp != NULL && vuurmuurlog_shmp != (char *)(-1) &&
            vuurmuurlog_shmtable != 0) {
        if (vrmr_lock(vuurmuurlog_semid)) {
            vuurmuurlog_shmtable->configtool.connected = 3;
            vrmr_unlock(vuurmuurlog_semid);
        }
        (void)shmdt(vuurmuurlog_shmp);
    }

    /* destroy the global busywin */
    VrBusyWinDelete();

    /* delete panels and windows */
    (void)del_panel(main_panels[0]);
    (void)del_panel(main_panels[1]);
    (void)del_panel(main_panels[2]);
    (void)del_panel(main_panels[3]);
    (void)del_panel(main_panels[4]);

    (void)destroy_win(mainlog_win);
    (void)destroy_win(top_win);
    (void)destroy_win(main_win);
    (void)destroy_win(status_win);
    (void)destroy_win(status_frame_win);
    /* clear screen */
    (void)refresh();

    /* end ncurses mode */
    (void)endwin();

    /* set error functions to the stdout versions */
    vrprint.error = vrmr_stdoutprint_error;
    vrprint.warning = vrmr_stdoutprint_warning;
    vrprint.info = vrmr_stdoutprint_info;
    vrprint.debug = vrmr_stdoutprint_debug;
    vrprint.audit = vrmr_stdoutprint_audit;

    /* unload the backends */
    if (vrmr_backends_unload(&vctx.conf, &vctx) < 0) {
        vrmr_error(-1, VR_ERR, gettext("unloading the backends failed"));
        retval = -1;
    }

    /* cleanup the datastructures */
    (void)vrmr_list_cleanup(&vctx.blocklist.list);
    (void)vrmr_destroy_serviceslist(&vctx.services);
    (void)vrmr_destroy_zonedatalist(&vctx.zones);
    (void)vrmr_rules_cleanup_list(&vctx.rules);
    (void)vrmr_destroy_interfaceslist(&vctx.interfaces);
    vrmr_deinit(&vctx);
    return (retval);
}
Exemple #19
0
/*
 * Display a dialog box with a list of options that can be turned on or off
 * in the style of radiolist (only one option turned on at a time).
 */
int dialog_checklist(const char *title, const char *prompt, int height,
		     int width, int list_height)
{
	int i, x, y, box_x, box_y;
	int key = 0, button = 0, choice = 0, scroll = 0, max_choice;
	WINDOW *dialog, *list;

	/* which item to highlight */
	item_foreach() {
		if (item_is_tag('X'))
			choice = item_n();
		if (item_is_selected()) {
			choice = item_n();
			break;
		}
	}

do_resize:
	if (getmaxy(stdscr) < (height + 6))
		return -ERRDISPLAYTOOSMALL;
	if (getmaxx(stdscr) < (width + 6))
		return -ERRDISPLAYTOOSMALL;

	max_choice = MIN(list_height, item_count());

	/* center dialog box on screen */
	x = (COLS - width) / 2;
	y = (LINES - height) / 2;

	draw_shadow(stdscr, y, x, height, width);

	dialog = newwin(height, width, y, x);
	keypad(dialog, TRUE);

	draw_box(dialog, 0, 0, height, width,
		 dlg.dialog.atr, dlg.border.atr);
	wattrset(dialog, dlg.border.atr);
	mvwaddch(dialog, height - 3, 0, ACS_LTEE);
	for (i = 0; i < width - 2; i++)
		waddch(dialog, ACS_HLINE);
	wattrset(dialog, dlg.dialog.atr);
	waddch(dialog, ACS_RTEE);

	print_title(dialog, title, width);

	wattrset(dialog, dlg.dialog.atr);
	print_autowrap(dialog, prompt, width - 2, 1, 3);

	list_width = width - 6;
	box_y = height - list_height - 5;
	box_x = (width - list_width) / 2 - 1;

	/* create new window for the list */
	list = subwin(dialog, list_height, list_width, y + box_y + 1,
	              x + box_x + 1);

	keypad(list, TRUE);

	/* draw a box around the list items */
	draw_box(dialog, box_y, box_x, list_height + 2, list_width + 2,
	         dlg.menubox_border.atr, dlg.menubox.atr);

	/* Find length of longest item in order to center checklist */
	check_x = 0;
	item_foreach()
		check_x = MAX(check_x, strlen(item_str()) + 4);

	check_x = (list_width - check_x) / 2;
	item_x = check_x + 4;

	if (choice >= list_height) {
		scroll = choice - list_height + 1;
		choice -= scroll;
	}

	/* Print the list */
	for (i = 0; i < max_choice; i++) {
		item_set(scroll + i);
		print_item(list, i, i == choice);
	}

	print_arrows(dialog, choice, item_count(), scroll,
		     box_y, box_x + check_x + 5, list_height);

	print_buttons(dialog, height, width, 0);

	wnoutrefresh(dialog);
	wnoutrefresh(list);
	doupdate();

	while (key != KEY_ESC) {
		key = wgetch(dialog);

		for (i = 0; i < max_choice; i++) {
			item_set(i + scroll);
			if (toupper(key) == toupper(item_str()[0]))
				break;
		}

		if (i < max_choice || key == KEY_UP || key == KEY_DOWN ||
		    key == '+' || key == '-') {
			if (key == KEY_UP || key == '-') {
				if (!choice) {
					if (!scroll)
						continue;
					/* Scroll list down */
					if (list_height > 1) {
						/* De-highlight current first item */
						item_set(scroll);
						print_item(list, 0, FALSE);
						scrollok(list, TRUE);
						wscrl(list, -1);
						scrollok(list, FALSE);
					}
					scroll--;
					item_set(scroll);
					print_item(list, 0, TRUE);
					print_arrows(dialog, choice, item_count(),
						     scroll, box_y, box_x + check_x + 5, list_height);

					wnoutrefresh(dialog);
					wrefresh(list);

					continue;	/* wait for another key press */
				} else
					i = choice - 1;
			} else if (key == KEY_DOWN || key == '+') {
				if (choice == max_choice - 1) {
					if (scroll + choice >= item_count() - 1)
						continue;
					/* Scroll list up */
					if (list_height > 1) {
						/* De-highlight current last item before scrolling up */
						item_set(scroll + max_choice - 1);
						print_item(list,
							    max_choice - 1,
							    FALSE);
						scrollok(list, TRUE);
						wscrl(list, 1);
						scrollok(list, FALSE);
					}
					scroll++;
					item_set(scroll + max_choice - 1);
					print_item(list, max_choice - 1, TRUE);

					print_arrows(dialog, choice, item_count(),
						     scroll, box_y, box_x + check_x + 5, list_height);

					wnoutrefresh(dialog);
					wrefresh(list);

					continue;	/* wait for another key press */
				} else
					i = choice + 1;
			}
			if (i != choice) {
				/* De-highlight current item */
				item_set(scroll + choice);
				print_item(list, choice, FALSE);
				/* Highlight new item */
				choice = i;
				item_set(scroll + choice);
				print_item(list, choice, TRUE);
				wnoutrefresh(dialog);
				wrefresh(list);
			}
			continue;	/* wait for another key press */
		}
		switch (key) {
		case 'H':
		case 'h':
		case '?':
			button = 1;
			/* fall-through */
		case 'S':
		case 's':
		case ' ':
		case '\n':
			item_foreach()
				item_set_selected(0);
			item_set(scroll + choice);
			item_set_selected(1);
			delwin(list);
			delwin(dialog);
			return button;
		case TAB:
		case KEY_LEFT:
		case KEY_RIGHT:
			button = ((key == KEY_LEFT ? --button : ++button) < 0)
			    ? 1 : (button > 1 ? 0 : button);

			print_buttons(dialog, height, width, button);
			wrefresh(dialog);
			break;
		case 'X':
		case 'x':
			key = KEY_ESC;
			break;
		case KEY_ESC:
			key = on_key_esc(dialog);
			break;
		case KEY_RESIZE:
			delwin(list);
			delwin(dialog);
			on_key_resize();
			goto do_resize;
		}

		/* Now, update everything... */
		doupdate();
	}
	delwin(list);
	delwin(dialog);
	return key;		/* ESC pressed */
}
Exemple #20
0
/*
 * cl_suspend --
 *	Suspend a screen.
 *
 * PUBLIC: int cl_suspend __P((SCR *, int *));
 */
int
cl_suspend(SCR *sp, int *allowedp)
{
	struct termios t;
	CL_PRIVATE *clp;
	WINDOW *win;
	GS *gp;
	size_t y, x;
	int changed;

	gp = sp->gp;
	clp = CLP(sp);
	win = CLSP(sp) ? CLSP(sp) : stdscr;
	*allowedp = 1;

	/*
	 * The ex implementation of this function isn't needed by screens not
	 * supporting ex commands that require full terminal canonical mode
	 * (e.g. :suspend).
	 *
	 * The vi implementation of this function isn't needed by screens not
	 * supporting vi process suspension, i.e. any screen that isn't backed
	 * by a UNIX shell.
	 *
	 * Setting allowedp to 0 will cause the editor to reject the command.
	 */
	if (F_ISSET(sp, SC_EX)) { 
		/* Save the terminal settings, and restore the original ones. */
		if (F_ISSET(clp, CL_STDIN_TTY)) {
			(void)tcgetattr(STDIN_FILENO, &t);
			(void)tcsetattr(STDIN_FILENO,
			    TCSASOFT | TCSADRAIN, &clp->orig);
		}

		/* Stop the process group. */
		(void)kill(0, SIGTSTP);

		/* Time passes ... */

		/* Restore terminal settings. */
		if (F_ISSET(clp, CL_STDIN_TTY))
			(void)tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &t);
		return (0);
	}

	/*
	 * Move to the lower left-hand corner of the screen.
	 *
	 * XXX
	 * Not sure this is necessary in System V implementations, but it
	 * shouldn't hurt.
	 */
	getyx(win, y, x);
	(void)wmove(win, LINES - 1, 0);
	(void)wrefresh(win);

	/*
	 * Temporarily end the screen.  System V introduced a semantic where
	 * endwin() could be restarted.  We use it because restarting curses
	 * from scratch often fails in System V.  4BSD curses didn't support
	 * restarting after endwin(), so we have to do what clean up we can
	 * without calling it.
	 */
	/* Save the terminal settings. */
	(void)tcgetattr(STDIN_FILENO, &t);

	/* Restore the cursor keys to normal mode. */
	(void)keypad(stdscr, FALSE);

	/* Restore the window name. */
	(void)cl_rename(sp, NULL, 0);

#ifdef HAVE_BSD_CURSES
	(void)cl_attr(sp, SA_ALTERNATE, 0);
#else
	(void)endwin();
#endif
	/*
	 * XXX
	 * Restore the original terminal settings.  This is bad -- the
	 * reset can cause character loss from the tty queue.  However,
	 * we can't call endwin() in BSD curses implementations, and too
	 * many System V curses implementations don't get it right.
	 */
	(void)tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &clp->orig);

	/* Stop the process group. */
	(void)kill(0, SIGTSTP);

	/* Time passes ... */

	/*
	 * If we received a killer signal, we're done.  Leave everything
	 * unchanged.  In addition, the terminal has already been reset
	 * correctly, so leave it alone.
	 */
	if (clp->killersig) {
		F_CLR(clp, CL_SCR_EX_INIT | CL_SCR_VI_INIT);
		return (0);
	}

	/* Restore terminal settings. */
	wrefresh(win);			    /* Needed on SunOs/Solaris ? */
	if (F_ISSET(clp, CL_STDIN_TTY))
		(void)tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &t);

#ifdef HAVE_BSD_CURSES
	(void)cl_attr(sp, SA_ALTERNATE, 1);
#endif

	/* Set the window name. */
	(void)cl_rename(sp, sp->frp->name, 1);

	/* Put the cursor keys into application mode. */
	(void)keypad(stdscr, TRUE);

	/* Refresh and repaint the screen. */
	(void)wmove(win, y, x);
	(void)cl_refresh(sp, 1);

	/* If the screen changed size, set the SIGWINCH bit. */
	if (cl_ssize(sp, 1, NULL, NULL, &changed))
		return (1);
	if (changed)
		F_SET(CLP(sp), CL_SIGWINCH);

	return (0);
}
Exemple #21
0
int main(int argc, char **argv)
{
        int exit_status = 0;

        char header[HEADER_BUFFER_SIZE];
        size_t header_length =
            snprintf(
                header,
                sizeof(header),
                "%-*s %-*s %-*s %-*s %-*s %-*s %*s %*s %*s "
                "%*s %*s %*s %*s %*s %*s\n",
                PID_Column_Width,     PID_Column_Name,
                PPID_Column_Width,    PPID_Column_Name,
                Name_Column_Width,    Name_Column_Name,
                UID_Column_Width,     UID_Column_Name,
                GID_Column_Width,     GID_Column_Name,
                State_Column_Width,   State_Column_Name,
                Nice_Column_Width,    Nice_Column_Name,
                UTime_Column_Width,   UTime_Column_Name,
                KTime_Column_Width,   KTime_Column_Name,
                RSS_Column_Width,     RSS_Column_Name,
                VM_Column_Width,      VM_Column_Name,
                Reads_Column_Width,   Reads_Column_Name,
                Writes_Column_Width,  Writes_Column_Name,
                Read_Column_Width,    Read_Column_Name,
                Written_Column_Width, Written_Column_Name
            );

        pid_t *pid_list = NULL;

        char total_ram_scaled[FIELD_BUFFER_SIZE];
        char used_ram_scaled[FIELD_BUFFER_SIZE];
        char free_ram_scaled[FIELD_BUFFER_SIZE];
        char total_swap_scaled[FIELD_BUFFER_SIZE];
        char used_swap_scaled[FIELD_BUFFER_SIZE];
        char free_swap_scaled[FIELD_BUFFER_SIZE];

        char user_cpu_time_scaled[FIELD_BUFFER_SIZE];
        char kernel_cpu_time_scaled[FIELD_BUFFER_SIZE];

        char core_memory_usage_scaled[FIELD_BUFFER_SIZE];
        char virtual_memory_usage_scaled[FIELD_BUFFER_SIZE];
        char data_read_scaled[FIELD_BUFFER_SIZE];
        char data_written_scaled[FIELD_BUFFER_SIZE];

        bool show_kernel_threads = false;

        if (!initscr()) {
            fprintf(
                stderr,
                "Failed to create the program's UI.\n"
            );

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

        if (has_colors()) {
            start_color();
            use_default_colors();
            init_pair(1, COLOR_BLACK, COLOR_WHITE);
        }
        noecho();
        halfdelay(Input_Delay);

        WINDOW *header_pad = newpad(1, header_length);
        if (!header_pad) {
            fprintf(
                stderr,
                "Failed to create a UI pad for a header.\n"
            );

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

        bool has_attribute = false;
        if (has_colors()) {
            wattron(header_pad, COLOR_PAIR(1));
            has_attribute =
                !has_attribute;
        }
        waddstr(header_pad, header);
        if (has_attribute) {
            wattroff(header_pad, COLOR_PAIR(1));
        }

        WINDOW *pad = NULL;
        int pad_height = -1;
        int pad_shift_y = 0;
        int pad_shift_x = 0;

        WINDOW *footer_pad = newpad(1, header_length);
        if (!footer_pad) {
            fprintf(
                stderr,
                "Failed to create a UI pad for a footer.\n"
            );

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

        wprintw(
            footer_pad,
            "Press 't' to %s kernel threads. Press 'q' to exit.",
            show_kernel_threads ?
                "hide" : "show"
        );

        for (;;) {
            pid_t current_pid =
                getpid();

            struct sysinfo system;
            if (sysinfo(&system)) {
                fprintf(
                    stderr,
                    "Failed to perform the 'sysinfo' system call.\n"
                );

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            long pid_list_length = syscall(__NR_get_pids, 0, NULL);
            if (pid_list_length <= 0) {
                fprintf(
                    stderr,
                    "Failed to perform the 'get_pids' system call. "
                    "Ensure that the 'task_info' subsystem was compiled "
                    "into the kernel.\n"
                );

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            size_t pid_list_size = pid_list_length * sizeof(*pid_list);
            if (!(pid_list = realloc(pid_list, pid_list_size))) {
                fprintf(stderr, "Failed to reserve memory.\n");

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            memset(pid_list, 0, pid_list_size);

            if (syscall(__NR_get_pids, pid_list_length, pid_list) <= 0) {
                fprintf(
                    stderr,
                    "Failed to perform the 'get_pids' system call. "
                    "Ensure that the 'task_info' subsystem was compiled "
                    "into the kernel.\n"
                );

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            if (pad_height != pid_list_length + 1) {
                pad_height =
                    pid_list_length + 1;

                if (pad) {
                    delwin(pad);
                }

                pad = newpad(pad_height, header_length);
                if (!pad) {
                    fprintf(
                        stderr,
                        "Failed to create a scrollable UI pad.\n"
                    );

                    exit_status =
                        EXIT_FAILURE;

                    goto cleanup;
                }

                keypad(pad, true);
            }

            size_t header_height =
                Header_Height;

            unsigned long uptime_days =
                system.uptime / 86400;
            unsigned long uptime_hours =
                system.uptime / 3600 -
                    uptime_days * 24;
            unsigned long uptime_minutes =
                system.uptime / 60 -
                    uptime_days * 1440 -
                    uptime_hours * 60;
            unsigned long uptime_seconds =
                system.uptime % 60;

            float load_average_scale =
                1 << SI_LOAD_SHIFT;
            float load_average_for_1_minute =
                system.loads[0] / load_average_scale;
            float load_average_for_5_minutes =
                system.loads[1] / load_average_scale;
            float load_average_for_15_minutes =
                system.loads[1] / load_average_scale;

            uint64_t total_ram =
                system.totalram * system.mem_unit;
            uint64_t used_ram =
                (system.totalram - system.freeram) * system.mem_unit;
            uint64_t free_ram =
                system.freeram * system.mem_unit;
            uint64_t total_swap =
                system.totalswap * system.mem_unit;
            uint64_t used_swap =
                (system.totalswap - system.freeswap) * system.mem_unit;
            uint64_t free_swap =
                system.freeswap * system.mem_unit;

            scale_size(
                total_ram,
                total_ram_scaled,
                sizeof(total_ram_scaled)
            );
            scale_size(
                used_ram,
                used_ram_scaled,
                sizeof(used_ram_scaled)
            );
            scale_size(
                free_ram,
                free_ram_scaled,
                sizeof(free_ram_scaled)
            );
            scale_size(
                total_swap,
                total_swap_scaled,
                sizeof(total_swap_scaled)
            );
            scale_size(
                used_swap,
                used_swap_scaled,
                sizeof(used_swap_scaled)
            );
            scale_size(
                free_swap,
                free_swap_scaled,
                sizeof(free_swap_scaled)
            );

            wredrawln(stdscr, 0, header_height);
            mvprintw(
                0, 0,
                "up for %lu %s %lu:%lu:%lu, tasks: %zu\n"
                "load average: %.2f, %.2f, %.2f\n"
                "\n"
                "total ram:  %*s, used ram:  %*s, free ram:  %*s\n"
                "total swap: %*s, used swap: %*s, free swap: %*s\n",
                uptime_days,
                uptime_days == 1 ?
                    "day" : "days",
                uptime_hours,
                uptime_minutes,
                uptime_seconds,
                pid_list_length,
                load_average_for_1_minute,
                load_average_for_5_minutes,
                load_average_for_15_minutes,
                Memory_Column_Width,
                total_ram_scaled,
                Memory_Column_Width,
                used_ram_scaled,
                Memory_Column_Width,
                free_ram_scaled,
                Memory_Column_Width,
                total_swap_scaled,
                Memory_Column_Width,
                used_swap_scaled,
                Memory_Column_Width,
                free_swap_scaled
            );

            werase(pad);

            int real_pad_height = 0;
            for (size_t i = 0; i < pid_list_length; ++i) {
                struct task_info task;
                pid_t pid = pid_list[i];
                if (syscall(__NR_get_task_info, pid, &task) == 0) {
                    if (!show_kernel_threads &&
                            (task.pid  == Kernel_Thread_Daemon_PID ||
                             task.ppid == Kernel_Thread_Daemon_PID)) {
                        continue;
                    }

                    const char *task_state =
                        task.state < Task_States_Count - 1 ?
                            Task_States[task.state + 1] :
                            Task_States[0];

                    scale_time(
                        task.user_cpu_time,
                        user_cpu_time_scaled,
                        sizeof(user_cpu_time_scaled)
                    );
                    scale_time(
                        task.system_cpu_time,
                        kernel_cpu_time_scaled,
                        sizeof(kernel_cpu_time_scaled)
                    );

                    scale_size(
                        task.core_memory_bytes_used,
                        core_memory_usage_scaled,
                        sizeof(core_memory_usage_scaled)
                    );
                    scale_size(
                        task.virtual_memory_bytes_used,
                        virtual_memory_usage_scaled,
                        sizeof(virtual_memory_usage_scaled)
                    );
                    scale_size(
                        task.bytes_read,
                        data_read_scaled,
                        sizeof(data_read_scaled)
                    );
                    scale_size(
                        task.bytes_written,
                        data_written_scaled,
                        sizeof(data_written_scaled)
                    );

                    has_attribute = false;
                    if (has_colors()) {
                        if (task.state == 0 &&
                                task.pid != current_pid) {
                            wattron(pad, COLOR_PAIR(1));
                            has_attribute =
                                !has_attribute;
                        }
                    }

                    wprintw(
                        pad,
                        "%-*d %-*d %-*s %-*d %-*d %-*s %*d "
                        "%*s %*s %*s %*s "
                        "%*"PRIu64" %*"PRIu64" "
                        "%*s %*s\n",
                        PID_Column_Width,     (int) pid,
                        PPID_Column_Width,    task.ppid,
                        Name_Column_Width,    task.name,
                        UID_Column_Width,     task.uid,
                        GID_Column_Width,     task.gid,
                        State_Column_Width,   task_state,
                        Nice_Column_Width,    task.nice_level,
                        UTime_Column_Width,   user_cpu_time_scaled,
                        KTime_Column_Width,   kernel_cpu_time_scaled,
                        RSS_Column_Width,     core_memory_usage_scaled,
                        VM_Column_Width,      virtual_memory_usage_scaled,
                        Reads_Column_Width,   task.read_syscalls_count,
                        Writes_Column_Width,  task.write_syscalls_count,
                        Read_Column_Width,    data_read_scaled,
                        Written_Column_Width, data_written_scaled
                    );

                    if (has_attribute) {
                        wattroff(pad, COLOR_PAIR(1));
                    }

                    ++real_pad_height;
                }
            }

            int window_height, window_width;
            getmaxyx(stdscr, window_height, window_width);

            wnoutrefresh(stdscr);
            prefresh(
                header_pad,
                0,                 pad_shift_x,
                header_height,     0,
                header_height + 1, window_width - 1
            );
            prefresh(
                pad,
                pad_shift_y,       pad_shift_x,
                header_height + 1, 0,
                window_height - 2, window_width - 1
            );
            prefresh(
                footer_pad,
                0,                 0,
                window_height - 1, 0,
                window_height,     window_width - 1
            );
            doupdate();

            int key = wgetch(pad);
            if (key != ERR) {
                switch (key) {
                    case 'h':
                    case KEY_LEFT:
                        --pad_shift_x;
                        break;
                    case 'j':
                    case KEY_DOWN:
                        ++pad_shift_y;
                        break;
                    case 'k':
                    case KEY_UP:
                        --pad_shift_y;
                        break;
                    case 'l':
                    case KEY_RIGHT:
                        ++pad_shift_x;
                        break;
                    case 't':
                        show_kernel_threads =
                            !show_kernel_threads;

                        werase(footer_pad);
                        wprintw(
                            footer_pad,
                            "Press 't' to %s kernel threads. "
                            "Press 'q' to exit.",
                            show_kernel_threads ?
                                "hide" : "show"
                        );

                        break;
                    case 'q':
                        goto cleanup;
                }

                int pad_height_limit =
                    real_pad_height - 2;

                if (pad_shift_y < 0) {
                    pad_shift_y = 0;
                } else if (pad_shift_y >
                               pad_height_limit) {
                    pad_shift_y =
                        pad_height_limit;
                }

                int pad_width_limit =
                    header_length - 5;

                if (pad_shift_x < 0) {
                    pad_shift_x = 0;
                } else if (pad_shift_x >
                               pad_width_limit) {
                    pad_shift_x =
                        pad_width_limit;
                }
            }
        }

cleanup:
        if (header_pad) {
            delwin(header_pad);
        }
        if (pad) {
            delwin(pad);
        }
        if (footer_pad) {
            delwin(footer_pad);
        }

        endwin();

        return exit_status;
}
Exemple #22
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;
    std::string dump;
    dump_mode dmode = dump_mode::TSV;

    // 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;
                }
            },
            {
                "--dump-stats", "<what> [mode = TSV]",
                "Dumps item stats",
                section_default,
                [&dump,&dmode](int n, const char *params[]) -> int {
                    if( n < 1 ) {
                        return -1;
                    }
                    dump = params[ 0 ];
                    if( n == 2 ) {
                        if( !strcmp( params[ 1 ], "TSV" ) ) {
                            dmode = dump_mode::TSV;
                            return 0;
                        } else if( !strcmp( params[ 1 ], "HTML" ) ) {
                            dmode = dump_mode::HTML;
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                    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
    get_options().init();
    get_options().load();

    set_language(true);

    // if we are dumping stats don't initialize curses to avoid escape sequences
    // being inserted in to the output stream
    if( dump.empty() ) {
         if( initscr() == nullptr ) { // 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( !dump.empty() ) {
            init_colors();
            g->dump_stats( dump, dmode );
            exit( 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( const std::exception &err ) {
        debugmsg( "%s", err.what() );
        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;
}
int window_sessions_list_print(gui_t* gui, int wid)
{
	int y,x;
	char buf[250];

	sipua_set_t* call;

	int nbusy, line, n, view;
	int busylines[MAX_SIPUA_LINES];
	int max;

	ogmp_curses_t* ocui = gui->topui;
	user_profile_t* user_profile = ocui->sipua->profile(ocui->sipua);

	if(gui->topui->gui_windows[EXTRAGUI])
		josua_clear_box_and_commands(gui->topui->gui_windows[EXTRAGUI]);

	gui->parent = wid;

	curseson(); cbreak(); noecho(); nonl(); keypad(stdscr,TRUE);

	getmaxyx(stdscr,y,x);
	max = y + gui->y1 - gui->y0 - 1;

	attrset(A_NORMAL);

	/* Window Title */
	attrset(COLOR_PAIR(4));
	snprintf(buf, 250, "%199.199s", " ");
	mvaddnstr(gui->y0, gui->x0, buf, (x-gui->x0));

	snprintf(buf, x-gui->x0, "All Calls of '%s'<%s>", user_profile->fullname, user_profile->regname);
	mvaddstr(gui->y0, gui->x0+1, buf);

	attrset(COLOR_PAIR(0));
	snprintf(buf, 250, "%199.199s", " ");
	mvaddnstr(gui->y0+1, gui->x0, buf, (x-gui->x0));
	mvaddnstr(gui->y0+2, gui->x0, buf, (x-gui->x0));
	mvaddnstr(gui->y0+3, gui->x0, buf, (x-gui->x0));

	/* Window Body */
	ocui->sipua->lock_lines(ocui->sipua);

	nbusy = ocui->sipua->busylines(ocui->sipua, busylines, MAX_SIPUA_LINES);
	if(nbusy == 0)
	{
		attrset(COLOR_PAIR(1));

		snprintf(buf, x - gui->x0, "No call available !");
		mvaddstr(gui->y0+2, gui->x0+1, buf);

		gui->gui_draw_commands(gui);
		return 0;
	}

	n = 0;
	while(busylines[n] != calllist_line) n++;

	if(n > max/2)
		view = n - max/2;
	else
		view = 0;
	
	for(line = view; line < nbusy; line++)
    {
#if 0
		snprintf(buf, 199, "%c%c %i//%i %i %s with: %s %199.199s",
					(cursor_sessions_list==pos-1) ? '-' : ' ',
					(cursor_sessions_list==pos-1) ? '>' : ' ',
					jcalls[k].cid,
					jcalls[k].did,
					jcalls[k].status_code,
					jcalls[k].reason_phrase,
					jcalls[k].remote_uri, " ");
#endif
		call = ocui->sipua->line(ocui->sipua, busylines[line]);

		if(line==calllist_line)
		{
			snprintf(buf, x - gui->x0, " %c%c %d. %s - [%s]%-80.80s",
					'-', '>', line, call->setid.id, call->subject, " ");
      
			attrset(COLOR_PAIR(10));
		}
		else
		{
			snprintf(buf, x - gui->x0, " %c%c %d. %s - [%s]%-80.80s",
					' ', ' ', line, call->setid.id, call->subject, " ");
      
			attrset(COLOR_PAIR(1));
		}

		mvaddnstr(gui->y0+1+n, gui->x0, buf, x-gui->x0);

		if (n == max)
			break;

		n++;
    }
  
	ocui->sipua->unlock_lines(ocui->sipua);

	gui->gui_draw_commands(gui);
  
	return 0;
}
int main( int argc, char *argv[] )
{
	ChewingContext *ctx;
	FILE *fout;
	char *prefix = CHEWING_DATA_PREFIX;
	int ch;
	int add_phrase_length;

	if ( argc < 2 ) {
		fprintf( stderr, "usage: genkeystroke filename\n" );
		exit( 1 );
	}
	else {
		fout = fopen( argv[ 1 ], "w" );
		if ( ! fout ) {
			fprintf( stderr, "Error: failed to open %s\n", argv[ 1 ] );
			exit( 1 );
		}
	}

	/* Initialize curses library */
	setlocale(LC_CTYPE, "");
	initscr();
	if ( has_colors() == TRUE ) {
		start_color();
		init_pair( 1, COLOR_WHITE, COLOR_BLUE );
		init_pair( 2, COLOR_RED, COLOR_YELLOW );
		init_pair( 3, COLOR_WHITE, COLOR_RED );
		hasColor = 1;
	}
	cbreak();
	noecho();
	keypad( stdscr, 1 );
	start_color();
	clear();
	refresh();

	/* Initialize libchewing */
	putenv( "CHEWING_PATH=" CHEWING_DATA_PREFIX );
	/* for the sake of testing, we should not change existing hash data */
	putenv( "CHEWING_USER_PATH=" TEST_HASH_DIR );
	chewing_Init( prefix, TEST_HASH_DIR );

	/* Request handle to ChewingContext */
	ctx = chewing_new();

	/* Set keyboard type */
	chewing_set_KBType( ctx, chewing_KBStr2Num( "KB_DEFAULT" ) );

	/* Fill configuration values */
	chewing_set_candPerPage( ctx, 9 );
	chewing_set_maxChiSymbolLen( ctx, 16 );
	chewing_set_addPhraseDirection( ctx, 1 );
	chewing_set_selKey( ctx, selKey_define, 10 );
	chewing_set_spaceAsSelection( ctx, 1 );
	chewing_set_autoShiftCur( ctx, 1 );
	chewing_set_phraseChoiceRearward( ctx, 1 );

	clear();
	mvaddstr( 0, 0, "Any key to start testing..." );

	while ( TRUE ) {
		ch = getch();
		switch ( ch ) {
			case KEY_LEFT:
				chewing_handle_Left( ctx );
				fprintf( fout, "<L>" );
				break;
			case KEY_SLEFT:
				chewing_handle_ShiftLeft( ctx );
				fprintf( fout, "<SL>" );
				break;
			case KEY_RIGHT:
				chewing_handle_Right( ctx );
				fprintf( fout, "<R>" );
				break;
			case KEY_SRIGHT:
				chewing_handle_ShiftRight( ctx );
				fprintf( fout, "<SR>" );
				break;
			case KEY_UP:
				chewing_handle_Up( ctx );
				fprintf( fout, "<U>" );
				break;
			case KEY_DOWN:
				chewing_handle_Down( ctx );
				fprintf( fout, "<D>" );
				break;
			case KEY_SPACE:
				chewing_handle_Space( ctx );
				fprintf( fout, " " );
				break;
			case KEY_ENTER:
				chewing_handle_Enter( ctx );
				fprintf( fout, "<E>" );
				break;
			case KEY_BACKSPACE:
				chewing_handle_Backspace( ctx );
				fprintf( fout, "<B>" );
				break;
			case KEY_ESC:
				chewing_handle_Esc( ctx );
				fprintf( fout, "<EE>" );
				break;
			case KEY_DC:
				chewing_handle_Del( ctx );
				fprintf( fout, "<DC>" );
				break;
			case KEY_HOME:
				chewing_handle_Home( ctx );
				fprintf( fout, "<H>" );
				break;
			case KEY_END:
				chewing_handle_End( ctx );
				fprintf( fout, "<EN>" );
				break;
			case KEY_TAB:
				chewing_handle_Tab( ctx );
				fprintf( fout, "<T>" );
				break;
			case CTRL_0:
			case CTRL_1:
			case CTRL_2:
			case CTRL_3:
			case CTRL_4:
			case CTRL_5:
			case CTRL_6:
			case CTRL_7:
			case CTRL_8:
			case CTRL_9:
				add_phrase_length = ( ch - CTRL_0 + '0' );
				chewing_handle_CtrlNum( ctx, add_phrase_length );
				fprintf( fout, "<C%c>", add_phrase_length );
				break;
			case KEY_CTRL_('B'): /* emulate CapsLock */
				chewing_handle_Capslock( ctx );
				fprintf( fout, "<CB>");
				break;
			case KEY_CTRL_('D'):
				goto end;
			case KEY_CTRL_('H'): /* emulate Shift */
				if ( chewing_get_ShapeMode( ctx ) == FULLSHAPE_MODE )
					chewing_set_ShapeMode( ctx, HALFSHAPE_MODE );
				else
					chewing_set_ShapeMode( ctx, FULLSHAPE_MODE );
				break;
			case KEY_NPAGE:
				chewing_handle_PageDown( ctx );
				fprintf( fout, "<PD>");
				break;
			case KEY_PPAGE:
				chewing_handle_PageUp( ctx );
				fprintf( fout, "<PU>");
				break;
			default:
				chewing_handle_Default( ctx, (char) ch );
				if ( ch != '<' && ch != '>' )
					fprintf( fout, "%c", (char) ch );
				else
					fprintf( fout, "<%c>", (char) ch );
				break;
		}
		drawline( 0, 0 );
		drawline( 2, 0 );
		show_interval_buffer( 3, 0, ctx );
		drawline( 4, 0 );
		show_choose_buffer( 5, 0, ctx );
		drawline( 6, 0 );
		show_zuin_buffer( 7, 0, ctx );
		show_full_shape( 7, 5, ctx );
		drawline( 8, 0 );
		mvaddstr( 9, 0, "Ctrl + d : leave" );
		mvaddstr( 9, 20, "Ctrl + b : toggle Eng/Chi mode" );
		mvaddstr( 10, 0, "F1, F2, F3, ..., F9 : Add user defined phrase");
		mvaddstr( 11, 0, "Ctrl + h : toggle Full/Half shape mode" );
		show_commit_string( 12, 0, ctx );
		show_userphrase( 7, 12, ctx );
		show_edit_buffer( 1, 0, ctx );
	}
end:
	endwin();

	/* Release Chewing context */
	chewing_delete( ctx );

	/* Termate Chewing services */
	chewing_Terminate();

	fprintf( fout, "\n" );
	fclose( fout );
	return 0;
}
Exemple #25
0
int main(int argc, char *argv[])
{
	int cap1, cap2;
	if (argc == 1)
	{
		cap1 = 3;
		cap2 = 5;
	}
	else
	{
		if (argc != 3)
			return 3;
		cap1 = atoi(argv[1]);
		cap2 = atoi(argv[2]);
		if (cap1 <= 0 || cap2 <= 0)
			return 5;
	}
	int ch = 0;
	int i;
	const int roof = std::max(cap1, cap2) + 2 + 2;
	Bucket b1(cap1), b2(cap2);

	initscr();
	start_color();
	cbreak();
	keypad(stdscr, true);
	noecho();
	init_pair(1, COLOR_WHITE, COLOR_BLUE);
	refresh();

	WINDOW *win1, *win2;

	win1 = newwin(cap1+2, 3, roof-(cap1+2), 2);
	win2 = newwin(cap2+2, 3, roof-(cap2+2), 6);

	box(win1, 0, 0);
	box(win2, 0, 0);

	wrefresh(win1);
	wrefresh(win2);
	move(0, 0);

	while (ch != 'q')
	{
		ch = getch();

		switch(ch)
		{
			case 'h':
				b1 << b2;
				break;
			case 'l':
				b1 >> b2;
				break;
			case 'u':
				b1.fill();
				break;
			case 'i':
				b2.fill();
				break;
			case 'j':
				b1.empty();
				break;
			case 'k':
				b2.empty();
				break;
			default:
				break;
		}
		wattron(win1, COLOR_PAIR(1));
		for (i=0; i<b1.level(); ++i)
			mvwaddch(win1, b1.max()-i, 1, ' ');
		wattroff(win1, COLOR_PAIR(1));
		for (; i<b1.max(); ++i)
			mvwaddch(win1, b1.max()-i, 1, ' ');
		wrefresh(win1);

		wattron(win2, COLOR_PAIR(1));
		for (i=0; i<b2.level(); ++i)
			mvwaddch(win2, b2.max()-i, 1, ' ');
		wattroff(win2, COLOR_PAIR(1));
		for (; i<b2.max(); ++i)
			mvwaddch(win2, b2.max()-i, 1, ' ');
		wrefresh(win2);
		move(0, 0);
	}

	endwin();
	return 0;
}
int main() {
  fdb = fopen("debug", "w");
  memset(land.cells, '#', WIDTH_MAX * HEIGHT_MAX * sizeof(char));
  memset(mines.cells, 0, sizeof(Landmap));
  srand(time(NULL));

  int i, x, y;
  for (i = 0; i < num_mine; ++i) {
    x = rand() % width, y = rand() % height;
    if (mines.cells[x][y])
      --i;
    else
      mines.cells[x][y] = 1;
  }

  // this can be written much betterly :P
  int j;
  for (i = 0; i < width; ++i) {
    for (j = 0; j < height; ++j) {
      if (mines.cells[i][j]) {
	map.cells[i][j] = '#';
	continue;
      }
      int k, l, tot = 0;
      for (k = -1; k <= 1; ++k)
	for (l = -1; l <= 1; ++l)
	  tot += IN_BOUNDS(i + k, j + l) ? mines.cells[i+k][j+l] : 0;
      map.cells[i][j] = tot ? tot + '0' : ' ';
    }
  }

  initscr();
  raw();
  noecho();
  keypad(stdscr, 1);
  start_color();

  init_pair(1, COLOR_BLUE, COLOR_BLACK);
  init_pair(2, COLOR_BLACK, COLOR_BLUE);
  init_pair(3, COLOR_RED, COLOR_RED);

  int curx = 0, cury = 0;
  for (;;) {
    render(curx, cury);
    switch (getch()) {
    case 'k': case KEY_UP:
      if (cury > 0)
	--cury;
      break;
    case 'j': case KEY_DOWN:
      if (cury < height - 1)
	++cury;
      break;
    case 'h': case KEY_LEFT:
      if (curx > 0)
	--curx;
      break;
    case 'l': case KEY_RIGHT:
      if (curx < width - 1)
	++curx;
      break;
    case 'u': case ' ':
      if (mines.cells[curx][cury])
	lose(mines);
      if (land.cells[curx][cury] == '#')
	flood(curx, cury);
      break;
    case 'q':
      endwin();
      exit(0);
    }
  }
  return 0; // shouldn't be reached
}
Exemple #27
0
int main(int argc, char **argv) {
    // ros initialization
    ros::init(argc, argv, "keyboard");
    ros::NodeHandle n;
    ros::Rate loop_rate(10);

    // connect to ros to control drone
    ros::Publisher launch, land, reset, cmd_vel;
    launch = n.advertise<std_msgs::Empty>("ardrone/takeoff", 5);
    land = n.advertise<std_msgs::Empty>("ardrone/land", 5);
    reset = n.advertise<std_msgs::Empty>("ardrone/reset", 5);
    cmd_vel = n.advertise<geometry_msgs::Twist>("cmd_vel", 15);

    // set up control messages
    std_msgs::Empty empty;
    geometry_msgs::Twist twist;
    twist.linear.x = 0; twist.linear.y = 0; twist.linear.z = 0;
    twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0;

    // ncurses initialization
    initscr();
    raw();
    noecho();
    keypad(stdscr, TRUE);
    timeout(500);

    printw("Team LMT ArDrone Keyboard Control Node\n\n");
    printw("Usage:\n");
    printw("    r - Reset\n");
    printw("    q - Quit (and land if necessary)\n");
    printw("    Space - Takeoff/Land\n");
    printw("    Arrow keys - Move laterally\n");
    printw("    w/s - Move up/down\n");
    printw("    a/d - Rotate left/right\n");
    refresh();

    // process keyboard input
    int in_air = 0, running = 1;
    while(running) {
        int ch = getch();
        switch(ch) {
            case ERR:
                cmd_vel.publish(twist);
                break;
            case 'q':
            case 'Q':
                cmd_vel.publish(twist);
                land.publish(empty);
                running = 0;
                break;
            case ' ':
                cmd_vel.publish(twist);
                if(in_air) land.publish(empty);
                else launch.publish(empty);
                in_air = !in_air;
                break;
            case 'r':
            case 'R':
                reset.publish(empty);
                break;
            case KEY_UP:
                twist.linear.x = VEL;
                cmd_vel.publish(twist);
                twist.linear.x = 0;
                break;
            case KEY_DOWN:
                twist.linear.x = -VEL;
                cmd_vel.publish(twist);
                twist.linear.x = 0;
                break;
            case KEY_LEFT:
                twist.linear.y = VEL;
                cmd_vel.publish(twist);
                twist.linear.y = 0;
                break;
            case KEY_RIGHT:
                twist.linear.y = -VEL;
                cmd_vel.publish(twist);
                twist.linear.y = 0;
                break;
            case 'w':
            case 'W':
                twist.linear.z = VEL;
                cmd_vel.publish(twist);
                twist.linear.z = 0;
                break;
            case 's':
            case 'S':
                twist.linear.z = -VEL;
                cmd_vel.publish(twist);
                twist.linear.z = 0;
                break;
            case 'a':
            case 'A':
                twist.angular.z = -VEL;
                cmd_vel.publish(twist);
                twist.angular.z = 0;
                break;
            case 'd':
            case 'D':
                twist.angular.z = VEL;
                cmd_vel.publish(twist);
                twist.angular.z = 0;
                break;
        }
    }

    // end curses
    endwin();
}
Exemple #28
0
void update_st_stats(struct pkt_record *pkt)
{
	struct pkt_record *table_entry;
	struct pkt_list_entry *ple, *tmp, *titer;
	struct timeval max_age = {.tv_sec = 0, .tv_usec = 5E5 };

	/* maintain a long-term history of packets */
	ple = malloc(sizeof(struct pkt_list_entry));
	ple->pkt = *pkt;
	DL_APPEND(st_pkt_list_head, ple);
	DL_FOREACH_SAFE(st_pkt_list_head, titer, tmp)
	{
		if (has_aged(ple, titer, max_age)) {
			HASH_FIND(hh, st_flow_table, &(titer->pkt.flow),
			          sizeof(struct flow), table_entry);
			assert(table_entry);
			table_entry->len -= titer->pkt.len;
			if (0 == table_entry->len) {
				HASH_DEL(st_flow_table, table_entry);
			}

			DL_DELETE(st_pkt_list_head, titer);
			free(titer);
		} else {
			break;
		}
	}

	/* Update the flow accounting table */
	/* id already in the hash? */
	HASH_FIND(hh, st_flow_table, &(pkt->flow), sizeof(struct flow),
	          table_entry);
	if (!table_entry) {
		table_entry =
		    (struct pkt_record *)malloc(sizeof(struct pkt_record));
		memset(table_entry, 0, sizeof(struct pkt_record));
		memcpy(table_entry, pkt, sizeof(struct pkt_record));
		HASH_ADD(hh, st_flow_table, flow, sizeof(struct flow),
		         table_entry);
	} else {
		table_entry->len += pkt->len;
	}

	HASH_SORT(st_flow_table, bytes_cmp);
}

void update_lt_stats(struct pkt_record *pkt)
{
	struct pkt_record *table_entry;
	struct pkt_list_entry *ple, *tmp, *titer;
	struct timeval max_age = {.tv_sec = 60, .tv_usec = 0 };

	/* maintain a long-term history of packets */
	ple = malloc(sizeof(struct pkt_list_entry));
	ple->pkt = *pkt;
	DL_APPEND(lt_pkt_list_head, ple);
	DL_FOREACH_SAFE(lt_pkt_list_head, titer, tmp)
	{
		if (has_aged(ple, titer, max_age)) {
			HASH_FIND(hh, lt_flow_table, &(titer->pkt.flow),
			          sizeof(struct flow), table_entry);
			assert(table_entry);
			table_entry->len -= titer->pkt.len;
			if (0 == table_entry->len) {
				HASH_DEL(lt_flow_table, table_entry);
			}

			DL_DELETE(lt_pkt_list_head, titer);
			free(titer);
		} else {
			break;
		}
	}

	/* Update the flow accounting table */
	/* id already in the hash? */
	HASH_FIND(hh, lt_flow_table, &(pkt->flow), sizeof(struct flow),
	          table_entry);
	if (!table_entry) {
		table_entry =
		    (struct pkt_record *)malloc(sizeof(struct pkt_record));
		memset(table_entry, 0, sizeof(struct pkt_record));
		memcpy(table_entry, pkt, sizeof(struct pkt_record));
		HASH_ADD(hh, lt_flow_table, flow, sizeof(struct flow),
		         table_entry);
	} else {
		table_entry->len += pkt->len;
	}

	HASH_SORT(lt_flow_table, bytes_cmp);
}

void update_stats_tables(struct pkt_record *pkt)
{
	update_st_stats(pkt);
	update_lt_stats(pkt);
}

void handle_packet(uint8_t *user, const struct pcap_pkthdr *pcap_hdr,
                   const uint8_t *wirebits)
{
	static const struct pkt_record ZeroPkt = { 0 };
	struct pkt_record *pkt;
	char errstr[DECODE_ERRBUF_SIZE];

	pkt = malloc(sizeof(struct pkt_record));
	*pkt = ZeroPkt;

	if (0 == decode_ethernet(pcap_hdr, wirebits, pkt, errstr)) {
		update_stats_tables(pkt);
	} else {
		mvprintw(ERR_LINE_OFFSET, 0, "%-80s", errstr);
	}

	free(pkt);
}

void grab_packets(int fd, pcap_t *handle)
{
	struct timespec timeout_ts = {.tv_sec = 0, .tv_nsec = 1E8 };
	struct pollfd fds[] = {
		{.fd = fd, .events = POLLIN, .revents = POLLHUP }
	};

	int ch;

	while (1) {
		if (ppoll(fds, 1, &timeout_ts, NULL)) {
			pcap_dispatch(handle, 10000, handle_packet, NULL);
		}

		if ((ch = getch()) == ERR) {
			/* normal case - no input */
			;
		} else {
			switch (ch) {
			case 'q':
				endwin(); /* End curses mode */
				return;
			}
		}
		print_top_n(5);
		refresh(); /* ncurses screen update */
	}
}

void init_curses()
{
	initscr();            /* Start curses mode              */
	raw();                /* Line buffering disabled        */
	keypad(stdscr, TRUE); /* We get F1, F2 etc..            */
	noecho();             /* Don't echo() while we do getch */
	nodelay(stdscr, TRUE);
}
Exemple #29
0
int
edit_entry (const char *datafile, long pos)
{
  FILE *fp = NULL;
  char filename[PATH_MAX];
  pid_t process_id = 0;
  int status = 0;
  struct stat sb;
  time_t modified_time = 0;
  vc_component *v = NULL;
  int ret_val = -1;

  /* retrieve the entry for editing */
  fp = fopen (datafile, "r");
  fseek (fp, pos, SEEK_SET);
  v = parse_vcard_file (fp);
  fclose (fp);
  fp = NULL;

  /* open a temp file for editing */
  tmpnam (filename);
  fp = fopen (filename, "w");

  /* dump the entry into the temp file for editing */
  fprintf_vcard (fp, v);
  fclose (fp);
  fp = NULL;

  /* record when the file has been modified */
  stat (filename, &sb);
  modified_time = sb.st_mtime;

  endwin ();

  process_id = fork ();
  if (process_id < 0)
    {
      /* could not fork... check errno */
    }
  else if (0 == process_id)
    {
      /* child is running */

      /* replace process image with the editor */
      execlp (editor, editor_basename, filename, NULL);
      _exit (2);                /* execlp failed */
    }
  else
    {
      /* parent is running */
      waitpid (process_id, &status, 0);
    }

  /* check if the temp file has been modified */
  stat (filename, &sb);
  if (modified_time != sb.st_mtime)
    {
      /* need to change the datafile */
      update_datafile (datafile, pos, filename);
      ret_val = EDIT_SUCCESSFUL;
    }
  else
    {
      ret_val = EDIT_ABORTED;
    }

  remove (filename);

  /* put everything back to normal */
  refresh ();
  initscr ();
  keypad (stdscr, TRUE);        /* enable keypad for use of arrow keys */
  nonl ();                      /* tell curses not to do NL->CR/NL on output */
  cbreak ();                    /* take input chars immediately */
  noecho ();
  return ret_val;
}
Exemple #30
0
sysdig_init_res csysdig_init(int argc, char **argv)
{
	sysdig_init_res res;
	sinsp* inspector = NULL;
	vector<string> infiles;
	int op;
	uint64_t cnt = -1;
	uint32_t snaplen = 0;
	int long_index = 0;
	int32_t n_filterargs = 0;
	captureinfo cinfo;
	string errorstr;
	string display_view;
	bool print_containers = false;
	uint64_t refresh_interval_ns = 2000000000;
	bool list_flds = false;
	bool m_raw_output = false;
	string* k8s_api = 0;

	static struct option long_options[] =
	{
		{"delay", required_argument, 0, 'd' },
		{"exclude-users", no_argument, 0, 'E' },
		{"help", no_argument, 0, 'h' },
		{"k8s-api", required_argument, 0, 'k'},
		{"list", optional_argument, 0, 'l' },
		{"numevents", required_argument, 0, 'n' },
		{"print", required_argument, 0, 'p' },
		{"readfile", required_argument, 0, 'r' },
		{"raw", no_argument, 0, 0 },
		{"snaplen", required_argument, 0, 's' },
		{"logfile", required_argument, 0, 0 },
		{"view", required_argument, 0, 'v' },
		{"version", no_argument, 0, 0 },
		{0, 0, 0, 0}
	};

	//
	// Parse the arguments
	//
	try
	{
		inspector = new sinsp();

#ifdef HAS_CHISELS
		add_chisel_dirs(inspector);
#endif

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv,
			"d:Ehk:lNn:p:r:s:v:", long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case '?':
				//
				// Command line error 
				//
				throw sinsp_exception("command line error");
				break;
			case 'd':
				try
				{
					refresh_interval_ns = sinsp_numparser::parseu64(optarg) * 1000000;
				}
				catch(...)
				{
					throw sinsp_exception("can't parse the -d argument, make sure it's a number");
				}

				if(refresh_interval_ns < 100000000)
				{
					throw sinsp_exception("Period must be bigger then 100ms");
				}

				break;
			case 'E':
				inspector->set_import_users(false);
				break;
			case 'h':
				usage();
				delete inspector;
				return sysdig_init_res(EXIT_SUCCESS);
			case 'k':
				k8s_api = new string(optarg);
				break;
			case 'l':
				list_flds = true;
				break;
			case 'N':
				inspector->set_hostname_and_port_resolution_mode(false);
				break;
			case 'n':
				try
				{
					cnt = sinsp_numparser::parseu64(optarg);
				}
				catch(...)
				{
					throw sinsp_exception("can't parse the -n argument, make sure it's a number");
				}

				if(cnt <= 0)
				{
					throw sinsp_exception(string("invalid event count ") + optarg);
					res.m_res = EXIT_FAILURE;
					goto exit;
				}
				break;
			case 'p':
				if(string(optarg) == "c" || string(optarg) == "container")
				{
					inspector->set_print_container_data(true);
					print_containers = true;
				}

				break;
			case 'r':
				infiles.push_back(optarg);
				k8s_api = new string();
				break;
			case 's':
				snaplen = atoi(optarg);
				break;
			case 'v':
				display_view = optarg;
				break;
			case 0:
				{
					if(long_options[long_index].flag != 0)
					{
						break;
					}

					string optname = string(long_options[long_index].name);
					if(optname == "version")
					{
						printf("sysdig version %s\n", SYSDIG_VERSION);
						delete inspector;
						return sysdig_init_res(EXIT_SUCCESS);
					}
					else if(optname == "logfile")
					{
						inspector->set_log_file(optarg);
					}
					else if(optname == "raw")
					{
						m_raw_output = true;
					}
				}
				break;
			default:
				break;
			}
		}

		string filter;

		//
		// If -l was specified, print the fields and exit
		//
		if(list_flds)
		{
			list_fields(false);

			res.m_res = EXIT_SUCCESS;
			goto exit;
		}

		//
		// the filter is at the end of the command line
		//
		if(optind + n_filterargs < argc)
		{
#ifdef HAS_FILTERING
			for(int32_t j = optind + n_filterargs; j < argc; j++)
			{
				filter += argv[j];
				if(j < argc)
				{
					filter += " ";
				}
			}
#else
			fprintf(stderr, "filtering not compiled.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
#endif
		}

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			res.m_res = EXIT_FAILURE;
			goto exit;
		}

		//
		// Initialize ncurses
		//
#ifndef NOCURSESUI
		if(!m_raw_output)
		{
			(void) initscr();      // initialize the curses library
			(void) nonl();         // tell curses not to do NL->CR/NL on output
			intrflush(stdscr, false);
			keypad(stdscr, true);
			curs_set(0);
			if (has_colors())
			{
			  start_color();
			}
			use_default_colors();
			mousemask(ALL_MOUSE_EVENTS, NULL);
			noecho();

			timeout(0);

			// If this is uncommented, it's possible to natively handle stuff like CTRL+c
			//raw();
		}
#endif

		//
		// Create the list of views
		//
		sinsp_view_manager view_manager;

		//
		// Scan the chisel list to load the Lua views, and add them to the list
		//
		vector<chisel_desc> chlist;
		sinsp_chisel::get_chisel_list(&chlist);

		for(auto it : chlist)
		{
			if(it.m_viewinfo.m_valid)
			{
				if(print_containers)
				{
					it.m_viewinfo.apply_tag("containers");
				}
				else
				{
					it.m_viewinfo.apply_tag("default");
				}

				if(it.m_viewinfo.m_tags.size() != 0)
				{
					if(it.m_viewinfo.m_tags[0] == "Containers")
					{
						continue;
					}
				}

				view_manager.add(&it.m_viewinfo);
			}
		}

		//
		// Set the initial disply view
		//
		view_manager.set_selected_view(display_view);

		//
		// Go through the input sources and apply the processing to all of them
		//
		for(uint32_t j = 0; j < infiles.size() || infiles.size() == 0; j++)
		{
			//
			// Initialize the UI
			//
			sinsp_cursesui ui(inspector, 
				(infiles.size() != 0)? infiles[0] : "",
				(filter.size() != 0)? filter : "",
				refresh_interval_ns,
				print_containers,
				m_raw_output);

			ui.configure(&view_manager);
			ui.start(false, false);

			//
			// Launch the capture
			//
			bool open_success = true;

			if(infiles.size() != 0)
			{
				//
				// We have a file to open
				//
				inspector->open(infiles[j]);
			}
			else
			{
				if(j > 0)
				{
					break;
				}

				//
				// No file to open, this is a live capture
				//
#if defined(HAS_CAPTURE)
				try
				{
					inspector->open("");
				}
				catch(sinsp_exception e)
				{
					open_success = false;
				}

				//
				// Starting the live capture failed, try to load the driver with
				// modprobe.
				//
				if(!open_success)
				{
					open_success = true;

					if(system("modprobe " PROBE_NAME " > /dev/null 2> /dev/null"))
					{
						fprintf(stderr, "Unable to load the driver\n");
					}

					inspector->open("");
				}
#else
				//
				// Starting live capture
				// If this fails on Windows and OSX, don't try with any driver
				//
				inspector->open("");
#endif

				//
				// Enable gathering the CPU from the kernel module
				//
				inspector->set_get_procs_cpu_from_driver(true);
			}

			//
			// If required, set the snaplen
			//
			if(snaplen != 0)
			{
				inspector->set_snaplen(snaplen);
			}

			//
			// run k8s, if required
			//
			if(k8s_api)
			{
				inspector->init_k8s_client(k8s_api);
				k8s_api = 0;
			}
			else if(char* k8s_api_env = getenv("SYSDIG_K8S_API"))
			{
				if(k8s_api_env != NULL)
				{
					k8s_api = new string(k8s_api_env);
					inspector->init_k8s_client(k8s_api);
					k8s_api = 0;
				}
			}

			//
			// Start the capture loop
			//
			cinfo = do_inspect(inspector,
				cnt,
				&ui);

			//
			// Done. Close the capture.
			//
			inspector->close();
		}
	}
	catch(sinsp_capture_interrupt_exception&)
	{
	}
	catch(sinsp_exception& e)
	{
		errorstr = e.what();
		res.m_res = EXIT_FAILURE;
	}
	catch(...)
	{
		errorstr = "uncatched exception";
		res.m_res = EXIT_FAILURE;
	}

exit:
	if(inspector)
	{
		delete inspector;
	}

	//
	// Restore the original screen
	//
#ifndef NOCURSESUI
	if(!m_raw_output)
	{
		endwin();
	}
#endif

	if(errorstr != "")
	{
		cerr << errorstr << endl;
	}

	return res;
}