Example #1
0
/* Among other things,  'newtest' demonstrates how to make a Win32a
PDCurses app that is a for-real,  "pure Windows" version (instead of
a console application).  Doing this is quite easy,  and has certain
advantages.  If the app is invoked from a command prompt,  the only
difference you'll see is that the app runs separately (that is,  you
can continue to use the command prompt,  switching between it,  your
PDCurses/Win32a app,  and other processes).  Which is the main reason
I did it;  it meant that I could invoke a PDCurses-based text editor,
for example,  and still have use of the command line.

   (NOTE that,  for reasons I don't actually understand,  this happens
when the Visual C++ compiler is used.  With MinGW or OpenWatcom,  it's
still "really" a console app.)

   To do it,  we ensure that the usual main() function has an alternative
dummy_main() form,  taking the same arguments as main().  We add a
WinMain() function,  whose sole purpose is to reformulate lpszCmdLine
into argc/argv form,  and pass it on to dummy_main().  And,  of course,
we can switch back to a "normal" console app by removing the above
#define PURE_WINDOWS_VERSION line.             */

#ifdef PURE_WINDOWS_VERSION
#undef MOUSE_MOVED
#include <windows.h>

int dummy_main( int argc, char **argv);

int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPSTR lpszCmdLine, int nCmdShow)
{
   char *argv[30];
   int i, argc = 1;

   argv[0] = "newtest";
   for( i = 0; lpszCmdLine[i]; i++)
       if( lpszCmdLine[i] != ' ' && (!i || lpszCmdLine[i - 1] == ' '))
          argv[argc++] = lpszCmdLine + i;

   for( i = 0; lpszCmdLine[i]; i++)
       if( lpszCmdLine[i] == ' ')
          lpszCmdLine[i] = '\0';

   return dummy_main( argc, (char **)argv);
}

int dummy_main( int argc, char **argv)
#else       /* "usual",  console-app version: */
int main( int argc, char **argv)
#endif
{
    int quit = 0, i,  use_slk = 1;
    int fmt = 0xa;
    bool blink_state = FALSE;
    int cursor_state_1 = 2, cursor_state_2 = 3;
    int show_slk_index_line = 0;
    int redraw = 1;
    unsigned extra_character_to_show = 0;
#ifdef PDC_WIDE
    unsigned unicode_offset = 0x80;
#endif

/*  setlocale(LC_ALL, ".utf8");     */
    ttytype[0] = 25;   ttytype[1] = 90;         /* Allow 25 to 90 lines... */
    ttytype[2] = 80;   ttytype[3] = (char)200;  /* ...and 80 to 200 columns */
         /* (This program gets weird artifacts when smaller than 25x80.) */
    for( i = 1; i < argc; i++)
        if( argv[i][0] == '-')
            switch( argv[i][1])
            {
                case 's':
                    use_slk = 0;
                    break;
                case 'l':
                    setlocale( LC_ALL, argv[i] + 2);
                    break;
                case 'e':
                    sscanf( argv[i] + 2, "%x", &extra_character_to_show);
                    break;
                case 'f':
                    sscanf( argv[i] + 2, "%x", (unsigned *)&fmt);
                    break;
                case 'i':
                    show_slk_index_line = 1;
                    break;
                case 'r':     /* allow user-resizable windows */
                    {
                        int min_lines, max_lines, min_cols, max_cols;

                        if( sscanf( argv[i] + 2, "%d,%d,%d,%d",
                                       &min_lines, &max_lines,
                                       &min_cols, &max_cols) == 4)
                        {
                            ttytype[0] = min_lines;
                            ttytype[1] = max_lines;
                            ttytype[2] = min_cols;
                            ttytype[3] = max_cols;
                        }
                    }
                    break;
                case 'd':     /* set window size before initscr */
                    {
                        int n_lines, n_cols;

                        if( sscanf( argv[i] + 2, "%d,%d", &n_lines,
                                    &n_cols) == 2)
                            resize_term( n_lines, n_cols);
                    }
                    break;
#ifdef PDC_WIDE
                case 'u':
                    sscanf( argv[i] + 2, "%x", &unicode_offset);
                    break;
#endif
                default:
                    printf( "Option '%s' unrecognized\n", argv[i]);
                    break;
            }
    if( use_slk)
       slk_init( show_slk_index_line ? 3 : 0);
    Xinitscr(argc, argv);
    if( use_slk)
       slk_setup( show_slk_index_line ? -fmt : fmt);

    start_color();

# if defined(NCURSES_VERSION) || (defined(PDC_BUILD) && PDC_BUILD > 3000)
    use_default_colors();
# endif
    cbreak();
    noecho();
    clear();
    refresh();
#ifdef __PDCURSES__
    PDC_set_title( "NewTest: tests various PDCurses features");
#endif
    keypad( stdscr, TRUE);
    init_pair( 1, 15, COLOR_BLACK);
    init_pair( 2, COLOR_BLACK, COLOR_YELLOW);

    mousemask( ALL_MOUSE_EVENTS, NULL);
    attrset( COLOR_PAIR( 1));
    while( !quit)
    {
        char buff[80];
        const int xmax = getmaxx( stdscr);
        const int ymax = getmaxy( stdscr);
        int color_block_start = 54, c;
        int color_block_cols = (xmax - color_block_start) / 2;
        const int color_block_lines = 19;
        const char *cursor_state_text[N_CURSORS] = {
                  "Invisible (click to change) ",
                  "Underscore (click to change)",
                  "Block (click to change)     ",
                  "Outline (click to change)   ",
                  "Caret (click to change)     ",
                  "Half-block (click to change)",
                  "Central (click to change)   ",
                  "Cross (click to change)     ",
                  "Heavy box (click to change) " };

        if( color_block_cols < 0)
            color_block_cols = 0;
        if( redraw)
        {
            mvaddstr( 1, COL1, "'Normal' white-on-black");
            mvaddstr( 2, COL1, longname( ));
#if(CHTYPE_LONG >= 2)       /* "non-standard" 64-bit chtypes     */
            attron( A_DIM);
            mvaddstr( 15, 41, "Dimmed text");
            attroff( A_DIM);
#endif
#ifdef PDC_WIDE
            mvaddwstr( 3, COL1, L"'Normal' text,  but wide");
#endif
            attron( A_BLINK);
            mvaddstr( 6, 40, "Blinking");
            attron( A_BOLD);
            mvaddstr( 8, 40, "BlinkBold");
            attron( A_ITALIC);
            mvaddstr( 0, COL2, "BlinkBoldItalic");
            attrset( COLOR_PAIR( 3));
            attron( A_UNDERLINE);
#ifdef PDC_WIDE
            mvaddstr( 1, COL2, "Underlined");
            addwstr( L"WideUnder");
#endif
            attrset( COLOR_PAIR( 1));
            attron( A_UNDERLINE | A_ITALIC);
            mvaddstr( 2, COL2, "UnderlinedItalic");
            attrset( COLOR_PAIR( 2));
            attron( A_BLINK);
            mvaddstr( 4, COL1, "Black-on-yellow blinking");

            attrset( COLOR_PAIR( 1));
            move( 4, COL2);
            text_in_a_box( "Text in a box");

#ifdef CHTYPE_LONG
            attrset( COLOR_PAIR( 6));
            attron( A_STRIKEOUT);
            mvaddstr( 10, 40, "Strikeout");
            attrset( COLOR_PAIR( 1));
#endif

#ifdef PDC_WIDE
            move( 11, 40);
            text_in_a_box( "Next Ucode pg");
            if( unicode_offset)
               {
               move( 12, 40);
               text_in_a_box( "Prev Ucode pg");
               }
            mvprintw( 13, 40, "U+%04x ", unicode_offset);

#endif

            for( i = 0; i < 128; i++)
            {                 /* Show extended characters: */
#ifdef PDC_WIDE
                wchar_t buff[20];

                swprintf( buff, 20, L"%02x ",
                           (unsigned)( i + unicode_offset) & 0xff);
                mvaddwstr( 5 + i % 16, (i / 16) * 5, buff);
                if( i + unicode_offset > ' ')
                   addch( (chtype)( i + unicode_offset));
                else
                   addch( ' ');
                addch( ' ');
#else
                char buff[6];

                sprintf( buff, "%02x %c", i + 128, (char)(i + 128));
                mvaddstr( 5 + i % 16, (i / 16) * 5, buff);
#endif
            }

#if(CHTYPE_LONG >= 2)       /* "non-standard" 64-bit chtypes     */
            for( i = 0; i < 3 && i + 21 < ymax; i++)
            {                 /* Demonstrate full RGB color control: */
                int j;
                const char *output_text[3] = {
                    "Red on green to white on black   | (you can get full RGB colors when desired,",
                    "Blue on yellow to black on red | with palette coloring still being available)",
                    "White on red to green on blue,  underlined and italic" };
                const int len = (int)strlen( output_text[i]);

                move( 21 + i, 1);
                for( j = 0; j < len && j + 1 < xmax; j++)
                {
                    attr_t output_color;
                    const int oval = j * 31 / len;
                    const int reverse = 31 - oval;

                    if( !i)
                        output_color = A_RGB( 31, oval, oval, 0, reverse, 0);
                    else if( i == 1)
                        output_color = A_RGB( 0, 0, reverse, 31, reverse, 0);
                    else
                    {
                        output_color = A_RGB( reverse, 31, reverse,
                               reverse, 0, oval);
                        output_color |= A_UNDERLINE | A_ITALIC;
                    }
                    attrset( output_color);
                    addch( output_text[i][j]);
                }
            }
#endif         /* #if(CHTYPE_LONG >= 2) */
            redraw = 0;
            attrset( COLOR_PAIR( 1));
            if( extra_character_to_show && ymax > 23)
                mvaddch( 23, 63, (chtype)extra_character_to_show);

#ifdef PDC_WIDE
            for( i = 0; i < 6; i++)
            {
                static const wchar_t spanish[] = L"Espa\xf1ol";
                const int line = 24 + i / 3;
                const int col = 5 + 25 * (i % 3);

                static const wchar_t russian[] = {0x0420, 0x0443, 0x0441, 0x0441,
                   0x043a, 0x0438, 0x0439, L' ', 0x044f, 0x0437, 0x044b, 0x043a, 0};

                static const wchar_t greek[] = {0x0395, 0x03bb, 0x03bb, 0x03b7,
                   0x03bd, 0x03b9, 0x03ba, 0x03ac, 0};

                static const wchar_t georgian[] = {0x10e5, 0x10d0, 0x10e0, 0x10d7,
                   0x10e3, 0x10da, 0x10d8, L' ', 0x10d4, 0x10dc, 0x10d0, 0};

                static const wchar_t fullwidth[] = { 0xff26, 0xff55, 0xff4c, 0xff4c,
                   0xff57, 0xff49, 0xff44, 0xff54, 0xff48, 0 };  /* "Fullwidth" */

                static const wchar_t combining_marks[] = { L'C', L'o', 0x35c, L'm',
                   L'b', 0x30a, L'i', L'n', L'i', 0x304, L'n', 0x30b, 0x329,
                   L'g', 0x310,
                   L' ', L'C', 0x338, L'h', 0x306,  L'a', 0x361, L'r', L's',
                   0x30e, 0x348, 0 };

                static const wchar_t *texts[6] = { spanish, russian, greek,
                                georgian, fullwidth, combining_marks};

                if( line < ymax && col < xmax)
                   mvaddnwstr( line, 5 + 25 * (i % 3), texts[i], xmax - col);
            }
#endif

#ifdef MAYBE_TRY_THIS_SOMEWHERE_ELSE
        mvaddstr(  1, COL3, "Click on cursor descriptions to");
        mvaddstr(  2, COL3, "cycle through possible cursors");
        mvaddstr(  3, COL3, "Click on colors at left to change");
        mvaddstr(  4, COL3, "colors used for under/over/outlining");
        mvaddstr(  5, COL3, "Click 'Blink' at bottom to toggle");
        mvaddstr(  6, COL3, "'real' blinking vs. 'highlit' blink");
#endif
        }

        mvaddnstr( 19, color_block_start, cursor_state_text[cursor_state_1],
                                 xmax - color_block_start);
        mvaddnstr( 20, color_block_start, cursor_state_text[cursor_state_2],
                                 xmax - color_block_start);
        curs_set( (cursor_state_1 << 8) | cursor_state_2);
        for( i = 0; i < color_block_cols * color_block_lines; i++)
        {
            const int n_color_blocks = (COLOR_PAIRS < 256 ? COLOR_PAIRS : 256);

            attrset( COLOR_PAIR( i >= n_color_blocks ? 2 : i));
            if( i > 2 && i < n_color_blocks)
               init_pair((short)i, (short)i, COLOR_BLACK);
            if( !(i % color_block_cols))
               move( i / color_block_cols, color_block_start);
            attron( A_REVERSE);
            addstr( "  ");
        }
        move( 19, color_block_start - 3);
        refresh();
        c = getch( );
        attrset( COLOR_PAIR( 1));
        if( c == KEY_RESIZE)
        {
            redraw = 1;
            resize_term( 0, 0);
        }
        else if( c == KEY_F(1) || c == 27)
            quit = 1;
        else if( c == KEY_F(2))
        {
            blink_state ^= 1;
            PDC_set_blink( blink_state);
        }
        else if( c == KEY_F(3))   /* toggle SLKs */
        {
            use_slk ^= 1;
            if( use_slk)
                slk_restore( );
            else
                slk_clear( );
        }
        else if( c >= KEY_F(4) && c < KEY_F(12))
        {
            sscanf( labels[c - KEY_F(1)], "%x", (unsigned *)&fmt);
            if( use_slk)
                slk_setup( show_slk_index_line ? -fmt : fmt);
        }
        if( c != KEY_MOUSE)
        {
            sprintf( buff, "Key %s", keyname( c));
            if( !memcmp( buff + 4, "UNKNOWN", 7))
                sprintf( buff + 11, " (%x)", c);
            strcat( buff, " hit                 ");
            buff[COL2 - COL1] = '\0';
            mvaddstr( 0, COL1, buff);
        }
        else
        {
            MEVENT mouse_event;
#ifdef __PDCURSES__
            nc_getmouse( &mouse_event);
#else
            getmouse( &mouse_event);
#endif
            sprintf( buff, "Mouse at %d x %d: %x  ", mouse_event.x,
                              mouse_event.y, (unsigned)mouse_event.bstate);
            mvaddstr( 0, COL1, buff);
            if( mouse_event.x >= color_block_start
                            && mouse_event.y < color_block_lines)
            {
                int new_color = (mouse_event.x - color_block_start) / 2
                              + mouse_event.y * color_block_cols;

                if( new_color >= 256)
                    new_color = -1;
                PDC_set_line_color( (short)new_color);
            }
            else if( mouse_event.x >= color_block_start)
            {
                int shift = ((mouse_event.bstate & BUTTON_MODIFIER_SHIFT) ?
                           N_CURSORS - 1 : 1);

                if( mouse_event.y == 19)  /* blink/non-blink toggle */
                    cursor_state_1 = (cursor_state_1 + shift) % N_CURSORS;
                else if( mouse_event.y == 20)  /* cycle cursor state */
                    cursor_state_2 = (cursor_state_2 + shift) % N_CURSORS;
            }
#ifdef PDC_WIDE
            else if( mouse_event.x >= 40 && mouse_event.x < 40 + 10)
               {
               if( mouse_event.y == 11)
                  {
                  redraw = 1;
                  unicode_offset += 0x80;
                  }
               else if( mouse_event.y == 12 && unicode_offset)
                  {
                  redraw = 1;
                  unicode_offset -= 0x80;
                  }
               }
#endif
        }
    }

    endwin();

    return 0;
}
Example #2
0
File: haino.c Project: shixv/test
    int
main(int argc, char **argv)
{
    int NTiles, FromCol, ToCol,opt;
    unsigned char AutoFlag = 0;
    if(argc<2 || argc>3){ Usage();exit(0);}
    while( (opt=getopt(argc,argv,"a:n:h") )!=-1)
        switch (opt)
        {
            case 'n':
                NTiles = atoi(optarg);
                if (NTiles > MAXTILES || NTiles < MINTILES)
                {   fprintf(stderr, "步数从 %d 自 %d之间\n", MINTILES, MAXTILES);
                    return EXIT_FAILURE;
                }
                AutoFlag = FALSE;
                break;
            case 'a':
                NTiles = atoi(optarg);
                if (NTiles > MAXTILES || NTiles < MINTILES)
                {       fprintf(stderr, "步数从 %d 自 %d之间\n", MINTILES, MAXTILES);
                    return EXIT_FAILURE;
                }
                AutoFlag = TRUE;
                break;
            case 'h':
            case '?':
            case ':':
                Usage();
                exit(0);
        }
    initscr();
    if (has_colors())
    {
        int i;
        int bg = COLOR_BLACK;
        start_color();
        if (use_default_colors() == OK)
            bg = -1;
        for (i = 0; i < 9; i++)
            init_pair(i + 1, bg, TileColour[i]);
    }
    cbreak();
    /*LINES和COLS是Curses内部变量,用于存储当前终端的行数和列数*/
    if (LINES < 24 || COLS < 80)          /*标准的终端为24行80列*/
    {
        endwin();
        fprintf(stderr, "当前小于 24x80 \n");
        return EXIT_FAILURE;
    }
    if (AutoFlag)
    {
        curs_set(0);
        leaveok(stdscr, TRUE);
    }
    InitTiles(NTiles);
    DisplayTiles();
    if (AutoFlag) {
        do {
            noecho();
            AutoMove(0, 2, NTiles);
        } while (!Solved(NTiles));
        sleep(2);
    } 
    else {
        echo();
        for (;;) {
            if (GetMove(&FromCol, &ToCol))
                break;
            if (InvalidMove(FromCol, ToCol)) {
                mvaddstr(STATUSLINE, 0, "移 动 无 效 !!");
                refresh();
                beep();
                sleep(2);
                continue;
            }
            MakeMove(FromCol, ToCol);
            if (Solved(NTiles)) {
                mvprintw(STATUSLINE, 0, "恭喜!! 恭喜!! 你用 %d 步赢了", NMoves);
                refresh();
                sleep(5);
                break;
            }
        }
    }
    endwin();
    return EXIT_SUCCESS;
}
Example #3
0
static WINDOW *
ncurses_setup(void){
	struct ncurses_input_marshal *nim;
	const char *errstr = NULL;
	WINDOW *w = NULL;

	fprintf(stderr,"Entering ncurses mode...\n");
	if(initscr() == NULL){
		fprintf(stderr,"Couldn't initialize ncurses\n");
		return NULL;
	}
	if(cbreak() != OK){
		errstr = "Couldn't disable input buffering\n";
		goto err;
	}
	if(noecho() != OK){
		errstr = "Couldn't disable input echoing\n";
		goto err;
	}
	if(intrflush(stdscr,TRUE) != OK){
		errstr = "Couldn't set flush-on-interrupt\n";
		goto err;
	}
	if(scrollok(stdscr,FALSE) != OK){
		errstr = "Couldn't disable scrolling\n";
		goto err;
	}
	if(nonl() != OK){
		errstr = "Couldn't disable nl translation\n";
		goto err;
	}
	if(start_color() != OK){
		errstr = "Couldn't initialize ncurses color\n";
		goto err;
	}
	if(use_default_colors()){
		errstr = "Couldn't initialize ncurses colordefs\n";
		goto err;
	}
	w = stdscr;
	ESCDELAY = 100;
	keypad(stdscr,TRUE);
	if(nodelay(stdscr,FALSE) != OK){
		errstr = "Couldn't set blocking input\n";
		goto err;
	}
	if(curs_set(0) == ERR){
		errstr = "Couldn't disable cursor\n";
		goto err;
	}
	if(setup_statusbar(COLS)){
		errstr = "Couldn't setup status bar\n";
		goto err;
	}
	if(COLORS < 16){
		assert(init_pair(BORDER_COLOR,COLOR_GREEN,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_YELLOW,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_RED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_WHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CYAN,-1) == OK); // will use A_BOLD via OUR_BOLD
		assert(init_pair(UCAST_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(USELECTED_COLOR,-1,COLOR_CYAN) == OK);
		assert(init_pair(MSELECTED_COLOR,-1,COLOR_BLUE) == OK);
		assert(init_pair(BSELECTED_COLOR,-1,COLOR_MAGENTA) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_CYAN,-1) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_BLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_MAGENTA,-1) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_WHITE,-1) == OK);
	}else{
		int z;

		assert(init_pair(BORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(HEADER_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(FOOTER_COLOR,COLOR_MODYELLOW,-1) == OK);
		assert(init_pair(DBORDER_COLOR,COLOR_ALUMINIUM,-1) == OK);
		assert(init_pair(DHEADING_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(UBORDER_COLOR,COLOR_MODCYAN,-1) == OK);
		assert(init_pair(UHEADING_COLOR,COLOR_ORANGE,-1) == OK);
		assert(init_pair(PBORDER_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(PHEADING_COLOR,COLOR_MODRED,-1) == OK);
		assert(init_pair(BULKTEXT_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(BULKTEXT_ALTROW_COLOR,COLOR_MODWHITE,COLOR_PALEALUMINIUM) == OK);
		assert(init_pair(IFACE_COLOR,COLOR_MODWHITE,-1) == OK);
		assert(init_pair(LCAST_COLOR,COLOR_CHAMELEON,-1) == OK);
		assert(init_pair(UCAST_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(MCAST_COLOR,COLOR_SKYBLUE,-1) == OK);
		assert(init_pair(BCAST_COLOR,COLOR_MODVIOLET,-1) == OK);
		assert(init_pair(LSELECTED_COLOR,COLOR_MODWHITE,COLOR_CHAMELEON_50) == OK);
		assert(init_pair(USELECTED_COLOR,COLOR_MODWHITE,COLOR_BLUE_50) == OK);
		assert(init_pair(MSELECTED_COLOR,COLOR_MODWHITE,COLOR_SKYBLUE_50) == OK);
		assert(init_pair(BSELECTED_COLOR,COLOR_MODWHITE,COLOR_VIOLET_50) == OK);
		assert(init_pair(LCAST_L3_COLOR,COLOR_CHAMELEON_75,-1) == OK);
		assert(init_pair(UCAST_L3_COLOR,COLOR_BLUE_75,-1) == OK);
		assert(init_pair(MCAST_L3_COLOR,COLOR_SKYBLUE_75,-1) == OK);
		assert(init_pair(BCAST_L3_COLOR,COLOR_VIOLET_75,-1) == OK);
		assert(init_pair(LCAST_RES_COLOR,COLOR_CHAMELEON_50,-1) == OK);
		assert(init_pair(UCAST_RES_COLOR,COLOR_BLUE_50,-1) == OK);
		assert(init_pair(MCAST_RES_COLOR,COLOR_SKYBLUE_50,-1) == OK);
		assert(init_pair(BCAST_RES_COLOR,COLOR_VIOLET_50,-1) == OK);

		// Disable altrow stuff for now. It's hard to read and ugly.
		assert(init_pair(LCAST_ALTROW_COLOR,COLOR_CHAMELEON,-1) == OK);
		assert(init_pair(UCAST_ALTROW_COLOR,COLOR_MODBLUE,-1) == OK);
		assert(init_pair(MCAST_ALTROW_COLOR,COLOR_SKYBLUE,-1) == OK);
		assert(init_pair(BCAST_ALTROW_COLOR,COLOR_MODVIOLET,-1) == OK);
		assert(init_pair(LCAST_ALTROW_L3_COLOR,COLOR_CHAMELEON_75,-1) == OK);
		assert(init_pair(UCAST_ALTROW_L3_COLOR,COLOR_BLUE_75,-1) == OK);
		assert(init_pair(MCAST_ALTROW_L3_COLOR,COLOR_SKYBLUE_75,-1) == OK);
		assert(init_pair(BCAST_ALTROW_L3_COLOR,COLOR_VIOLET_75,-1) == OK);
		assert(init_pair(LCAST_ALTROW_RES_COLOR,COLOR_CHAMELEON_50,-1) == OK);
		assert(init_pair(UCAST_ALTROW_RES_COLOR,COLOR_BLUE_50,-1) == OK);
		assert(init_pair(MCAST_ALTROW_RES_COLOR,COLOR_SKYBLUE_50,-1) == OK);
		assert(init_pair(BCAST_ALTROW_RES_COLOR,COLOR_VIOLET_50,-1) == OK);
		assert(init_pair(SUBDISPLAY_COLOR,COLOR_MODWHITE,-1) == OK);

		for(z = FIRST_FREE_COLOR ; z < COLORS && z < COLOR_PAIRS ; ++z){
			assert(init_pair(z,z,-1) == OK);
		}
	}
	if(draw_main_window(w)){
		errstr = "Couldn't use ncurses\n";
		goto err;
	}
	if((nim = malloc(sizeof(*nim))) == NULL){
		goto err;
	}
	nim->w = w;
	nim->maintid = pthread_self();
	// Panels aren't yet being used, so we need call refresh() to
	// paint the main window.
	refresh();
	if(pthread_create(&inputtid,NULL,ncurses_input_thread,nim)){
		errstr = "Couldn't create UI thread\n";
		free(nim);
		goto err;
	}
	// FIXME install SIGWINCH() handler...?
	return w;

err:
	mandatory_cleanup(&w);
	fprintf(stderr,"%s",errstr);
	return NULL;
}
Example #4
0
void
init(void)
{
     struct sigaction sig;
     ttyclock->bg = COLOR_BLACK;

     /* Init ncurses */
     initscr();
     cbreak();
     noecho();
     keypad(stdscr, True);
     start_color();
     curs_set(False);
     clear();

     /* Init default terminal color */
     if(use_default_colors() == OK)
          ttyclock->bg = -1;

     /* Init color pair */
     init_pair(0, ttyclock->bg, ttyclock->bg);
     init_pair(1, ttyclock->bg, ttyclock->option.color);
     init_pair(2, ttyclock->option.color, ttyclock->bg);
     refresh();

     /* Init signal handler */
     sig.sa_handler = signal_handler;
     sig.sa_flags   = 0;
     sigaction(SIGWINCH, &sig, NULL);
     sigaction(SIGTERM,  &sig, NULL);
     sigaction(SIGINT,   &sig, NULL);
     sigaction(SIGSEGV,  &sig, NULL);

     /* Init global struct */
     ttyclock->running = True;
     if(!ttyclock->geo.x)
          ttyclock->geo.x = 0;
     if(!ttyclock->geo.y)
          ttyclock->geo.y = 0;
     if(!ttyclock->geo.a)
          ttyclock->geo.a = 1;
     if(!ttyclock->geo.b)
          ttyclock->geo.b = 1;
     ttyclock->geo.w = (ttyclock->option.second) ? SECFRAMEW : NORMFRAMEW;
     ttyclock->geo.h = 7;
     ttyclock->tm = localtime(&(ttyclock->lt));
     ttyclock->lt = time(NULL);
     update_hour();

     /* Create clock win */
     ttyclock->framewin = newwin(ttyclock->geo.h,
                                 ttyclock->geo.w,
                                 ttyclock->geo.x,
                                 ttyclock->geo.y);

     if(ttyclock->option.border) {
        box(ttyclock->framewin, 0, 0);
     }

     /* Create the date win */
     ttyclock->datewin = newwin(DATEWINH, strlen(ttyclock->date.datestr) + 2,
                                ttyclock->geo.x + ttyclock->geo.h - 1,
                                ttyclock->geo.y + (ttyclock->geo.w / 2) -
                                (strlen(ttyclock->date.datestr) / 2) - 1);

     if(ttyclock->option.border) {
          box(ttyclock->datewin, 0, 0);
     }

     clearok(ttyclock->datewin, True);

     set_center(ttyclock->option.center);

     nodelay(stdscr, True);

     wrefresh(ttyclock->datewin);
     wrefresh(ttyclock->framewin);

     return;
}
Example #5
0
Ui *ui_curses_new(void) {

	UiCurses *uic = calloc(1, sizeof(UiCurses));
	Ui *ui = (Ui*)uic;
	if (!uic)
		return NULL;
	tcgetattr(STDERR_FILENO, &uic->tio);
	if (!(uic->termkey = ui_termkey_new(STDIN_FILENO)))
		goto err;
	setlocale(LC_CTYPE, "");
	if (!getenv("ESCDELAY"))
		set_escdelay(50);
	char *term = getenv("TERM");
	if (!term)
		term = "xterm";
	if (!newterm(term, stderr, stdin)) {
		snprintf(uic->info, sizeof(uic->info), "Warning: unknown term `%s'", term);
		if (!newterm(strstr(term, "-256color") ? "xterm-256color" : "xterm", stderr, stdin))
			goto err;
	}
	start_color();
	use_default_colors();
	raw();
	noecho();
	nonl();
	keypad(stdscr, TRUE);
	meta(stdscr, TRUE);
	curs_set(0);
	/* needed because we use getch() which implicitly calls refresh() which
	   would clear the screen (overwrite it with an empty / unused stdscr */
	refresh();

	*ui = (Ui) {
		.init = ui_init,
		.start = ui_start,
		.free = ui_curses_free,
		.termkey_get = ui_termkey_get,
		.suspend = ui_suspend,
		.resize = ui_resize,
		.update = ui_update,
		.window_new = ui_window_new,
		.window_free = ui_window_free,
		.window_focus = ui_window_focus,
		.window_swap = ui_window_swap,
		.draw = ui_draw,
		.redraw = ui_redraw,
		.arrange = ui_arrange,
		.die = ui_die,
		.info = ui_info,
		.info_hide = ui_info_hide,
		.haskey = ui_haskey,
		.getkey = ui_getkey,
		.terminal_save = ui_terminal_save,
		.terminal_restore = ui_terminal_restore,
	};

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = sigwinch_handler;
	sigaction(SIGWINCH, &sa, NULL);
	sigaction(SIGCONT, &sa, NULL);

	ui_resize(ui);

	return ui;
err:
	ui_curses_free(ui);
	return NULL;
}
Example #6
0
void init_colors(int use_color)
{
	if (!!has_colors() == !!use_color) {
		start_color();
		use_default_colors();

		init_pair(1, COLOR_CYAN, -1);
		init_pair(2, COLOR_YELLOW, -1);
		init_pair(3, COLOR_WHITE, COLOR_GREEN);
		init_pair(4, COLOR_RED, -1);
		init_pair(5, COLOR_WHITE, -1);
		init_pair(6, COLOR_WHITE, COLOR_BLUE);
		init_pair(7, COLOR_RED, COLOR_BLUE);
		init_pair(8, COLOR_GREEN, COLOR_GREEN);
		init_pair(9, COLOR_WHITE, COLOR_RED);
#ifdef TRICOLOR_VOLUME_BAR
		init_pair(10, COLOR_WHITE, COLOR_WHITE);
		init_pair(11, COLOR_RED, COLOR_RED);
#endif

		attr_mixer_frame = COLOR_PAIR(1);
		attr_mixer_text = COLOR_PAIR(1);
		attr_mixer_active = A_BOLD | COLOR_PAIR(2);
		attr_ctl_frame = A_BOLD | COLOR_PAIR(1);
		attr_ctl_mute = COLOR_PAIR(1);
		attr_ctl_nomute = A_BOLD | COLOR_PAIR(3);
		attr_ctl_capture = A_BOLD | COLOR_PAIR(4);
		attr_ctl_nocapture = COLOR_PAIR(5);
		attr_ctl_label = A_BOLD | COLOR_PAIR(6);
		attr_ctl_label_focus = A_BOLD | COLOR_PAIR(7);
		attr_ctl_mark_focus = A_BOLD | COLOR_PAIR(4);
		attr_ctl_bar_lo = A_BOLD | COLOR_PAIR(8);
#ifdef TRICOLOR_VOLUME_BAR
		attr_ctl_bar_mi = A_BOLD | COLOR_PAIR(10);
		attr_ctl_bar_hi = A_BOLD | COLOR_PAIR(11);
#endif
		attr_ctl_inactive = COLOR_PAIR(5);
		attr_ctl_label_inactive = A_REVERSE | COLOR_PAIR(5);
		attr_errormsg = A_BOLD | COLOR_PAIR(9);
		attr_infomsg = A_BOLD | COLOR_PAIR(6);
		attr_textbox = A_BOLD | COLOR_PAIR(6);
		attr_textfield = A_REVERSE | COLOR_PAIR(5);
		attr_menu = A_BOLD | COLOR_PAIR(6);
		attr_menu_selected = A_REVERSE | COLOR_PAIR(6);
	} else {
		attr_mixer_frame = A_NORMAL;
		attr_mixer_text = A_NORMAL;
		attr_mixer_active = A_BOLD;
		attr_ctl_frame = A_BOLD;
		attr_ctl_mute = A_NORMAL;
		attr_ctl_nomute = A_BOLD;
		attr_ctl_capture = A_BOLD;
		attr_ctl_nocapture = A_NORMAL;
		attr_ctl_label = A_REVERSE;
		attr_ctl_label_focus = A_REVERSE | A_BOLD;
		attr_ctl_mark_focus = A_BOLD;
		attr_ctl_bar_lo = A_BOLD;
#ifdef TRICOLOR_VOLUME_BAR
		attr_ctl_bar_mi = A_BOLD;
		attr_ctl_bar_hi = A_BOLD;
#endif
		attr_ctl_inactive = A_NORMAL;
		attr_ctl_label_inactive = A_REVERSE;
		attr_errormsg = A_STANDOUT;
		attr_infomsg = A_NORMAL;
		attr_textbox = A_NORMAL;
		attr_textfield = A_REVERSE;
		attr_menu = A_NORMAL;
		attr_menu_selected = A_REVERSE;
	}
}
Example #7
0
File: irc.c Project: klange/ponyos
int main(int argc, char * argv[]) {

	int c;

	while ((c = getopt(argc, argv, "hp:n:")) != -1) {
		switch (c) {

			case 'n':
				nick = optarg;
				break;

			case 'p':
				port = atoi(optarg);
				break;

			case 'h':
			default:
				show_usage(argc,argv);
		}
	}

	if (optind >= argc) {
		show_usage(argc,argv);
	}

	setlocale (LC_ALL, "");

	host = argv[optind];

	char tmphost[512];
	sprintf(tmphost, "/dev/net/%s:%d", host, port);
	int sockfd = open(tmphost, O_RDWR);
	sock = fdopen(sockfd, "w");
	sockb = fdopen(sockfd, "r");

	if (!sock) {
		fprintf(stderr, "%s: Connection failed or network not available.\n", argv[0]);
		return 1;
	}

	main_win = initscr();
	start_color();
	use_default_colors();
	assume_default_colors(-1,-1);

	for (int bg = 1; bg < 16; ++bg) {
		for (int fg = 0; fg < 16; ++fg) {
			init_pair(fg+bg*16, fg, bg);
		}
	}

	for (int fg = 1; fg < 16; ++fg) {
		init_pair(fg, fg, -1);
	}


	int w, h;
	getmaxyx(main_win, h, w);

	topic_win  = newwin(1, w, 0, 0);
	body_win   = newwin(h-3, w, 1, 0);
	status_win = newwin(1, w, h-2, 0);
	input_win  = newwin(1, w, h-1, 0);

	signal(SIGWINCH, SIGWINCH_handler);

	scrollok(body_win, TRUE);

	wbkgd(topic_win, COLOR_PAIR(COLOR_WHITE+COLOR_BLUE*16));
	wbkgd(body_win, COLOR_PAIR(0));
	wbkgd(status_win, COLOR_PAIR(COLOR_WHITE+COLOR_BLUE*16));
	wbkgd(input_win, COLOR_PAIR(0));

	/* Write the welcome thing to the body */
	wprintw(body_win, " - Toaru IRC v. %s - \n", VERSION_STRING);
	wprintw(body_win, " Copyright 2015 K Lange\n");
	wprintw(body_win, " http://toaruos.org - http://github.com/klange/toaruos\n");
	wprintw(body_win, "\n");
	wprintw(body_win, " For help, type /help.\n");

	wmove(topic_win, 0, 0);
	wprintw(topic_win, " Toaru IRC v. %s", VERSION_STRING);

	/* Update status */
	wmove(status_win, 0, 0);
	wprintw(status_win, "[%s] ", nick);

	refresh_all();

	pthread_create(&read_thread, NULL, irc_read_thread, NULL);

	fprintf(sock, "NICK %s\r\nUSER %s * 0 :%s\r\n", nick, nick, nick);
	fflush(sock);

	char * buf = malloc(1024);

	while (1) {
		spin_lock(&c_lock);
		wmove(input_win, 0, 0);
		wprintw(input_win, "[%s] ", channel ? channel : "(none)");
		memset(buf, 0, sizeof(buf));
		spin_unlock(&c_lock);
		wgetstr(input_win, buf);

		do_thing(buf);

		spin_lock(&c_lock);
		wclear(input_win);
		wrefresh(input_win);
		spin_unlock(&c_lock);
	}

	endwin();

	return 0;
}
Example #8
0
int main(int argc, char **argv) {
	int y, x;
	int oldy, oldx;
	int graphy;
	int xhalf, graphyx2;
	int key;
	bool redraw = true;
	bool erase = true;
	bool changedelay = false;
	long timer = 0;
	struct timeval tv;
	struct iface ifa;
	WINDOW *rxgraph, *txgraph, *rxstats, *txstats;

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

	ARGBEGIN {
	case 'v':
		eprintf("nbwmon-%s\n", VERSION);
	case 'C':
		colors = false;
		break;
	case 's':
		siunits = true;
		break;
	case 'm':
		minimum = true;
		break;
	case 'g':
		globalmax = true;
		break;
	case 'd':
		delay = estrtod(EARGF(usage()));
		break;
	case 'i':
		strlcpy(ifa.ifname, EARGF(usage()), IFNAMSIZ);
		break;
	default:
		usage();
	} ARGEND;

	if (!detectiface(ifa.ifname))
		eprintf("Can't find network interface\n");
	if (!getcounters(ifa.ifname, &ifa.rx, &ifa.tx))
		eprintf("Can't read rx and tx bytes for %s\n", ifa.ifname);

	initscr();
	curs_set(FALSE);
	noecho();
	timeout(10);
	if (colors && has_colors()) {
		start_color();
		use_default_colors();
		init_pair(1, COLOR_GREEN, -1);
		init_pair(2, COLOR_RED, -1);
	}
	getmaxyx(stdscr, y, x);
	getmaxyx(stdscr, oldy, oldx);

	ifa.rxs = ecalloc(x - 3, sizeof(*ifa.rxs));
	ifa.txs = ecalloc(x - 3, sizeof(*ifa.txs));

	graphy = (y - 7) / 2;
	rxgraph = newwin(graphy, x, 0, 0);
	txgraph = newwin(graphy, x, graphy, 0);
	rxstats = newwin(y - graphy * 2, x / 2, graphy * 2, 0);
	txstats = newwin(y - graphy * 2, x - x / 2, graphy * 2, x / 2);

	for (key = ERR; key != 'q'; key = getch()) {
		if (key != ERR)
			redraw = true;
		switch (key) {
		case 's':
			siunits = !siunits;
			break;
		case 'm':
			minimum = !minimum;
			break;
		case 'g':
			globalmax = !globalmax;
			break;
		case '+':
			if (delay < 8) {
				delay *= 2;
				changedelay = true;
			}
			break;
		case '-':
			if (delay > 0.25) {
				delay /= 2;
				changedelay = true;
			}
			break;
		}

		if (y < 11 || x < 44) {
			werase(stdscr);
			addstr("terminal too small");
			wrefresh(stdscr);
			if (key == KEY_RESIZE)
				getmaxyx(stdscr, y, x);
			erase = true;
			continue;
		}
		if (erase) {
			werase(stdscr);
			wnoutrefresh(stdscr);
			erase = false;
		}

		if (oldy != y || oldx != x) {
			graphy = (y - 7) / 2;
			graphyx2 = graphy * 2;
			xhalf = x / 2;
			wresize(rxgraph, graphy, x);
			wresize(txgraph, graphy, x);
			wresize(rxstats, y - graphyx2, xhalf);
			wresize(txstats, y - graphyx2, x - xhalf);
			mvwin(rxgraph, 0, 0);
			mvwin(txgraph, graphy, 0);
			mvwin(rxstats, graphyx2, 0);
			mvwin(txstats, graphyx2, xhalf);
			if (oldx != x) {
				arrayresize(&ifa.rxs, x - 3, oldx - 3);
				arrayresize(&ifa.txs, x - 3, oldx - 3);
			}
			redraw = true;
		}

		gettimeofday(&tv, NULL);
		tv.tv_usec = (tv.tv_sec * 1000 + tv.tv_usec / 1000) / (delay * 1000.0);
		if (changedelay) {
			timer = tv.tv_usec;
			changedelay = false;
		}
		if (timer != tv.tv_usec) {
			timer = tv.tv_usec;
			if (!getdata(&ifa, x - 3))
				eprintf("Can't read rx and tx bytes for %s\n", ifa.ifname);
			redraw = true;
		}

		if (redraw) {
			printgraphw(rxgraph, "Received", ifa.ifname, COLOR_PAIR(1),
					ifa.rxs, ifa.rxmin, ifa.rxmax);
			printgraphw(txgraph, "Transmitted", NULL, COLOR_PAIR(2),
					ifa.txs, ifa.txmin, ifa.txmax);
			printstatsw(rxstats, "Received",
					ifa.rxs[x - 4], ifa.rxmin, ifa.rxavg, ifa.rxmax, ifa.rx);
			printstatsw(txstats, "Transmitted",
					ifa.txs[x - 4], ifa.txmin, ifa.txavg, ifa.txmax, ifa.tx);
			doupdate();
			redraw = false;
		}

		oldy = y;
		oldx = x;
		if (key == KEY_RESIZE)
			getmaxyx(stdscr, y, x);
	}

	delwin(rxgraph);
	delwin(txgraph);
	delwin(rxstats);
	delwin(txstats);
	endwin();
	free(ifa.rxs);
	free(ifa.txs);

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

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

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

		case 'C':
			option_clear = 0;
			break;

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

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

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

	if (optind >= argc)
		do_usage();

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

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

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



	get_terminal_size();

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

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

	if (precise_timekeeping)
		next_loop = get_time_usec();

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

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

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

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

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

			free(header);
		}

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

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

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

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

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

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

                }

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


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

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

                fclose(p);

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

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

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

        endwin();

        return 0;
}
Example #10
0
File: CRT.c Project: jweyrich/htop
void CRT_init(int delay, int colorScheme) {
   initscr();
   noecho();
   CRT_delay = delay;
   if (CRT_delay == 0) {
      CRT_delay = 1;
   }
   CRT_colors = CRT_colorSchemes[colorScheme];
   CRT_colorScheme = colorScheme;
   
   for (int i = 0; i < LAST_COLORELEMENT; i++) {
      int color = CRT_colorSchemes[COLORSCHEME_DEFAULT][i];
      CRT_colorSchemes[COLORSCHEME_BROKENGRAY][i] = color == (A_BOLD | ColorPair(Black,Black)) ? ColorPair(White,Black) : color;
   }
   
   halfdelay(CRT_delay);
   nonl();
   intrflush(stdscr, false);
   keypad(stdscr, true);
   mouseinterval(0);
   curs_set(0);
   if (has_colors()) {
      start_color();
      CRT_hasColors = true;
   } else {
      CRT_hasColors = false;
   }
   CRT_termType = getenv("TERM");
   if (String_eq(CRT_termType, "linux"))
      CRT_scrollHAmount = 20;
   else
      CRT_scrollHAmount = 5;
   if (String_eq(CRT_termType, "xterm") || String_eq(CRT_termType, "xterm-color") || String_eq(CRT_termType, "vt220")) {
      define_key("\033[H", KEY_HOME);
      define_key("\033[F", KEY_END);
      define_key("\033[7~", KEY_HOME);
      define_key("\033[8~", KEY_END);
      define_key("\033OP", KEY_F(1));
      define_key("\033OQ", KEY_F(2));
      define_key("\033OR", KEY_F(3));
      define_key("\033OS", KEY_F(4));
      define_key("\033[11~", KEY_F(1));
      define_key("\033[12~", KEY_F(2));
      define_key("\033[13~", KEY_F(3));
      define_key("\033[14~", KEY_F(4));
      define_key("\033[17;2~", KEY_F(18));
   }
#ifndef DEBUG
   signal(11, CRT_handleSIGSEGV);
#endif
   signal(SIGTERM, CRT_handleSIGTERM);
   use_default_colors();
   if (!has_colors())
      CRT_colorScheme = 1;
   CRT_setColors(CRT_colorScheme);

   /* initialize locale */
   setlocale(LC_CTYPE, "");

#ifdef HAVE_LIBNCURSESW
   if(strcmp(nl_langinfo(CODESET), "UTF-8") == 0)
      CRT_utf8 = true;
   else
      CRT_utf8 = false;
#endif

   CRT_treeStr =
#ifdef HAVE_LIBNCURSESW
	   CRT_utf8 ? CRT_treeStrUtf8 :
#endif
	   CRT_treeStrAscii;

#if NCURSES_MOUSE_VERSION > 1
   mousemask(BUTTON1_RELEASED | BUTTON4_PRESSED | BUTTON5_PRESSED, NULL);
#else
   mousemask(BUTTON1_RELEASED, NULL);
#endif
}
Example #11
0
/*
 * Prepare "curses" for use by the file "term.c"
 *
 * Installs the "hook" functions defined above, and then activates
 * the main screen "term", which clears the screen and such things.
 *
 * Someone should really check the semantics of "initscr()"
 */
errr init_gcu(int argc, char *argv[])
{
   int i;
   char path[1024];

#ifdef USE_SOUND

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

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

#endif

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

   if (!getenv("ESCDELAY"))
       putenv("ESCDELAY=20");

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

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

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


#ifdef A_COLOR

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

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

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

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

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

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

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

   }

#endif

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

	 /* Cannot enable */
	 arg_sound = FALSE;
      }

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

#ifdef USE_GRAPHICS

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

#endif /* USE_GRAPHICS */



   /*** Low level preparation ***/

#ifdef USE_GETCH

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

#endif

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

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

   /* Parse Args and Prepare the Terminals. Rectangles are specified
      as Width x Height, right? The game will allow you to have two
      strips of extra terminals, one on the right and one on the bottom.
      The map terminal will than fit in as big as possible in the remaining
      space.

      Examples:
        poschengband -mgcu -- -right 30x27,* -bottom *x7 will layout as

        Term-0: Map (COLS-30)x(LINES-7) | Term-1: 30x27
        --------------------------------|----------------------
        <----Term-3: (COLS-30)x7------->| Term-2: 30x(LINES-27)

        poschengband -mgcu -- -bottom *x7 -right 30x27,* will layout as

        Term-0: Map (COLS-30)x(LINES-7) | Term-2: 30x27
                                        |------------------------------
                                        | Term-3: 30x(LINES-27)
        ---------------------------------------------------------------
        <----------Term-1: (COLS)x7----------------------------------->

        Notice the effect on the bottom terminal by specifying its argument
        second or first. Notice the sequence numbers for the various terminals
        as you will have to blindly configure them in the window setup screen.
    */
    {
        int  spacer_cx = 1;
        int  spacer_cy = 1;
        int  min_cy = 3;
        int  min_cx = 10;
        int  right_cx = 0;
        int  right_cys[10] = {0};
        int  right_ct = 0;
        int  bottom_cy = 0;
        int  bottom_cxs[10] = {0};
        int  bottom_ct = 0;
        bool right_first = TRUE;
        int  map_cx, map_cy;
        int  next_win = 0;

        for (i = 1; i < argc; i++)
        {
            if (strcmp(argv[i], "-b") == 0)
            {
                term_data_init(&data[0], LINES, COLS, 0, 0);
                angband_term[0] = Term;
                break;
            }
            else if (strcmp(argv[i], "-right") == 0)
            {
                cptr arg, tmp;

                if (!bottom_cy)
                    right_first = TRUE;

                i++;
                if (i >= argc)
                    quit("Missing size specifier for -right");

                arg = argv[i];
                tmp = strchr(arg, 'x');
                if (!tmp)
                    quit("Expected something like -right 60x27,* for two right hand terminals of 60 columns, the first 27 lines and the second whatever is left.");
                right_cx = atoi(arg);
                tmp++;
                right_ct = _parse_size_list(tmp, right_cys, 10);
            }
            else if (strcmp(argv[i], "-bottom") == 0)
            {
                cptr arg, tmp;

                if (!right_cx)
                    right_first = FALSE;

                i++;
                if (i >= argc)
                    quit("Missing size specifier for -bottom");

                arg = argv[i];
                tmp = strchr(arg, 'x');
                if (!tmp)
                    quit("Expected something like -bottom *x7 for a single bottom terminal of 7 lines using as many columns as are available.");
                tmp++;
                bottom_cy = atoi(tmp);
                bottom_ct = _parse_size_list(arg, bottom_cxs, 10);
            }
        }

        if (right_cx)
            map_cx = COLS - (right_cx + spacer_cx);
        else
            map_cx = COLS;

        if (bottom_cy)
            map_cy = LINES - (bottom_cy + spacer_cy);
        else
            map_cy = LINES;

        if (map_cx < 80 || map_cy < 27)
            quit(format("Failed: PosChengband needs an 80x27 map screen, not %dx%d", map_cx, map_cy));

        /* Map Window: Upper Left */
        term_data_init(&data[next_win], map_cy, map_cx, 0, 0);
        angband_term[next_win] = Term;
        next_win++;

        /* Right Hand Strip */
        if (right_first)
        {
            int cy_remaining = LINES;
            int x = map_cx + spacer_cx;
            int y = 0;

            for (i = 0; i < right_ct; i++)
            {
                int cy = right_cys[i];

                if (!cy) break;

                if (cy > cy_remaining)
                    cy = cy_remaining;

                if (cy > min_cy)
                {
                    term_data_init(&data[next_win], cy, right_cx, y, x);
                    angband_term[next_win] = Term;
                    next_win++;

                    y += cy + spacer_cy;
                    cy_remaining -= cy + spacer_cy;
                }
            }
        }

        /* Bottom Strip */
        {
            int cx_remaining = COLS;
            int x = 0;
            int y = map_cy + spacer_cy;

            if (right_first)
                cx_remaining -= (right_cx + spacer_cx);

            for (i = 0; i < bottom_ct; i++)
            {
                int cx = bottom_cxs[i];

                if (!cx) break;

                if (cx > cx_remaining)
                    cx = cx_remaining;

                if (cx > min_cx)
                {
                    term_data_init(&data[next_win], bottom_cy, cx, y, x);
                    angband_term[next_win] = Term;
                    next_win++;

                    x += cx + spacer_cx;
                    cx_remaining -= cx + spacer_cx;
                }
            }
        }

        /* Right Hand Strip: TODO: Refactor this code duplication!
           But note that if the user specifies -right before bottom,
           then the terminal sequence numbers should reflect this fact! */
        if (!right_first)
        {
            int cy_remaining = LINES - bottom_cy;
            int x = map_cx + spacer_cx;
            int y = 0;

            for (i = 0; i < right_ct; i++)
            {
                int cy = right_cys[i];

                if (!cy) break;

                if (cy > cy_remaining)
                    cy = cy_remaining;

                if (cy > min_cy)
                {
                    term_data_init(&data[next_win], cy, right_cx, y, x);
                    angband_term[next_win] = Term;
                    next_win++;

                    y += cy + spacer_cy;
                    cy_remaining -= cy + spacer_cy;
                }
            }
        }
    }

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

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

#ifdef USE_GETCH
   /* Title screen (news.txt) won't draw otherwise for some reason ... */
   wrefresh(stdscr);
#endif

   /* Success */
   return (0);
}
Example #12
0
int main(int argc, char **argv){
	extern char *optarg;
	int c;
	int colouron = 0;

	time_t last_update = 0;

	WINDOW *window;

	extern int errno;

	int delay=2;

	sg_init();
	if(sg_drop_privileges() != 0){
		fprintf(stderr, "Failed to drop setuid/setgid privileges\n");
		return 1;
	}

#ifdef COLOR_SUPPORT
	while ((c = getopt(argc, argv, "d:cvh")) != -1){
#else
	while ((c = getopt(argc, argv, "d:vh")) != -1){
#endif
		switch (c){
			case 'd':
				delay = atoi(optarg);
				if (delay < 1){
					fprintf(stderr, "Time must be 1 second or greater\n");
					exit(1);
				}
				break;
#ifdef COLOR_SUPPORT
			case 'c':
				colouron = 1;
				break;
#endif
			case 'v':
				version_num(argv[0]);
				break;
			case 'h':
			default:
				usage(argv[0]);
				return 1;
				break;
		}
	}

	signal(SIGWINCH, sig_winch_handler);
	initscr();
#ifdef COLOR_SUPPORT
	/* turn on colour */
	if (colouron) {
		if (has_colors()) {
			start_color();
			use_default_colors();
			init_pair(1,COLOR_RED,-1);
			init_pair(2,COLOR_GREEN,-1);
			init_pair(3,COLOR_YELLOW,-1);
			init_pair(4,COLOR_BLUE,-1);
			init_pair(5,COLOR_MAGENTA,-1);
			init_pair(6,COLOR_CYAN,-1);
		} else {
			fprintf(stderr, "Colour support disabled: your terminal does not support colour.");
			colouron = 0;
		}
	}
#endif
	nonl();
	curs_set(0);
	cbreak();
	noecho();
	timeout(delay * 1000);
	window=newwin(0, 0, 0, 0);
	clear();

	if(!get_stats()){
		fprintf(stderr, "Failed to get all the stats. Please check correct permissions\n");
		endwin();
		return 1;
	}

	display_headings();

	for(;;){
		time_t now;
		int ch = getch();

		if (ch == 'q'){
			break;
		}

		/* To keep the numbers slightly accurate we do not want them
		 * updating more frequently than once a second.
		 */
		now = time(NULL);
		if ((now - last_update) >= 1) {
			get_stats();
		}
		last_update = now;

		if(sig_winch_flag) {
			clear();
			display_headings();
			sig_winch_flag = 0;
		}

		display_data(colouron);
	}

	endwin();
	return 0;
}
Example #13
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;
}
Example #14
0
int main(int argc, char* argv[]){
  /* Initialize pseudo random number generator */
  srand(time(NULL));

  /* Read command line arguments */
  struct basic_options op;
  struct multi_options mop;
  if (get_options(argc, argv, &op, &mop) == 1) return 1;
 
  /* Setup signal handlers */
  struct sigaction newhandler;            /* new settings         */
  sigset_t         blocked;               /* set of blocked sigs  */
  newhandler.sa_flags = SA_RESTART;       /* options     */
  sigemptyset(&blocked);                  /* clear all bits       */
  newhandler.sa_mask = blocked;           /* store blockmask      */
  newhandler.sa_handler = on_timer;      /* handler function     */
  if ( sigaction(SIGALRM, &newhandler, NULL) == -1 )
    perror("sigaction");


  /* prepare the terminal for the animation */
  setlocale(LC_ALL, "");
  initscr();     /* initialize the library and screen */
  cbreak();      /* put terminal into non-blocking input mode */
  noecho();      /* turn off echo */
  start_color();
  clear();       /* clear the screen */
  curs_set(0);   /* hide the cursor */

  use_default_colors();
  init_pair(0, COLOR_WHITE, COLOR_BLACK);
  init_pair(1, COLOR_WHITE, COLOR_BLACK);
  init_pair(2, COLOR_BLACK, COLOR_BLACK);
  init_pair(3, COLOR_RED, COLOR_BLACK);
  init_pair(4, COLOR_GREEN, COLOR_BLACK);
  init_pair(5, COLOR_BLUE, COLOR_BLACK);
  init_pair(6, COLOR_YELLOW, COLOR_BLACK);
  init_pair(7, COLOR_MAGENTA, COLOR_BLACK);
  init_pair(8, COLOR_CYAN, COLOR_BLACK);
 
  color_set(0, NULL);
  assume_default_colors(COLOR_WHITE, COLOR_BLACK);
  clear();
    
  struct state st;
  struct ui ui;

  /* Initialize the parameters of the program */
  attrset(A_BOLD | COLOR_PAIR(2));
  mvaddstr(0,0,"Map is generated. Please wait.");
  refresh();

  state_init(&st, &op, &mop);
 
  ui_init(&st, &ui);

  clear();
 
  /* non-blocking input */
  int fd_flags = fcntl(0, F_GETFL);
  fcntl(0, F_SETFL, (fd_flags|O_NONBLOCK));

  /* Start the real time interval timer with delay interval size */
  struct itimerval it;
  it.it_value.tv_sec = 0;
  it.it_value.tv_usec = 10000;
  it.it_interval.tv_sec = 0;
  it.it_interval.tv_usec = 10000;
  setitimer(ITIMER_REAL, &it, NULL);
  
  refresh();        
  input_ready = 0;
  time_to_redraw = 1;

  if (!mop.multiplayer_flag) {
    /* Run the game */
    run(&st, &ui);
  }
  else {
    if (mop.server_flag) run_server(&st, mop.clients_num, mop.val_server_port);
    else run_client(&st, &ui, mop.val_server_addr, mop.val_server_port, mop.val_client_port);
  }

  /* Restore the teminal state */
  echo();
  curs_set(1);
  clear();
  endwin();

  if (!mop.multiplayer_flag || mop.server_flag)
    printf ("Random seed was %i\n", st.map_seed);

  free(mop.val_server_addr);
  free(mop.val_server_port);
  free(mop.val_client_port);
  return 0;
}
Example #15
0
int main(int argc, char *argv[]) {
	static struct sigaction act;

	act.sa_handler = get_signal;
	sigfillset(&(act.sa_mask));
	sigaction(SIGSEGV, &act, NULL);

	int no_curses = 0;

	extern char *optarg;
	extern int optind, optopt;
	int c, refresh_tmp_time = 0;
	char *endptr;
	while ((c = getopt(argc, argv, ":r:ch")) != -1) {
		switch (c) {
		case 'r':
			refresh_tmp_time = (int) strtol(optarg, &endptr, 10);
			if ((refresh_tmp_time) && (refresh_tmp_time < 30)) {
				refresh_time = refresh_tmp_time * 1000;
			}
			break;
		case 'c':
			no_curses = 1;
			break;
		case 'h':
			printf("Usage: dbtop [parameters]\n");
			printf("no parameters - standart ncurses mode\n\n");
			printf("parameters:\n");
			printf("-r interval - refresh interval for ncurses mode(in seconds)\n");
			printf("-c - show one time users list (no ncurses)\n");
			exit(0);
			break;
		}
	}
	_socket = connect_to_server_dbtop();
	in = fdopen(_socket, "r+");
	out = fdopen(_socket, "w");
	if (!in || !out) {
		printf("Can't connect to socket. Maybe governor is not started\n");
		exit(-1);
	}
	if (no_curses) {
		client_type_t ctt = DBTOPCL;
		fwrite(&ctt, sizeof(client_type_t), 1, out);
		fflush(out);
		accounts = NULL;
		recv_accounts = NULL;
		read_info();
		printOneScreenNoCurses();
		exit(0);
	}
	
///    
    /*client_type_t ctt = DBTOP;
	fwrite(&ctt, sizeof(client_type_t), 1, out);
	fflush(out);*/
	accounts = NULL;
	recv_accounts = NULL;
	initscr();
	
	signal(SIGALRM, end_pgm);
	signal(SIGHUP, end_pgm);
	signal(SIGPIPE, end_pgm);
	signal(SIGQUIT, end_pgm);
	signal(SIGTERM, end_pgm);
	signal(SIGINT, end_pgm);
	
	noecho();
	nonl();
	intrflush(stdscr, false);
	keypad(stdscr, true);
	curs_set(0);
	if (has_colors()) {
		start_color();
		use_default_colors();
		init_pair(1, COLOR_GREEN, COLOR_BLUE);
		init_pair(2, COLOR_BLUE, -1);
		init_pair(3, COLOR_RED, -1);
	}
	raw();
	halfdelay(5);
    
    read_keys();
	closesock();
}
Example #16
0
int main()
{
    srand( time(NULL) );
    
    struct termios defs;    //Se guarda el estado actual de termios.
    tcgetattr(0,&defs);     //No queremos contaminar el tty del usuario
                            //(Asi es, el tty, no solo el proceso!)                          
	int startx, starty;

	initscr();			/* Start curses mode 		*/
	cbreak();			/* Line buffering disabled, Pass on */
					    /* everty thing to me 		*/
    start_color();
    use_default_colors();
    init_pair(1, COLOR_GREEN, -1);
    init_pair(2, COLOR_RED, -1);
    init_pair(3, COLOR_YELLOW, COLOR_RED);
    init_pair(4, COLOR_YELLOW,-1);
	keypad(stdscr, TRUE);		/* Activa las teclas de control. */

	starty = (LINES - HEIGHT) / 4;	/* Calcula la posición del centro de la pantalla */
	startx = (COLS - WIDTH) / 2;
	printw("Presione Q para salir");
	refresh();
	my_win = create_newwin(HEIGHT, WIDTH, starty, startx);
	stats = create_newwin(6,30,starty, startx+60);
	msgs = create_newwin(9,80,starty+30,startx-13);
	struct Animal *player;
    player = (struct Animal *)malloc(sizeof(struct Animal));
	draw_welcome(my_win,msgs,&player);
	my_win = create_newwin(HEIGHT, WIDTH, starty, startx);
    struct Nodo *cList = NULL;      //  ]
    struct Nodo *hList = NULL;      //   -> Los animales leidos se guardan en éstas listas.
    struct Nodo *pList = NULL;      //  ]
    int lim = loadData(&cList,&hList,&pList); //Carga las listas de animales, y devuelve el número de comidas.
    struct Cell matrix[9][9];
    initMatrix(matrix);
    int px = matrix[4][4].xpos;
    int py = matrix[4][4].ypos;
    
    //GAME LOOP:
    //Primero, setear modo no-canonico
    //Esto permite obtener input en tiempo real
    //y no bloquar la ejecución mientras el usuario juega.

    nonCanonical();
    char ch; int end = 0; int i = 0; int j = 0;
    while(!end)
	{
	    ch = '0';
	    read(0,&ch,1);      //Se lée el (posible) input del usuario.
	    if(!(i % 3))
    	    iterateMatrix(matrix,player);   //Los NPC reaccionan cada 3 ticks.
    	i++;
	    switch(ch)
		{	case 'a':
		        if(!apply(matrix,player,&cList,&hList,&pList,'l'))
	                draw_matrix(my_win,matrix,player);
               	wrefresh(my_win);
				break;
			case 'd':
			    if(!apply(matrix,player,&cList,&hList,&pList,'r'))
    	            draw_matrix(my_win,matrix,player);
	            wrefresh(my_win);
				break;
			case 'w':
			    if(!apply(matrix,player,&cList,&hList,&pList,'u'))
	                draw_matrix(my_win,matrix,player);
	            wrefresh(my_win);
   				break;
			case 's':
			    if(!apply(matrix,player,&cList,&hList,&pList,'d'))
	                draw_matrix(my_win,matrix,player);
	            wrefresh(my_win);
				break;
		    case 'q':
		        end = 1;
		        break;
		    default: draw_matrix(my_win,matrix,player);
		}
		if(player->eat(player,0) >= lim)
		{
		    draw_msg("Limite de comidas alcanzado! Felicitaciones!",msg_buffer);
            draw_msg("                                            ",msg_buffer);
            draw_msg("                                            ",msg_buffer);
		    canonical(&defs);
            getch();
		    end = 1;
		}
		if(player)
		    draw_stats(stats, player, lim);
		if(player->getHP(player) < 1)
		{
            wattron(my_win,COLOR_PAIR(3));
            for(i=-1;i<2;i++)
                for(j=-1;j<2;j++)
                    mvwprintw(my_win,px+i,py+j," ");
            mvwprintw(my_win,px,py,"X");
            wattroff(my_win,COLOR_PAIR(3));
            wrefresh(my_win);
            draw_msg("Has sido devorado...                      ",msg_buffer);
            draw_msg("                                          ",msg_buffer);
            draw_msg("                                          ",msg_buffer);
            end = 1;
            canonical(&defs);
            getch();
        }		    
	}
    canonical(&defs);
	endwin();			/* End curses mode		  */
    
    return 0;
}
Example #17
0
int
main(int argc, char **argv)
{
    int NTiles, FromCol, ToCol;
    unsigned char AutoFlag = 0;

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

	for(;;) {

		int attr_size, attr_name, attr_class, attr_graph, attr_bar, attr_cursor;

		if(opt_color) {
			attr_size = COLOR_PAIR(PAIR_SIZE);
			attr_name = COLOR_PAIR(PAIR_NAME);
			attr_bar = COLOR_PAIR(PAIR_BAR);
			attr_cursor = COLOR_PAIR(PAIR_CURSOR);
			attr_graph = COLOR_PAIR(PAIR_GRAPH);
			attr_class = COLOR_PAIR(PAIR_CLASS);
		} else {
			attr_size = 0;
			attr_name = A_BOLD;
			attr_class = 0;
			attr_graph = 0;
			attr_bar = A_REVERSE;
			attr_cursor = A_REVERSE;
			use_default_colors();
		}
	
		duc_size_type st = opt_apparent ? DUC_SIZE_TYPE_APPARENT : DUC_SIZE_TYPE_ACTUAL;

		/* Iterate all dirents to find largest size */

		duc_dir_seek(dir, 0);

		off_t size_max = 1;
		struct duc_dirent *e;
		while( (e = duc_dir_read(dir, st)) != NULL) {
			off_t size = opt_apparent ? e->size.apparent : e->size.actual;
			if(size > size_max) size_max = size;
		}

		int count = duc_dir_get_count(dir);
		int pgsize = rows - 2;
		
		/* Check boundaries */

		if(cur < 0) cur = 0;
		if(cur > count - 1) cur = count - 1;
		if(cur < top) top = cur;
		if(cur > top + pgsize - 1) top = cur - pgsize + 1;
		if(top < 0) top = 0;


		/* Draw header */

		char *path = duc_dir_get_path(dir);
		attrset(attr_bar);
		mvhline(0, 0, ' ', cols);
		mvprintw(0, 1, " %s ", path);
		attrset(0);
		free(path);


		/* Draw footer */

		struct duc_size size;
		duc_dir_get_size(dir, &size);
		char siz[32], cnt[32];
		duc_human_size(&size, st, opt_bytes, siz, sizeof siz);
		duc_human_number(count, opt_bytes, cnt, sizeof cnt);
		attrset(attr_bar);
		mvhline(rows-1, 0, ' ', cols);
		mvprintw(rows-1, 0, " Total %sB in %s files/directories", siz, cnt);
		attrset(0);

		/* Draw dirents */
	
		duc_dir_seek(dir, top);

		int i;
		int y = 1;

		for(i=top; i<top + pgsize; i++) {
			
			struct duc_dirent *e = duc_dir_read(dir, st);

			attrset(cur == i ? attr_cursor : 0);
			mvhline(y, 0, ' ', cols);

			if(e) {

				off_t size = opt_apparent ? e->size.apparent : e->size.actual;
		
				size_t max_size_len = opt_bytes ? 12 : 7;

				char class = duc_file_type_char(e->type);

				char siz[32];
				duc_human_size(&e->size, st, opt_bytes, siz, sizeof siz);
				if(cur != i) attrset(attr_size);
				printw("%*s", max_size_len, siz);

				printw(" ");
				char *p = e->name;
				if(cur != i) attrset(attr_name);
				while(*p) {
					if(*(uint8_t *)p >= 32) {
						printw("%c", *p);
					} else {
						printw("^%c", *p+64);
					}
					p++;
				}
				if(cur != i) attrset(attr_class);
				printw("%c", class);

				int w = cols - 30;
				if(w > cols / 2) w = cols / 2;
				if(opt_graph && w > 2) {
					int j;
					off_t g = w * size / size_max;
					if(cur != i) attrset(attr_graph);
					mvprintw(y, cols - w - 4, " [");
					for(j=0; j<w; j++) printw("%s", j < g ? "=" : " ");
					printw("] ");
				}

			} else {

				attrset(A_DIM);
				mvprintw(y, 0, "~");
			}

			y++;
		}

		duc_dir *dir2 = NULL;

		/* Handle key */

		int c = getch();

		switch(c) {
			case 'k':
			case KEY_UP: cur--; break;
			case 'j':
			case KEY_DOWN: cur++; break;
			case 21: cur -= pgsize/2; break;
			case KEY_PPAGE: cur -= pgsize; break;
			case 4: cur += pgsize/2; break;
			case KEY_NPAGE: cur += pgsize; break;
			case KEY_RESIZE: getmaxyx(stdscr, rows, cols); break;
			case 'a': opt_apparent ^= 1; break;
			case 'b': opt_bytes ^= 1; break;
			case 'c': opt_color ^= 1; break;
			case 'g': opt_graph ^= 1; break;
			case 'h': help(); break;

			case 27:
			case 'q': 
				  exit(0); break;

			case KEY_BACKSPACE:
			case KEY_LEFT:
				  if(depth > 0) {
					  return NULL;
				  } else {
					  dir2 = duc_dir_openat(dir, "..");
					  if(dir2) {
						  do_dir(dir2, 0);
						  duc_dir_close(dir2);
					  }
				  }
				  break;

			case KEY_RIGHT:
			case '\r':
			case '\n': 
				  duc_dir_seek(dir, cur);
				  struct duc_dirent *e = duc_dir_read(dir, st);
				  if(e->type == DUC_FILE_TYPE_DIR) {
					dir2 = duc_dir_openent(dir, e);
					if(dir2) {
						do_dir(dir2, depth + 1);
						duc_dir_close(dir2);
					}
				  }
				  break;
			default:
				  break;
		}

	}
Example #19
0
int main(int argn, char** argv) {
	
	int xsize, ysize;
	char c, c2;
	int i, i2;
	int x, y;

	WINDOW* wnd;
	char buf[50];
	tile* temp_tile; 

	/* Inicjalizacja generatora liczb losowych */
	srand(time(0));

	wnd = initscr();
	start_color();
	
	if(has_colors()) {

		enable_tile_colors();
		use_default_colors();

		/* Przyporządkuj każdej płytce kolor */
		init_pair(1, COLOR_YELLOW, -1);
		init_pair(2, COLOR_GREEN, -1);
		init_pair(3, COLOR_RED, -1);
		init_pair(4, COLOR_YELLOW, -1);
		init_pair(5, COLOR_WHITE, -1);
		init_pair(6, COLOR_RED, -1);
		init_pair(7, COLOR_GREEN, -1);
		init_pair(8, COLOR_BLUE, -1);
		init_pair(9, COLOR_CYAN, -1);
		init_pair(10, COLOR_MAGENTA, -1);

	}
	else {

		disable_tile_colors();

	}

	cbreak();
	echo();
	nonl();
	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);

	getmaxyx(wnd, ysize, xsize);

	/* Pobierz docelowy rozmiar */
	while(1) {

		werase(wnd);

		draw_frame(wnd);

		wmove(wnd, ysize/2-(MAX_SIZE-MIN_SIZE+2), 20);	

		wprintw(wnd, "Available pool size:");

		for(i=MIN_SIZE;i<=MAX_SIZE;i++) {

			wmove(wnd, ysize/2-(MAX_SIZE-MIN_SIZE+2)+(i-MIN_SIZE+1), 20);
			attron(COLOR_PAIR(5) | A_BOLD);
			wprintw(wnd, "%d", i);
			attroff(COLOR_PAIR(5) | A_BOLD);
			wprintw(wnd, " for %dx%d", i, i);
			
		}

		wmove(wnd, ysize-2, 2);
		wprintw(wnd, "Saephir (c), 2010");

		wmove(wnd, ysize/2+1, 20);
		wprintw(wnd, "Type the desired number: ");

		c = getch();

		buf[0] = c;
		buf[1] = 0;

		i2 = atoi(buf);

		if(i2 >= MIN_SIZE && i2 <= MAX_SIZE) {
			TILES_COUNT = i2;
			init();
			break;
		}

	}

	while(1) {

		werase(wnd);

		draw_frame(wnd);

		/* Wygrana gra */
		if(verify()) {

			print_game(wnd);

			wmove(wnd, ysize/2, 40);
			wprintw(wnd, "Well done!");
			wmove(wnd, ysize/2+1, 40);
			wprintw(wnd, "Press ENTER to exit...");
			getch();
			break;

		}

		print_game(wnd);
		print_pool(wnd);

		wmove(wnd, ysize-2, 1);

		wgetnstr(wnd, buf, 49);
		buf[49] = 0;

		if(strcmp(buf, "exit") == 0 || strcmp(buf, "quit") == 0 || strcmp(buf, "q") == 0) {

			break;

		}
		else if(strcmp(buf, "help") == 0 || strcmp(buf, "?") == 0) {

			wmove(wnd, ysize-2, 1);
			wclrtoeol(wnd);
			draw_frame(wnd);
			wmove(wnd, ysize-2, 1);
			wprintw(wnd, HELP_LINE);
			getch();
			wmove(wnd, ysize-2, 1);
			wclrtoeol(wnd);
			draw_frame(wnd);
			wmove(wnd, ysize-2, 1);
			wprintw(wnd, HELP_LINE2);
			getch();

		}

		else if(strcmp(buf, "<<") == 0) {

			push_left();

		}

		else if(strcmp(buf, ">>") == 0) {

			push_right();

		}

		else if(strcmp(buf, "^^") == 0) {

			push_top();

		}

		else if(strcmp(buf, "vv") == 0) {

			push_bottom();

		}
		else if(sscanf(buf, "%c%d<%c%d", &c, &i, &c2, &i2) == 4) {

			i--;
			i2--;

			if(c == c2 && i == i2)
				continue;

			if(c-'a' < 0 || c-'a' >= 2*TILES_COUNT)
				continue;

			if(c2-'a' < 0 || c2-'a' >= 2*TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			if(i2 < 0 || i2 >= TILES_COUNT)
				continue;

			/* Przesuwamy na pole gry */
			if(c-'a' < TILES_COUNT) {

				temp_tile = &game[i][c-'a'];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* przesuwamy z puli do gry */
				if(c2-'a' >= TILES_COUNT)
					temp_tile = &pool[i2][c2-'a'-TILES_COUNT];
				/* przesuwamy z gry do gry */
				else
					temp_tile = &game[i2][c2-'a'];

				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&game[i][c-'a'], temp_tile);

			}
			/* Przesuwamy do puli */
			else {

				temp_tile = &pool[i][c-'a'-TILES_COUNT];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z pola gry do puli */
				if(c2-'a' < TILES_COUNT)
					temp_tile = &game[i2][c2-'a'];
				/* Przesuwamy z puli do puli */
				else
					temp_tile = &pool[i2][c2-'a'-TILES_COUNT];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&pool[i][c-'a'-TILES_COUNT], temp_tile);

			}
			


		}
		else if(sscanf(buf, "%c%d>%c%d", &c, &i, &c2, &i2) == 4) {

			i--;
			i2--;

			if(c == c2 && i == i2)
				continue;

			if(c-'a' < 0 || c-'a' >= 2*TILES_COUNT)
				continue;

			if(c2-'a' < 0 || c2-'a' >= 2*TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			if(i2 < 0 || i2 >= TILES_COUNT)
				continue;

			/* Przesuwamy do puli */
			if(c2-'a' >= TILES_COUNT) {

				temp_tile = &pool[i2][c2-'a'-TILES_COUNT];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z pola gry */
				if(c-'a' < TILES_COUNT)
					temp_tile = &game[i][c-'a'];
				/* Przesuwamy z puli */
				else
					temp_tile = &pool[i][c-'a'-TILES_COUNT];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&pool[i2][c2-'a'-TILES_COUNT], temp_tile);

			}
			/* Przesuwamy na pole gry */
			else {

				temp_tile = &game[i2][c2-'a'];

				/* Miejsce musi być puste */
				if(!is_empty(temp_tile))
					continue;

				/* Przesuwamy z puli na pole gry */
				if(c-'a' >= TILES_COUNT)
					temp_tile = &pool[i][c-'a'-TILES_COUNT];
				/* Przesuwamy z pola gry na pole gry */
				else
					temp_tile = &game[i][c-'a'];
				
				/* Żródło nie może być puste */
				if(is_empty(temp_tile))
					continue;

				move_tile(&game[i2][c2-'a'], temp_tile);

			}

		}
		else if(sscanf(buf, "%c%d>pool", &c, &i) == 2 || sscanf(buf, "pool<%c%d", &c, &i) == 2) {

			i--;

			if(strcmp(&buf[2], ">pool") != 0) {
				buf[5] = 0;
				if(strcmp(buf, "pool<") != 0)
					continue;
			}

			if(c-'a' < 0 || c-'a' >= TILES_COUNT)
				continue;

			if(i < 0 || i >= TILES_COUNT)
				continue;

			/* Żródło nie może być puste */
			if(is_empty(&game[i][c-'a']))
				continue;

			/* Jeżeli źródło nie jest puste, to istnieją wolne miejsca w puli */
			/* znajdujemy więc pierwsze wolne miejsce */
			for(y=0;y<TILES_COUNT;y++) {
				for(x=0;x<TILES_COUNT;x++) {
					
					if(is_empty(&pool[x][y])) {
						
						move_tile(&pool[x][y], &game[i][c-'a']);
						break;
					}

				}
			}
			

		}

	}

	endwin();

	return 0;
}
Example #20
0
void
initcolors()
{
#ifdef HAVE_CURSES_COLOR
	if (has_colors())
	{
		start_color();
#ifdef HAVE_DECL_USE_DEFAULT_COLORS
		use_default_colors();
#endif
		normal = COLOR_PAIR(NORMAL);	/* normal text */
		init_pair(NORMAL, cols.normal_fore, cols.normal_back);
		if (cols.normal_bold)
			normal |= A_BOLD;
		if (cols.normal_blink)
			normal |= A_BLINK;

		menuselected = COLOR_PAIR(MENUSELECTED);		/* selected menu */
		init_pair(MENUSELECTED, cols.menuselected_fore, cols.menuselected_back);
		if (cols.menuselected_bold)
			menuselected |= A_BOLD;
		if (cols.menuselected_blink)
			menuselected |= A_BLINK;

		menu = COLOR_PAIR(MENU);	/* just menu */
		init_pair(MENU, cols.menu_fore, cols.menu_back);
		if (cols.menu_bold)
			menu |= A_BOLD;
		if (cols.menu_blink)
			menu |= A_BLINK;

		noteselected = COLOR_PAIR(NOTESELECTED);		/* selected note */
		init_pair(NOTESELECTED, cols.noteselected_fore, cols.noteselected_back);
		if (cols.noteselected_bold)
			noteselected |= A_BOLD;
		if (cols.noteselected_blink)
			noteselected |= A_BLINK;

		note = COLOR_PAIR(NOTE);	/* just note */
		init_pair(NOTE, cols.note_fore, cols.note_back);
		if (cols.note_bold)
			note |= A_BOLD;
		if (cols.note_blink)
			note |= A_BLINK;

		topline = COLOR_PAIR(TOPLINE);	/* topline color */
		init_pair(TOPLINE, cols.topline_fore, cols.topline_back);
		if (cols.topline_bold)
			topline |= A_BOLD;
		if (cols.topline_blink)
			topline |= A_BLINK;

		bottomline = COLOR_PAIR(BOTTOMLINE);	/* bottomline color */
		init_pair(BOTTOMLINE, cols.bottomline_fore, cols.bottomline_back);
		if (cols.bottomline_bold)
			bottomline |= A_BOLD;
		if (cols.bottomline_blink)
			bottomline |= A_BLINK;

		manualbold = COLOR_PAIR(MANUALBOLD);	/* manual bold color */
		init_pair(MANUALBOLD, cols.manualbold_fore, cols.manualbold_back);
		if (cols.manualbold_bold)
			manualbold |= A_BOLD;
		if (cols.manualbold_blink)
			manualbold |= A_BLINK;

		manualitalic = COLOR_PAIR(MANUALITALIC);		/* manual italic color */
		init_pair(MANUALITALIC, cols.manualitalic_fore, cols.manualitalic_back);
		if (cols.manualitalic_bold)
			manualitalic |= A_BOLD;
		if (cols.manualitalic_blink)
			manualitalic |= A_BLINK;

		url = COLOR_PAIR(URL);	/* url(http, ftp) color */
		init_pair(URL, cols.url_fore, cols.url_back);
		if (cols.url_bold)
			url |= A_BOLD;
		if (cols.url_blink)
			url |= A_BLINK;

		urlselected = COLOR_PAIR(URLSELECTED);	/* selected url */
		init_pair(URLSELECTED, cols.urlselected_fore, cols.urlselected_back);
		if (cols.urlselected_bold)
			urlselected |= A_BOLD;
		if (cols.urlselected_blink)
			urlselected |= A_BLINK;

		infohighlight = COLOR_PAIR(INFOHIGHLIGHT);	/* highlight for info quotes */
		init_pair(INFOHIGHLIGHT, cols.infohighlight_fore, cols.infohighlight_back);
		if (cols.infohighlight_bold)
			infohighlight |= A_BOLD;
		if (cols.infohighlight_blink)
			infohighlight |= A_BLINK;

		searchhighlight = COLOR_PAIR(SEARCHHIGHLIGHT);	/* highlight for info quotes */
		init_pair(SEARCHHIGHLIGHT, cols.searchhighlight_fore, cols.searchhighlight_back);
		if (cols.searchhighlight_bold)
			searchhighlight |= A_BOLD;
		if (cols.searchhighlight_blink)
			searchhighlight |= A_BLINK;
	}
	else
	{
#endif /* HAVE_CURSES_COLOR */
		normal = A_NORMAL;
		menu = A_BOLD;
		note = A_BOLD;
		url = A_BOLD;
		menuselected = A_REVERSE;
		noteselected = A_REVERSE;
		urlselected = A_REVERSE;
		topline = A_REVERSE;
		bottomline = A_REVERSE;
		manualbold = A_BOLD;
		manualitalic = A_BOLD;
		infohighlight = A_BOLD;
		searchhighlight = A_BOLD;
#ifdef HAVE_CURSES_COLOR
	}
#endif /* HAVE_CURSES_COLOR */
}
Example #21
0
/*
 * Prepare "curses" for use by the file "z-term.c"
 *
 * Installs the "hook" functions defined above, and then activates
 * the main screen "term", which clears the screen and such things.
 *
 * Someone should really check the semantics of "initscr()"
 */
errr init_gcu(int argc, char **argv) {
	int i;
	int rows, cols, y, x;
	int next_win = 0;

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

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

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

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

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

	/* Activate hooks */
	quit_aux = hook_quit;

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

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

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

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

		/* Prepare the colors */
		colortable[TERM_DARK]     = (COLOR_PAIR(PAIR_BLACK));
		colortable[TERM_WHITE]    = (COLOR_PAIR(PAIR_WHITE) | A_BRIGHT);
		colortable[TERM_SLATE]    = (COLOR_PAIR(PAIR_WHITE));
		colortable[TERM_ORANGE]   = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT);
		colortable[TERM_RED]      = (COLOR_PAIR(PAIR_RED));
		colortable[TERM_GREEN]    = (COLOR_PAIR(PAIR_GREEN));
		colortable[TERM_BLUE]     = (COLOR_PAIR(PAIR_BLUE));
		colortable[TERM_UMBER]    = (COLOR_PAIR(PAIR_YELLOW));
		colortable[TERM_L_DARK]   = (COLOR_PAIR(PAIR_BLACK) | A_BRIGHT);
		colortable[TERM_L_WHITE]  = (COLOR_PAIR(PAIR_WHITE));
		colortable[TERM_L_PURPLE] = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[TERM_YELLOW]   = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT);
		colortable[TERM_L_RED]    = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[TERM_L_GREEN]  = (COLOR_PAIR(PAIR_GREEN) | A_BRIGHT);
		colortable[TERM_L_BLUE]   = (COLOR_PAIR(PAIR_BLUE) | A_BRIGHT);
		colortable[TERM_L_UMBER]  = (COLOR_PAIR(PAIR_YELLOW));

		colortable[TERM_PURPLE]      = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[TERM_VIOLET]      = (COLOR_PAIR(PAIR_MAGENTA));
		colortable[TERM_TEAL]        = (COLOR_PAIR(PAIR_CYAN));
		colortable[TERM_MUD]         = (COLOR_PAIR(PAIR_YELLOW));
		colortable[TERM_L_YELLOW]    = (COLOR_PAIR(PAIR_YELLOW | A_BRIGHT));
		colortable[TERM_MAGENTA]     = (COLOR_PAIR(PAIR_MAGENTA | A_BRIGHT));
		colortable[TERM_L_TEAL]      = (COLOR_PAIR(PAIR_CYAN) | A_BRIGHT);
		colortable[TERM_L_VIOLET]    = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[TERM_L_PINK]      = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT);
		colortable[TERM_MUSTARD]     = (COLOR_PAIR(PAIR_YELLOW));
		colortable[TERM_BLUE_SLATE]  = (COLOR_PAIR(PAIR_BLUE));
		colortable[TERM_DEEP_L_BLUE] = (COLOR_PAIR(PAIR_BLUE));
	}
#endif

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

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

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

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

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

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

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

	/* Success */
	return (0);
}
Example #22
0
int main(int argc, char **argv)
{
	int opt, optind = 0;
	int ch = ERR;

	struct option lopts[] = {
		{ "help",          no_argument,       NULL, 'h' },
		{ "version",       no_argument,       NULL, 'V' },
		{ "networks",      no_argument,       NULL, 'n' },
		{ "repeat-header", no_argument,       NULL, 'r' },
		{ "vcpus",         no_argument,       NULL, 'v' },
		{ "delay",         required_argument, NULL, 'd' },
		{ 0, 0, 0, 0 },
	};
	const char *sopts = "hVbnvd:";

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

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

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

	/* Begin curses stuff */
	initscr();
	start_color();
	cbreak();
	noecho();
	nonl();
	keypad(stdscr, TRUE);
	halfdelay(5);
	use_default_colors();
	init_pair(1, -1, COLOR_YELLOW);

	do {
		gettimeofday(&curtime, NULL);
		if(ch != ERR || (curtime.tv_sec - oldtime.tv_sec) >= delay) {
			clear();
			top();
			oldtime = curtime;
			refresh();
		}
		ch = getch();
	} while (handle_key(ch));

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

	return 0;
}
Example #23
0
/*
==================
CON_Init

Initialize the console in curses mode, fall back to tty mode on failure
==================
*/
void CON_Init(void)
{
	int col;

#ifndef _WIN32
	// If the process is backgrounded (running non interactively)
	// then SIGTTIN or SIGTOU is emitted, if not caught, turns into a SIGSTP
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
#endif

	// Make sure we're on a tty
	if (isatty(STDIN_FILENO) != 1 || isatty(STDOUT_FILENO) != 1 || isatty(STDERR_FILENO) != 1) {
		CON_Init_tty();
		return;
	}

	// Initialize curses and set up the root window
	if (!curses_on) {
		SCREEN *test = newterm(NULL, stdout, stdin);
		if (!test) {
			CON_Init_tty();
			CON_Print_tty("Couldn't initialize curses, falling back to tty\n");
			return;
		}
		endwin();
		delscreen(test);
		initscr();
		cbreak();
		noecho();
		nonl();
		intrflush(stdscr, FALSE);
		nodelay(stdscr, TRUE);
		keypad(stdscr, TRUE);
		wnoutrefresh(stdscr);

		// Set up colors
		if (has_colors()) {
			use_default_colors();
			start_color();
			init_pair(1, COLOR_BLACK, -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, -1, -1);
		}
	}

	// Create the border
	borderwin = newwin(LOG_LINES + 2, LOG_COLS + 2, 1, 0);
	CON_SetColor(borderwin, 2);
	box(borderwin, 0, 0);
	wnoutrefresh(borderwin);

	// Create the log window
	logwin = newpad(MAX_LOG_LINES, LOG_COLS);
	scrollok(logwin, TRUE);
	idlok(logwin, TRUE);
	if (curses_on)
		CON_ColorPrint(logwin, logbuf, qtrue);
	getyx(logwin, lastline, col);
	if (col)
		lastline++;
	scrollline = lastline - LOG_LINES;
	if (scrollline < 0)
		scrollline = 0;
	pnoutrefresh(logwin, scrollline, 0, 2, 1, LOG_LINES + 1, LOG_COLS + 1);

	// Create the scroll bar
	scrollwin = newwin(LOG_LINES, 1, 2, COLS - 1);
	CON_DrawScrollBar();
	CON_SetColor(stdscr, 3);
	mvaddch(1, COLS - 1, SCRLBAR_UP);
	mvaddch(LINES - 2, COLS - 1, SCRLBAR_DOWN);

	// Create the input field
	inputwin = newwin(1, COLS - Q_PrintStrlen(PROMPT) - 8, LINES - 1, Q_PrintStrlen(PROMPT) + 8);
	input_field.widthInChars = COLS - Q_PrintStrlen(PROMPT) - 9;
	if (curses_on) {
		if (input_field.cursor < input_field.scroll)
			input_field.scroll = input_field.cursor;
		else if (input_field.cursor >= input_field.scroll + input_field.widthInChars)
			input_field.scroll = input_field.cursor - input_field.widthInChars + 1;
		CON_ColorPrint(inputwin, input_field.buffer + input_field.scroll, qfalse);
	}
	CON_UpdateCursor();
	wnoutrefresh(inputwin);

	// Create the clock
	clockwin = newwin(1, 8, LINES - 1, 0);
	CON_UpdateClock();

	// Display the title and input prompt
	move(0, (COLS - Q_PrintStrlen(TITLE)) / 2);
	CON_ColorPrint(stdscr, TITLE, qtrue);
	move(LINES - 1, 8);
	CON_ColorPrint(stdscr, PROMPT, qtrue);
	wnoutrefresh(stdscr);
	doupdate();

#ifndef _WIN32
	// Catch window resizes
	signal(SIGWINCH, (void *)CON_Resize);
#endif

	curses_on = qtrue;
}
Example #24
0
/***
Reserve `-1` to represent terminal default colors.
@function use_default_colors
@treturn bool `true`, if successful
@see use_default_colors(3x)
@fixme ncurses only?
*/
static int
Puse_default_colors(lua_State *L)
{
	return pushokresult(use_default_colors());
}
Example #25
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;
}
Example #26
0
void TheLife::LoadLife() {

    
    struct timespec start;
    struct timespec end;
    struct timespec diff;
    
    clock_gettime(CLOCK_MONOTONIC, &start);
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_BEGIN"));
    
    pthread_t main, status;

    //Life Initialization
    sUI->lwin[0].buf[0] = 0x00;
    sUI->lwin[1].buf[0] = 0x00;
    
    // Init NCurses
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_CURSES"));
    initscr();
    start_color();
    use_default_colors();
    //noecho();
    keypad(stdscr, true);

    // Init colors
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_COLOR"));
    init_pair(1, 1, -1);
    init_pair(2, 2, -1);
    init_pair(3, 3, -1);
    init_pair(4, 4, -1);

    // Init UI
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_UI"));
    Interface::Load();
    
    sUI->SetHidden(false, WINDOW_CONSOLE);
    sUI->SetHidden(false, WINDOW_STATUS);    
    
    // Init Player
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_PLAYER"));
    FileHandler::PlayerInit();

    // Init SIGWICH (Console change signal) to SigHandler
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_SIGWINCH"));
    signal(SIGWINCH, TheLife::SigHandler);
    
    // Thread spawning
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_TH_SPAWN"));
    pthread_create(&status, NULL, Thread::Status, NULL);
    pthread_create(&main, NULL, Thread::Run, NULL);
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_TH_ADD"));
    sThread->AddThread(status);
    sThread->AddThread(main);
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_TH_JOIN"));
    pthread_join(status,NULL);
    pthread_join(main, NULL);    
    
    LogHandler::WriteLog(sLanguage->Get("LOG_LOAD_END"));
    clock_gettime(CLOCK_MONOTONIC, &end);
    diff = diff_timespec(start, end);
    Debug("Load took %lld milliseconds\n", millisec_elapsed(diff));
}
Example #27
0
File: upshell.c Project: aiQon/UP3D
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;
}
static void display_window(TALLOC_CTX *mem_ctx, struct registry_context *ctx)
{
	struct regedit *regedit;
	struct tree_node *root;
	bool colors;
	int key;

	initscr();

	cbreak();
	noecho();

	fault_configure(regedit_panic_handler);

	colors = has_colors();
	if (colors) {
		start_color();
		use_default_colors();
		assume_default_colors(COLOR_WHITE, COLOR_BLUE);
		init_pair(PAIR_YELLOW_CYAN, COLOR_YELLOW, COLOR_CYAN);
		init_pair(PAIR_BLACK_CYAN, COLOR_BLACK, COLOR_CYAN);
		init_pair(PAIR_YELLOW_BLUE, COLOR_YELLOW, COLOR_BLUE);
	}

	regedit = talloc_zero(mem_ctx, struct regedit);
	SMB_ASSERT(regedit != NULL);
	regedit_main = regedit;

	regedit->registry_context = ctx;
	regedit->main_window = stdscr;
	keypad(regedit->main_window, TRUE);

	mvwprintw(regedit->main_window, 0, 0, "Path: ");
	regedit->path_label = newpad(1, PATH_WIDTH_MAX);
	SMB_ASSERT(regedit->path_label);
	wprintw(regedit->path_label, "/");
	show_path(regedit_main);

	root = tree_node_new_root(regedit, ctx);
	SMB_ASSERT(root != NULL);

	regedit->keys = tree_view_new(regedit, root, KEY_HEIGHT, KEY_WIDTH,
				      KEY_START_Y, KEY_START_X);
	SMB_ASSERT(regedit->keys != NULL);

	regedit->vl = value_list_new(regedit, VAL_HEIGHT, VAL_WIDTH,
				     VAL_START_Y, VAL_START_X);
	SMB_ASSERT(regedit->vl != NULL);

	regedit->tree_input = true;
	print_heading(regedit);

	tree_view_show(regedit->keys);
	load_values(regedit);
	value_list_show(regedit->vl);

	update_panels();
	doupdate();

	do {
		key = regedit_getch();

		handle_main_input(regedit, key);
		update_panels();
		doupdate();
	} while (key != 'q' || key == 'Q');

	endwin();
}