int main() { // Initial blocks uint8_t blocks[5][2] = { {2,1}, {3,5}, {4,5}, {4,6}, {9,8}}; // Initial start position uint8_t startx = WIDTH / 2; uint8_t starty = HEIGHT / 2; int readc = 0, quit = 0, playerid = PLAYER1; int textpos = 0; // Game area gamearea* game = new_gamearea(WIDTH,HEIGHT,5,blocks); // Player player* pl1 = new_player(playerid,startx,starty,HEALTH); initscr(); // Start ncurses noecho(); // Disable echoing of terminal input cbreak(); // Individual keystrokes intrflush(stdscr, FALSE); // Prevent interrupt flush keypad(stdscr,TRUE); // Allow keypad usage start_color(); // Initialize colors // Color pairs init_pair(colorpair id,foreground color, background color) init_pair(PLAYER1,PLAYER1,COLOR_BLACK); // Player1 = COLOR_RED (1) init_pair(PLAYER2,PLAYER2,COLOR_BLACK); // Player2 = COLOR_GREEN (2) init_pair(PLAYER3,PLAYER3,COLOR_BLACK); // Player3 = COLOR_YELLOW (3) init_pair(PLAYER4,PLAYER4,COLOR_BLACK); // Player4 = COLOR_BLUE (4) init_pair(PLAYER_HIT_COLOR,COLOR_RED,COLOR_YELLOW); init_pair(WALL_COLOR,COLOR_WHITE,COLOR_WHITE); // Prepare everything clear_log(); prepare_horizontal_line(WIDTH); ui_draw_grid(game, pl1); fd_set readfs; int rval = 0; while(1) { FD_ZERO(&readfs); FD_SET(fileno(stdin),&readfs); // Block until we have something if((rval = select(fileno(stdin)+1,&readfs,NULL,NULL,NULL)) > 0) { // From user if(FD_ISSET(fileno(stdin),&readfs)) { readc = getch(); // Get each keypress pl1->hitwall = 0; switch(readc) { case KEY_LEFT: if(is_position_a_wall(game,pl1->posx-1,pl1->posy)) pl1->hitwall = 1; else pl1->posx--; break; case KEY_RIGHT: if(is_position_a_wall(game,pl1->posx+1,pl1->posy)) pl1->hitwall = 1; else pl1->posx++; break; case KEY_UP: if(is_position_a_wall(game,pl1->posx,pl1->posy-1)) pl1->hitwall = 1; else pl1->posy--; break; case KEY_DOWN: if(is_position_a_wall(game,pl1->posx,pl1->posy+1)) pl1->hitwall = 1; else pl1->posy++; break; // Function keys, here F1 is reacted to case KEY_F(1): status = status ^ 1; break; case 27: // Escape key quit = 1; break; case '/': // User wants to write something memset(&textbuffer,0,BUFFER); textinput = 1; textpos = 0; break; // Erase text case KEY_BACKSPACE: case KEY_DC: textpos--; textbuffer[textpos] = '\0'; break; // Push the line to log with enter case KEY_ENTER: case '\n': textinput = 0; if(strlen(textbuffer) > 0) add_log(textbuffer,textpos); textpos = 0; memset(&textbuffer,0,BUFFER); break; // Add the character to textbuffer if we were inputting text default: if(textinput == 1) { textbuffer[textpos] = readc; textpos++; if(textpos == BUFFER-1) { textpos = 0; textinput = 0; } } break; } } } // Hit a wall, change player if(pl1->hitwall) { pl1->health--; if(pl1->id == PLAYER4) pl1->id = PLAYER1; else pl1->id++; } // Update screen ui_draw_grid(game, pl1); // Suicide if(pl1->health == 0) { ui_draw_end(1); break; } // Surrended if(quit) { ui_draw_end(0); break; } } free_gamearea(game); free_player(pl1); free_horizontal_line(); sleep(1); endwin(); // End ncurses return 0; }
bool Display::Open() { // Open curses screen=initscr(); if (screen==NULL) { std::cerr << "Cannot initialize curses" << std::endl; return false; } #ifdef NCURSES_MOUSE_VERSION mousemask(BUTTON1_PRESSED| BUTTON1_RELEASED/*| BUTTON1_CLICKED| BUTTON1_DOUBLE_CLICKED| BUTTON1_TRIPLE_CLICKED*/,NULL); #endif // Check availibility of colors colorDepth=1; colorMode=colorModeMonochrome; if (has_colors() && start_color()!=ERR && COLORS>=8) { colorMode=colorModeColor; colorDepth=4; } // Basic curses initialisation curs_set(0); noecho(); cbreak(); nonl(); raw(); //Images::Factory::Set(OS::Factory::factory->CreateImageFactory(this)); screenWidth=COLS; screenHeight=LINES; workAreaWidth=screenWidth; workAreaHeight=screenHeight; type=typeTextual; EvaluateDisplaySize(); for (int c=1; c<COLOR_PAIRS; c++) { if (init_pair(c,c%COLORS,c/COLORS)==ERR) { std::cerr << c << " " << c%COLORS << " " << c/COLORS << std::endl; std::cerr << "Cannot initialize terminal color pairs" << std::endl; colorDepth=1; colorMode=colorModeMonochrome; break; } } propFont=driver->CreateFont(); propFont=propFont->Load(); propFontSize=1; fixedFont=driver->CreateFont(); fixedFont=fixedFont->Load(); fixedFontSize=1; theme=new Theme(this); for (size_t i=0; i<colorCount; i++) { color[i]=theme->GetColor((ColorIndex)i); } multiClickTime=200; eventLoop=new UnixEventLoop(); eventLoop->AddSource(new CursesEventSource(this)); return true; }
void do_start_color(state *st) { encode_ok_reply(st, start_color()); }
static int dialog_run (pinentry_t pinentry, const char *tty_name, const char *tty_type) { struct dialog diag; FILE *ttyfi = NULL; FILE *ttyfo = NULL; SCREEN *screen = 0; int done = 0; char *pin_utf8; int alt = 0; #ifndef HAVE_DOSISH_SYSTEM int no_input = 1; #endif #ifdef HAVE_NCURSESW char *old_ctype = NULL; if (pinentry->lc_ctype) { old_ctype = strdup (setlocale (LC_CTYPE, NULL)); setlocale (LC_CTYPE, pinentry->lc_ctype); } else setlocale (LC_CTYPE, ""); #endif /* Open the desired terminal if necessary. */ if (tty_name) { ttyfi = fopen (tty_name, "r"); if (!ttyfi) { pinentry->specific_err = ASSUAN_ENOENT; return -1; } ttyfo = fopen (tty_name, "w"); if (!ttyfo) { int err = errno; fclose (ttyfi); errno = err; pinentry->specific_err = ASSUAN_ENOENT; return -1; } screen = newterm (tty_type, ttyfo, ttyfi); set_term (screen); } else { if (!init_screen) { if (!(isatty(fileno(stdin)) && isatty(fileno(stdout)))) { errno = ENOTTY; pinentry->specific_err = ASSUAN_ENOTTY; return -1; } init_screen = 1; initscr (); } else clear (); } 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 (); /* Don't echo input - in color. */ if (has_colors ()) { start_color (); #ifdef NCURSES_VERSION use_default_colors (); #endif if (pinentry->color_so == PINENTRY_COLOR_DEFAULT) { pinentry->color_so = PINENTRY_COLOR_RED; pinentry->color_so_bright = 1; } if (COLOR_PAIRS >= 2) { init_pair (1, pinentry_color[pinentry->color_fg], pinentry_color[pinentry->color_bg]); init_pair (2, pinentry_color[pinentry->color_so], pinentry_color[pinentry->color_bg]); bkgd (COLOR_PAIR (1)); attron (COLOR_PAIR (1) | (pinentry->color_fg_bright ? A_BOLD : 0)); } } refresh (); /* Create the dialog. */ if (dialog_create (pinentry, &diag)) { /* Note: pinentry->specific_err has already been set. */ endwin (); if (screen) delscreen (screen); #ifdef HAVE_NCURSESW if (old_ctype) { setlocale (LC_CTYPE, old_ctype); free (old_ctype); } #endif if (ttyfi) fclose (ttyfi); if (ttyfo) fclose (ttyfo); return -2; } dialog_switch_pos (&diag, diag.pinentry->pin ? DIALOG_POS_PIN : DIALOG_POS_OK); #ifndef HAVE_DOSISH_SYSTEM wtimeout (stdscr, 70); #endif do { int c; c = wgetch (stdscr); /* Refresh, accept single keystroke of input. */ #ifndef HAVE_DOSISH_SYSTEM if (timed_out && no_input) { done = -2; break; } #endif switch (c) { case ERR: #ifndef HAVE_DOSISH_SYSTEM continue; #else done = -2; break; #endif case 27: /* Alt was pressed. */ alt = 1; /* Get the next key press. */ continue; case KEY_LEFT: case KEY_UP: switch (diag.pos) { case DIALOG_POS_OK: if (diag.pinentry->pin) dialog_switch_pos (&diag, DIALOG_POS_PIN); break; case DIALOG_POS_NOTOK: dialog_switch_pos (&diag, DIALOG_POS_OK); break; case DIALOG_POS_CANCEL: if (diag.notok) dialog_switch_pos (&diag, DIALOG_POS_NOTOK); else dialog_switch_pos (&diag, DIALOG_POS_OK); break; default: break; } break; case KEY_RIGHT: case KEY_DOWN: switch (diag.pos) { case DIALOG_POS_PIN: dialog_switch_pos (&diag, DIALOG_POS_OK); break; case DIALOG_POS_OK: if (diag.notok) dialog_switch_pos (&diag, DIALOG_POS_NOTOK); else dialog_switch_pos (&diag, DIALOG_POS_CANCEL); break; case DIALOG_POS_NOTOK: dialog_switch_pos (&diag, DIALOG_POS_CANCEL); break; default: break; } break; case '\t': switch (diag.pos) { case DIALOG_POS_PIN: dialog_switch_pos (&diag, DIALOG_POS_OK); break; case DIALOG_POS_OK: if (diag.notok) dialog_switch_pos (&diag, DIALOG_POS_NOTOK); else dialog_switch_pos (&diag, DIALOG_POS_CANCEL); break; case DIALOG_POS_NOTOK: dialog_switch_pos (&diag, DIALOG_POS_CANCEL); break; case DIALOG_POS_CANCEL: if (diag.pinentry->pin) dialog_switch_pos (&diag, DIALOG_POS_PIN); else dialog_switch_pos (&diag, DIALOG_POS_OK); break; default: break; } break; case '\005': done = -2; break; case '\r': switch (diag.pos) { case DIALOG_POS_PIN: case DIALOG_POS_OK: done = 1; break; case DIALOG_POS_NOTOK: done = -1; break; case DIALOG_POS_CANCEL: done = -2; break; case DIALOG_POS_NONE: break; } break; default: if (diag.pos == DIALOG_POS_PIN) dialog_input (&diag, alt, c); } #ifndef HAVE_DOSISH_SYSTEM no_input = 0; #endif if (c != -1) alt = 0; } while (!done); if (diag.pinentry->pin) /* NUL terminate the passphrase. dialog_run makes sure there is enough space for the terminating NUL byte. */ diag.pinentry->pin[diag.pin_len] = 0; set_cursor_state (1); endwin (); if (screen) delscreen (screen); #ifdef HAVE_NCURSESW if (old_ctype) { setlocale (LC_CTYPE, old_ctype); free (old_ctype); } #endif if (ttyfi) fclose (ttyfi); if (ttyfo) fclose (ttyfo); /* XXX Factor out into dialog_release or something. */ free (diag.ok); if (diag.cancel) free (diag.cancel); if (diag.notok) free (diag.notok); if (pinentry->pin) { pinentry->locale_err = 1; pin_utf8 = pinentry_local_to_utf8 (pinentry->lc_ctype, pinentry->pin, 1); if (pin_utf8) { pinentry_setbufferlen (pinentry, strlen (pin_utf8) + 1); if (pinentry->pin) strcpy (pinentry->pin, pin_utf8); secmem_free (pin_utf8); pinentry->locale_err = 0; } } if (done == -2) pinentry->canceled = 1; if (diag.pinentry->pin) return done < 0 ? -1 : diag.pin_len; else return done < 0 ? 0 : 1; }
void *mode4_init(void *aldl_in) { aldl = (aldl_conf_t *)aldl_in; /* sanity check pcm address to avoid using this with wrong ecm */ if(aldl->comm->pcm_address != 0xF4) { error(EFATAL, ERROR_PLUGIN, "MODE4 Special plugin is for EE only."); }; /* allocate main message buffer for log entries */ msgbuf = malloc(sizeof(char) * MSGBUFSIZE); /* initialize root window */ WINDOW *root; if((root = initscr()) == NULL) { error(1,ERROR_NULL,"could not init ncurses"); } curs_set(0); /* remove cursor */ cbreak(); /* dont req. line break for input */ nodelay(root,true); /* non-blocking input */ noecho(); /* configure colors (even though this doesn't use much color) */ start_color(); init_pair(RED_ON_BLACK,COLOR_RED,COLOR_BLACK); init_pair(BLACK_ON_RED,COLOR_BLACK,COLOR_RED); init_pair(GREEN_ON_BLACK,COLOR_GREEN,COLOR_BLACK); init_pair(CYAN_ON_BLACK,COLOR_CYAN,COLOR_BLACK); init_pair(WHITE_ON_BLACK,COLOR_WHITE,COLOR_BLACK); init_pair(WHITE_ON_RED,COLOR_WHITE,COLOR_RED); /* fetch indexes (saves repeated lookups) */ p_idx.rpm = get_index_by_name(aldl,"RPM"); p_idx.idletarget = get_index_by_name(aldl,"IDLESPD"); p_idx.iacsteps = get_index_by_name(aldl,"IAC"); p_idx.cooltemp = get_index_by_name(aldl,"COOLTMP"); p_idx.map = get_index_by_name(aldl,"MAP"); p_idx.adv = get_index_by_name(aldl,"ADV"); p_idx.kr = get_index_by_name(aldl,"KR"); /* get initial screen size */ getmaxyx(stdscr,w_height,w_width); /* wait for connection */ m4_cons_wait_for_connection(); /* prepare 'empty' mode4 command */ m4_comm_init(); while(1) { /* get newest record */ rec = newest_record_wait(aldl,rec); if(rec == NULL) { /* disconnected */ m4_cons_wait_for_connection(); continue; } /* process engine status */ get_engine_status(); erase(); /* clear screen --------- */ mvprintw(0,1,M4_USE_STRING); /* print usage */ /* print eng status */ mvprintw(2,1,"%s",print_engine_status()); m4_commrev = 0; /* reset revision bit. input handler may set it */ m4_consoleif_handle_input(); /* get keyboard input and branch */ #ifdef M4_PRINT_HEX /* print the m4 string in hex for debug */ m4_draw_cmd(1,1); #endif if(m4_commrev == 1) { /* send command if revised */ m4_comm_submit(); } refresh(); usleep(500); } sleep(4); delwin(root); endwin(); refresh(); pthread_exit(NULL); return NULL; }
int main() { gw.begin(); //uint8_t nodeID = 22; //gw.begin(nodeID,3,RF24_2MBPS); //uint16_t address = 0; //gw.begin(address,3,RF24_2MBPS); /** Setup NCurses**/ /*******************************/ win = initscr(); cbreak(); noecho(); getmaxyx(win,maxX,maxY); start_color(); curs_set(0); init_pair(1, COLOR_GREEN, COLOR_BLACK); init_pair(2, COLOR_RED, COLOR_BLACK); /** Setup Pads**/ /*******************************/ devPad = newpad(11,40); meshPad = newpad(11,50); rf24Pad = newpad(11,40); connPad = newpad(21,150); cfgPad = newpad(10,40); scrollok(meshPad,true); scrollok(connPad,true); scrollok(rf24Pad,true); timeout(0); drawMain(); /******************************************************************/ /***********************LOOP***************************************/ while(1){ //delayMicroseconds(5000); //delay(1); /** * The gateway handles all IP traffic (marked as EXTERNAL_DATA_TYPE) and passes it to the associated network interface * RF24Network user payloads are loaded into the user cache */ gw.update(); /** Read RF24Network Payloads (Do nothing with them currently) **/ /*******************************/ if( network.available() ){ RF24NetworkHeader header; size_t size = network.peek(header); uint8_t buf[size]; if(header.type == 1){ struct timeStruct{ uint8_t hr; uint8_t min; }myTime; time_t mTime; time(&mTime); struct tm* tm = localtime(&mTime); myTime.hr = tm->tm_hour; myTime.min = tm->tm_min; RF24NetworkHeader hdr(header.from_node,1); network.write(hdr,&myTime,sizeof(myTime)); } network.read(header,&buf,size); } /** Mesh address/id printout **/ /*******************************/ if(millis() - meshInfoTimer > updateRate){ getmaxyx(win,maxX,maxY); // Draw the pads on screen drawDevPad(); prefresh(devPad,0,0, 4,1, 15,25); drawMeshPad(); wscrl(meshPad,meshScroll); prefresh(meshPad,0,0, 4,26, 15,47); drawRF24Pad(); prefresh(rf24Pad,0,0, 4,51, 15, 73); if(showConnPad){ drawConnPad(); wscrl(connPad,connScroll); prefresh(connPad,0,0, 15,1, maxX-1,maxY-2); } } //MeshInfo Timer /** Handle keyboard input **/ /*******************************/ int myChar; if ( (myChar = getch()) == '\033') { getch(); switch(getch()){ case 'A': if(padSelection == 0){meshScroll++;}else if(padSelection == 1){connScroll++;} break; case 'B': if(padSelection == 0){meshScroll--;}else if(padSelection == 1){connScroll--;} break; case 'C': padSelection++; padSelection= std::min(padSelection,1); break; //right case 'D': padSelection--; padSelection= std::max(padSelection,0); break; //left } meshScroll = std::max(meshScroll,0); connScroll = std::max(connScroll,0); meshInfoTimer = 0; }else if(myChar > -1){ switch(myChar){ // a: En/Disable display of active connections case 'a' : showConnPad = !showConnPad; if(!showConnPad){ wclear(connPad); prefresh(connPad,0,0, 15,1, maxX-1,maxY-2); drawMain();} break; // w: Increase frame-rate of curses display case 'w' : if(updateRate > 100){updateRate-=100;} mvwprintw(win,2,27,"Refresh Rate: %.1f fps",1000.0/updateRate); refresh(); break; // s: Decrease frame-rate of curses display case 's' : updateRate+=100; mvwprintw(win,2,27,"Refresh Rate: %.1f fps \t",1000.0/updateRate); refresh(); break; // c: Display IP configuration menu case 'c' : drawCfg(1); break; // h: Display help menu case 'h' : drawHelp(); break; case 'x' : clear(); endwin(); return 0; break; } } delay(2); }//while 1 //delwin(meshPad); //delwin(connPad); clear(); endwin(); return 0; }//main
int main(int argc, char **argv){ int c; int colouron = 0; char *fslist = NULL; time_t last_update = 0; extern int errno; int delay=2; sg_log_init("saidar", "SAIDAR_LOG_PROPERTIES", argc ? argv[0] : NULL); sg_init(1); 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:F:cvh")) != -1){ #else while ((c = getopt(argc, argv, "d:F: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; } } if (fslist) { sg_error rc = set_valid_filesystems(fslist); if(rc != SG_ERROR_NONE) die(sg_str_error(rc)); free(fslist); } else { sg_error rc = set_valid_filesystems("!nfs, nfs3, nfs4, cifs, smbfs, samba, autofs"); if(rc != SG_ERROR_NONE) die(sg_str_error(rc)); } 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); 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(); sg_shutdown(); return 0; }
void Number (int argc, char **argv) { initscr (); noecho (); start_color (); clear (); refresh (); init_pair (1, COLOR_RED, COLOR_BLACK); init_pair (2, COLOR_GREEN, COLOR_BLACK); init_pair (3, COLOR_YELLOW, COLOR_BLACK); init_pair (4, COLOR_BLUE, COLOR_BLACK); init_pair (5, COLOR_MAGENTA, COLOR_BLACK); init_pair (6, COLOR_CYAN, COLOR_BLACK); init_pair (7, COLOR_WHITE, COLOR_BLACK); srand (time (NULL)); for (int count = 0; count < atoi ((argc == 2) ? argv [1] : "5"); count++) { for (int r = 0, l = LINES - 1; r < LINES && l >= 0; r++, l--) { for (int c = 0; c < COLS; c += 2) { attrset (A_BOLD | COLOR_PAIR (1 + rand () % 8)); mvprintw (l, c + 1, "%i", rand () % 10); attrset (A_NORMAL); attrset (A_BOLD | COLOR_PAIR (1 + rand () % 8)); mvprintw (r, c, "%i", rand () % 10); attrset (A_NORMAL); } move (LINES / 2, COLS / 2); refresh (); } for (int c = 0, v = COLS - 1; c < COLS && v >= 0; c++, v--) { for (int r = 0; r < LINES; r += 2) { mvaddch (r, c, ' '); mvaddch (r + 1, v, ' '); } move (LINES / 2, COLS / 2); refresh (); } for (int c = 0, v = COLS - 1; c < COLS && v >= 0; c++, v--) { for (int r = 0; r < LINES; r += 2) { attrset (A_BOLD | COLOR_PAIR (1 + rand () % 8)); mvprintw (r, c, "%i", rand () % 2); attrset (A_NORMAL); attrset (A_BOLD | COLOR_PAIR (1 + rand () % 8)); mvprintw (r + 1, v, "%i", rand () % 2); attrset (A_NORMAL); } move (LINES / 2, COLS / 2); refresh (); } for (int r = 0, l = LINES - 1; r < LINES && l >= 0; r++, l--) { for (int c = 0; c < COLS; c += 2) { mvaddch (l, c + 1, ' '); mvaddch (r, c, ' '); } move (LINES / 2, COLS / 2); refresh (); } } move (LINES - 1, COLS - 1); clear (); refresh (); endwin (); }
int main(int argc, char* argv[]) { init_console(); // do this FIRST //start curses initscr(); gamelog.initialize(GAMELOG_FILEPATH, OVERWRITE_GAMELOG, NEWLINEMODE_GAMELOG); //Initialize the gamelog (and also initialize artdir and homedir) time_t t = time(0); struct tm *now = localtime(&t); //Do not need to deallocate this. Statically allocated by system char datetime[41]; sprintf(datetime, "---------%i-%02i-%02i %02i:%02i:%02i---------\n\n\n", now->tm_year+1900, now->tm_mon+1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); //YYYY-MM-DD HH:MM:SS format gamelog.log(string("\n\n\n---------- PROGRAM STARTED ----------\n") + datetime); char file_name[13]; FILE *file; music.play(MUSIC_TITLEMODE); // initialize music and play title mode song (do this BEFORE displaying anything on the screen, but AFTER initializing artdir and homedir) // set window title char wtitle[50]; strcpy(wtitle,"Liberal Crime Squad "); strcat(wtitle,PACKAGE_VERSION); set_title(wtitle); noecho(); //initialize curses color start_color(); initMainRNG(); //initialize the array of color pairs for(int i=0;i<8;i++) for(int j=0;j<8;j++) { if(i==0&&j==0) { init_pair(7*8,0,0); continue; } if(i==7&&j==0) continue; init_pair(i*8+j,i,j); } //turns off cursor curs_set(0); //begin the game loop keypad(stdscr,TRUE); raw_output(TRUE); //addstr("Loading Graphics... "); //getkey(); loadgraphics(); //addstr("Loading Init File Options... "); //getkey(); loadinitfile(); //addstr("Loading sitemaps.txt... "); //getkey(); oldMapMode=!readConfigFile("sitemaps.txt"); // load site map data if(oldMapMode) { addstr("Failed to load sitemaps.txt! Reverting to old map mode.",gamelog); gamelog.nextMessage(); getkey(); } //move(1,0); //addstr("Setting initial game data... "); //getkey(); strcpy(slogan,"We need a slogan!"); if(!LCSrandom(20)) { switch(LCSrandom(7)) { case 0: strcpy(slogan,"To Rogues and Revolution!"); break; case 1: strcpy(slogan,"Hell yes, LCS!"); break; case 2: strcpy(slogan,"Striking high, standing tall!"); break; case 3: strcpy(slogan,"Revolution never comes with a warning!"); break; case 4: strcpy(slogan,"True Liberal Justice!"); break; case 5: strcpy(slogan,"Laissez ain't fair!"); break; case 6: strcpy(slogan,"This is a slogan!"); break; } } //Initialize sorting choices. for(int s=0;s<SORTINGCHOICENUM;s++) activesortingchoice[s]=SORTING_NONE; for(int v=0;v<VIEWNUM;v++) { attitude[v]=30+LCSrandom(25); public_interest[v]=0; background_liberal_influence[v]=0; } attitude[VIEW_LIBERALCRIMESQUAD]=0; attitude[VIEW_LIBERALCRIMESQUADPOS]=5; //attitude[VIEW_POLITICALVIOLENCE]=5; #ifdef REVOLUTIONNOW for(int v=0;v<VIEWNUM;v++) attitude[v]=100; #endif law[LAW_ABORTION]=1; law[LAW_ANIMALRESEARCH]=-1; law[LAW_POLICEBEHAVIOR]=-1; law[LAW_PRIVACY]=-1; law[LAW_DEATHPENALTY]=-1; law[LAW_NUCLEARPOWER]=-1; law[LAW_POLLUTION]=-1; law[LAW_LABOR]=0; law[LAW_GAY]=1; law[LAW_CORPORATE]=0; law[LAW_FREESPEECH]=0; law[LAW_FLAGBURNING]=1; law[LAW_GUNCONTROL]=-1; law[LAW_TAX]=0; law[LAW_WOMEN]=1; law[LAW_CIVILRIGHTS]=1; law[LAW_DRUGS]=-1; law[LAW_IMMIGRATION]=0; law[LAW_ELECTIONS]=0; law[LAW_MILITARY]=-1; law[LAW_PRISONS]=0; law[LAW_TORTURE]=-1; #ifdef SHITLAWS for(int l=0;l<LAWNUM;l++) law[l]=-2; #endif #ifdef PERFECTLAWS for(int l=0;l<LAWNUM;l++) law[l]=2; #endif for(int s=0;s<SENATENUM;s++) { if(s<25) senate[s]=-2; else if(s<60) senate[s]=-1; else if(s<80) senate[s]=0; else if(s<95) senate[s]=1; else senate[s]=2; } for(int h=0;h<HOUSENUM;h++) { if(h<50) house[h]=-2; else if(h<250) house[h]=-1; else if(h<350) house[h]=0; else if(h<400) house[h]=1; else house[h]=2; } for(int c=0;c<COURTNUM;c++) { if(c<3) court[c]=-2; else if(c<5) court[c]=-1; else if(c<5) court[c]=0; else if(c<8) court[c]=1; else court[c]=2; do { if(court[c]==-2) generate_name(courtname[c],GENDER_WHITEMALEPATRIARCH); else generate_name(courtname[c]); } while(len(courtname[c])>20); } for(int e=0;e<EXECNUM;e++) { exec[e]=-2; generate_name(execname[e],GENDER_WHITEMALEPATRIARCH); } initOtherRNG(attorneyseed); strcpy(lcityname,cityname()); xmllog.initialize("xmllog",true,1); bool xml_loaded_ok = true; xml_loaded_ok&=populate_from_xml(vehicletype,"vehicles.xml",xmllog); xml_loaded_ok&=populate_from_xml(cliptype,"clips.xml",xmllog); xml_loaded_ok&=populate_from_xml(weapontype,"weapons.xml",xmllog); xml_loaded_ok&=populate_from_xml(armortype,"armors.xml",xmllog); xml_loaded_ok&=populate_masks_from_xml(armortype,"masks.xml",xmllog); xml_loaded_ok&=populate_from_xml(loottype,"loot.xml",xmllog); xml_loaded_ok&=populate_from_xml(creaturetype,"creatures.xml",xmllog); xml_loaded_ok&=populate_from_xml(augmenttype,"augmentations.xml",xmllog); if(!xml_loaded_ok) end_game(EXIT_FAILURE); //addstr("Attempting to load saved game... "); //getkey(); //addstr("Setup complete!"); //getkey(); clear(); mode_title(); //deinitialize curses end_game(); return EXIT_SUCCESS; }
int main (int argc, char** argv) { const char* default_port = "23"; struct sigaction sa; int i; /* process command line args */ for (i = 1; i < argc; ++i) { /* help */ if (strcmp(argv[i], "-h") == 0) { printf( "CLC %s by Sean Middleditch <*****@*****.**>\n" "This program has been released into the PUBLIC DOMAIN.\n\n" "Usage:\n" " clc [-h] <host> [<port>]\n\n" "Options:\n" " -h display help\n", CLC_VERSION ); return 0; } /* other unknown option */ if (argv[i][0] == '-') { fprintf(stderr, "Unknown option %s.\nUse -h to see available options.\n", argv[i]); exit(1); } /* if host is unset, this is the host */ if (host == NULL) { host = argv[i]; /* otherwise, it's a port */ } else { port = argv[i]; } } /* ensure we have a host */ if (host == NULL) { fprintf(stderr, "No host was given.\nUse -h to see command format.\n"); exit(1); } /* set default port if none was given */ if (port == NULL) port = default_port; /* cleanup on any failure */ atexit(cleanup); /* set terminal defaults */ memset(&terminal, 0, sizeof(struct TERMINAL)); terminal.state = TERM_ASCII; terminal.flags = TERM_FLAGS_DEFAULT; terminal.color = TERM_COLOR_DEFAULT; /* initial telnet handler */ telnet = telnet_init(telnet_telopts, telnet_event, 0, 0); /* connect to server */ sock = do_connect(host, port); if (sock == -1) { fprintf(stderr, "Failed to connect to %s:%s\n", host, port); exit(1); } printf("Connected to %s:%s\n", host, port); /* set initial banner */ snprintf(banner, sizeof(banner), "CLC - %s:%s (connected)", host, port); /* configure curses */ initscr(); start_color(); nonl(); cbreak(); noecho(); win_main = newwin(LINES-2, COLS, 0, 0); win_banner = newwin(1, COLS, LINES-2, 0); win_input = newwin(1, COLS, LINES-1, 0); idlok(win_main, TRUE); scrollok(win_main, TRUE); nodelay(win_input, FALSE); keypad(win_input, TRUE); use_default_colors(); init_pair(COLOR_RED, COLOR_RED, -1); init_pair(COLOR_BLUE, COLOR_BLUE, -1); init_pair(COLOR_GREEN, COLOR_GREEN, -1); init_pair(COLOR_CYAN, COLOR_CYAN, -1); init_pair(COLOR_MAGENTA, COLOR_MAGENTA, -1); init_pair(COLOR_YELLOW, COLOR_YELLOW, -1); init_pair(COLOR_WHITE, COLOR_WHITE, -1); init_pair(TERM_COLOR_DEFAULT, -1, -1); wbkgd(win_main, COLOR_PAIR(TERM_COLOR_DEFAULT)); wclear(win_main); init_pair(10, COLOR_WHITE, COLOR_BLUE); wbkgd(win_banner, COLOR_PAIR(10)); wclear(win_banner); init_pair(11, -1, -1); wbkgd(win_input, COLOR_PAIR(11)); wclear(win_input); redraw_display(); /* set signal handlers */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = handle_signal; sigaction(SIGINT, &sa, NULL); sigaction(SIGWINCH, &sa, NULL); /* initial edit buffer */ memset(&editbuf, 0, sizeof(struct EDITBUF)); /* setup poll info */ struct pollfd fds[2]; fds[0].fd = 1; fds[0].events = POLLIN; fds[1].fd = sock; fds[1].events = POLLIN; /* main loop */ while (running) { /* poll sockets */ if (poll(fds, 2, -1) == -1) { if (errno != EAGAIN && errno != EINTR) { endwin(); fprintf(stderr, "poll() failed: %s\n", strerror(errno)); return 1; } } /* resize event? */ if (have_sigwinch) { have_sigwinch = 0; redraw_display(); } /* escape? */ if (have_sigint) { exit(0); } /* input? */ if (fds[0].revents & POLLIN) { int key = wgetch(win_input); if (key != ERR) on_key(key); } /* process input data */ if (fds[1].revents & POLLIN) { char buffer[2048]; int ret = recv(sock, buffer, sizeof(buffer), 0); if (ret == -1) { if (errno != EAGAIN && errno != EINTR) { endwin(); fprintf(stderr, "recv() failed: %s\n", strerror(errno)); return 1; } } else if (ret == 0) { running = 0; } else { recv_bytes += ret; telnet_recv(telnet, buffer, ret); } } /* flush output */ paint_banner(); wnoutrefresh(win_main); wnoutrefresh(win_banner); wnoutrefresh(win_input); doupdate(); } /* final display, pause */ sock = -1; autobanner = 1; paint_banner(); wnoutrefresh(win_banner); doupdate(); wgetch(win_input); /* clean up */ endwin(); printf("Disconnected.\n"); /* free memory (so Valgrind leak detection is useful) */ telnet_free(telnet); return 0; }
void StartColor() { Check(start_color(), "start_color"); }
/** Start things related to the game screen and layout */ int engine_screen_init(int width, int height) { engine.screen.width = width; engine.screen.height = height; /* Starting ncurses! */ initscr(); if ((has_colors() == TRUE) && (global.screen_use_colors)) { start_color(); /* This is a big hack to initialize all possible colors * in ncurses. The thing is, all colors are between * COLOR_BLACK and COLOR_WHITE. * Since I've set a large number of enums covering * all possibilities, I can do it all in a for loop. * Check 'man init_pair' for more details. * * This was taken straight from <curses.h>: * * #define COLOR_BLACK 0 * #define COLOR_RED 1 * #define COLOR_GREEN 2 * #define COLOR_YELLOW 3 * #define COLOR_BLUE 4 * #define COLOR_MAGENTA 5 * #define COLOR_CYAN 6 * #define COLOR_WHITE 7 */ int i, j, k = 1; for (i = (COLOR_BLACK); i <= (COLOR_WHITE); i++) { for (j = (COLOR_BLACK); j <= (COLOR_WHITE); j++) { init_pair(k, i, j); k++; } } /* Now we're able to get the user's current background and * use it on the game. That's what the `-1` means over there. * Better than forcing black, right? */ if ((global.screen_use_default_background) && (use_default_colors() != ERR)) { init_pair(BLACK_BLACK, COLOR_BLACK, -1); init_pair(RED_BLACK, COLOR_RED, -1); init_pair(GREEN_BLACK, COLOR_GREEN, -1); init_pair(YELLOW_BLACK, COLOR_YELLOW, -1); init_pair(BLUE_BLACK, COLOR_BLUE, -1); init_pair(MAGENTA_BLACK, COLOR_MAGENTA, -1); init_pair(CYAN_BLACK, COLOR_CYAN, -1); init_pair(WHITE_BLACK, COLOR_WHITE, -1); } } /* Gets the current width and height */ int current_height, current_width; getmaxyx(stdscr, current_height, current_width); if ((current_width < engine.screen.width) || (current_height < engine.screen.height)) { endwin(); fprintf(stderr, "Error! Your console screen is smaller than %dx%d\n" "Please resize your window and try again\n", engine.screen.width, engine.screen.height); exit(EXIT_FAILURE); } engine.screen.width = current_width; engine.screen.height = current_height; cbreak(); /* Character input doesnt require the <enter> key anymore */ curs_set(0); /* Makes the blinking cursor invisible */ noecho(); /* Wont print the keys received through input */ nodelay(stdscr, TRUE); /* Wont wait for input */ keypad(stdscr, TRUE); /* Support for extra keys (life F1, F2, ... ) */ refresh(); /* Refresh the screen (prints whats in the screen buffer) */ return 1; }
int main(int argc, char *argv[]) { if (argc != 10 || !strncmp(argv[1],"-h",2)) { puts("DrawLineSegment: Prints a line through two given points"); puts("USAGE: ./DrawLineSegment x"); return 0; } initscr(); /* Start curses mode */ raw(); /* Line buffering disabled */ noecho(); /* Don't echo() while we do getch */ start_color(); /* Start color */ init_pair(1, COLOR_RED, COLOR_RED); init_pair(2, COLOR_BLUE, COLOR_BLUE); attron(COLOR_PAIR(1)); curs_set(0); double x1 = atof(argv[1]); double y1 = atof(argv[2]); double x2 = atof(argv[3]); double y2 = atof(argv[4]); double x3 = atof(argv[5]); double y3 = atof(argv[6]); double x4 = atof(argv[7]); double y4 = atof(argv[8]); Pair mid1 = midPoint(x1,y1,x2,y2); Pair mid2 = midPoint(x3,y3,x4,y4); Pair mid = midPoint(mid1.x,mid1.y,mid2.x,mid2.y); Pair rpoint1; Pair rpoint2; Pair rpoint3; Pair rpoint4; for (int i = 0; i < 1080; i++) { rpoint1 = rotateDPoint(mid.x,mid.y,x1,y1,i); rpoint2 = rotateDPoint(mid.x,mid.y,x2,y2,i); rpoint3 = rotateDPoint(mid.x,mid.y,x3,y3,i); rpoint4 = rotateDPoint(mid.x,mid.y,x4,y4,i); //draw the starting line //draw the midpoint attron(COLOR_PAIR(2)); drawPair(mid); //draw rotated about the middle point attron(COLOR_PAIR(1)); drawQuadrilateral(rpoint1.x,rpoint1.y, rpoint2.x,rpoint2.y, rpoint3.x,rpoint3.y, rpoint4.x,rpoint4.y); //draw the shape refresh(); /* Print it on to the real screen */ //sleep() wasn't working too well for me for (int j = 0; j <= atol(argv[5])*10000; j++); clear(); } getch(); /* Wait for user input */ endwin(); /* End curses mode */ return 0; }
void sfm_ncurses(void) { int x; sfm_ncurses_win *iface = malloc(sizeof(sfm_ncurses_win)); char root_items[FILENAME_MAX]; int user_input; WINDOW *current_window; ITEM **ncmenu_items = NULL; MENU *sfm_menu; initscr(); start_color(); noecho(); cbreak(); getmaxyx(stdscr, iface->lines, iface->cols); refresh(); iface->sfmncmenu = newwin(3, iface->cols-1, iface->lines-5, 0); keypad(iface->sfmncmenu, TRUE); wmove(iface->sfmncmenu, 1, 1); box(iface->sfmncmenu, 0, 0); ncmenu_items = malloc((menu_choices_n+1) * sizeof(ITEM *)); for (x = 0; x < menu_choices_n; x++) ncmenu_items[x] = new_item(menu_choices[x], menu_choices[x]); //ncmenu_items[menu_choices_n] = (ITEM *)NULL; sfm_menu = new_menu((ITEM **)ncmenu_items); menu_opts_off(sfm_menu, O_SHOWDESC); set_menu_format(sfm_menu, 1, menu_choices_n); set_menu_mark(sfm_menu, " "); set_menu_win(sfm_menu, iface->sfmncmenu); set_menu_sub(sfm_menu, derwin(iface->sfmncmenu, 1, iface->cols-2, 1, 1)); post_menu(sfm_menu); wrefresh(iface->sfmncmenu); iface->sfmnroot = newwin(iface->lines-6, iface->cols-4, 0, 0); snprintf(root_items, sizeof(root_items)-1, "%-40s . %-6s . %-4s . %-3s . %-10s", "FILENAME", "SIZE", "TYPE", "UID", "PERMISSIONS"); wattron(iface->sfmnroot, A_REVERSE|A_BOLD); wprintw(iface->sfmnroot, root_items); wattroff(iface->sfmnroot, A_REVERSE|A_BOLD); for (x = 1; x < (iface->lines - 6); x++) { snprintf(root_items, sizeof(root_items)-1, "Item line %2d . 55Kb . .PDF . 100 . -rw-r--r--", x); mvwprintw(iface->sfmnroot, x, 0, root_items); } wrefresh(iface->sfmnroot); iface->sfmnstatus = newwin(1, iface->cols-1, iface->lines-2, 1); wprintw(iface->sfmnstatus, ":. Hello! Welcome to .: %s :. lines:%d, cols:%d", SFM_VSN, iface->lines, iface->cols); wrefresh(iface->sfmnstatus); current_window = iface->sfmncmenu; while (1) { user_input = wgetch(current_window); switch (user_input) { case KEY_LEFT: menu_driver(sfm_menu, REQ_LEFT_ITEM); break; case KEY_RIGHT: menu_driver(sfm_menu, REQ_RIGHT_ITEM); break; case KEY_UP: break; case KEY_DOWN: break; case 9: if (current_window == iface->sfmncmenu) current_window = iface->sfmnroot; else current_window = iface->sfmncmenu; keypad(current_window, TRUE); break; case 10: { //ITEM *cur; //cur = current_item(sfm_menu); } break; case 'Q': case 'q': wclear(iface->sfmnstatus); wprintw(iface->sfmnstatus, ":. Are you sure you want to quit!? [Y/N] "); wrefresh(iface->sfmnstatus); user_input = wgetch(iface->sfmnstatus); switch (user_input) { case 'y': case 'Y': case 's': case 'S': wclear(iface->sfmnstatus); wprintw(iface->sfmnstatus, ":. Thanks for using SFM! :) Quitting..."); wrefresh(iface->sfmnstatus); sleep(1); goto sfm_ncurses_exit; default: break; } } wclear(iface->sfmnstatus); wprintw(iface->sfmnstatus, ":. status: %d", user_input); wrefresh(iface->sfmnstatus); } sfm_ncurses_exit: delwin(iface->sfmnroot); delwin(iface->sfmnstatus); delwin(iface->sfmncmenu); unpost_menu(sfm_menu); free_menu(sfm_menu); for (x = 0; x < menu_choices_n; x++) free_item(ncmenu_items[x]); free(ncmenu_items); free(iface); refresh(); endwin(); }
int main(int argc, char **argv) { if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); if (signal(SIGUSR1, sig_handler) == SIG_ERR) printf("\ncan't catch SIGUSR1\n"); setlocale(LC_ALL, ""); uint8_t RAMVPointer = 3; // Позиция отображаемого участка памяти uint8_t PROVPointer = 0; int ActiveWindow = WIN_REG; // Активное окно int EditMode = False; // Режим редактора int cx, cy; // Координаты курсора Memory = sc_memoryInit(MaxMemory); if (NULL == Memory) { perror("Память не выделена\n"); goto TERMINATE; } WINDOW *winRAM; WINDOW *winREG; WINDOW *winTerminal; WINDOW *winProgram; initscr(); start_color(); init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_BLUE, COLOR_CYAN); init_pair(3, COLOR_WHITE, COLOR_BLACK); keypad(stdscr, TRUE); refresh(); noecho(); //curs_set(1); curs_set(0);//FIXME winREG = create_win(0, 0, 11, 15); winTerminal = create_win(0, 15, 11, 65); winRAM = create_win(18, 0, 6, 80); winProgram = create_win(11, 0, 7, 19); mvwprintw(winREG, 0, 1, "РЕГИСТРЫ"); mvwprintw(winTerminal, 0, 1, "ТЕРМИНАЛ"); mvwprintw(winRAM, 0, 1, "ПАМЯТЬ"); mvwprintw(winProgram, 0, 1, "ПРОГРАММА"); wbkgd(winREG, COLOR_PAIR(3)); wbkgd(winTerminal, COLOR_PAIR(3)); mvwprintw(winREG, 1, 1, "A: 0x0000"); mvwprintw(winREG, 2, 1, "IC: 0x00"); // mvwprintw(winREG, 3, 1, " FLAGS: 0x00"); // mvwprintw(winREG, 4, 1, " V Z E P C"); // mvwprintw(winREG, 5, 1, " 0 0 0 0 0"); mvwprintw(winREG, 3, 1, "F: 0b00000000"); mvwprintw(winREG, 4, 1, " VZEPC"); loadbios(Memory); viewprog(winProgram, Memory, 0, 0); //sc_memorySet(Memory, 17, 5); // sc_memorySave(Memory, (char*)"caca"); sc_memoryLoad(Memory, (char*)"caca"); viewram(winRAM, RAMVPointer, 0);//fixme wrefresh(winREG); wrefresh(winTerminal); wrefresh(winRAM); wrefresh(winProgram); refresh(); move(1, 1); paintbox(winREG, 1); int ch; while (1) { ch = getch(); switch (ActiveWindow) { case WIN_MEM: { if (ch == KEY_F(3)) { if (EditMode) { EditMode = False; curs_set(0); } else { EditMode = True; curs_set(1); move(19, 8); cx = 8; cy = 1; } } if (!(EditMode)) { switch (ch) { case KEY_DOWN: RAMVPointer = viewram(winRAM, RAMVPointer, 1); wrefresh(winRAM); break; case KEY_UP: RAMVPointer = viewram(winRAM, RAMVPointer, -1); wrefresh(winRAM); break; case KEY_TAB: //goto TERMINATE; ActiveWindow = WIN_REG; paintbox(winRAM, 3); paintbox(winREG, 1); ActiveWindow = WIN_REG; break; } } else { int dig = 0, t; switch (ch) { // MAXIMUM MAGIC! case 'a' ... 'f': //case 97 ... 102: dig -= 'a' - 'A'; // dig -= 32; case 'A' ... 'F': //case 65 ... 70: --dig; case '0' ... '9': //case 48 ... 57: dig += ch - '0'; // dig += ch - 48 if ('9' < ch) // if (57 < ch) dig -= 1 + 'f' - 'a'; // dig -= 6; if (cx < 31) t = (cx - 8) % 3; else t = ((cx - 8) % 3) - 1; Memory[16 * (RAMVPointer - (4 - cy)) + ((cx - 8) / 3)] = ((dig * 0x10 | (Memory[16 * (RAMVPointer - (4 - cy)) + ((cx - 8) / 3)] & 0x0f)) & (!t * 0xff)) + ((dig | (Memory[16 * (RAMVPointer - (4 - cy)) + ((cx - 8) / 3)] & 0xf0)) & (t * 0xff)); viewram(winRAM, RAMVPointer, 0); case KEY_RIGHT: { if (cx < 31) { if (cx % 3) ++cx; else cx += 2; if (cx == 32) ++cx; } else { if (cx % 3) cx += 2; else ++cx; } wmove(winRAM, cy, cx); wrefresh (winRAM);//fixme if (cx < 57) break; else cx = 8;//FIXME В самом конце } case KEY_DOWN: { if (cy > 3) RAMVPointer = viewram(winRAM, RAMVPointer, 1); else ++cy; wmove(winRAM, cy, cx); wrefresh (winRAM);//fixme } break; case KEY_LEFT: { if (cx > 31) { if (cx % 3) --cx; else cx -= 2; if (cx == 31) --cx; } else { if (cx % 3) cx -= 2; else --cx; } wmove(winRAM, cy,cx); wrefresh (winRAM);//fixme if (cx > 7) break; else if (RAMVPointer == 3) cx = 8; else cx = 55; } case KEY_UP: { if (cy <= 1) RAMVPointer = viewram(winRAM, RAMVPointer, -1); else --cy; wmove(winRAM, cy, cx); wrefresh (winRAM);//fixme } break; } } } break; case WIN_PRO: { switch (ch) { case KEY_UP: PROVPointer = viewprog(winProgram, Memory, PROVPointer, -1); wrefresh(winProgram); break; case KEY_DOWN: PROVPointer = viewprog(winProgram, Memory, PROVPointer, 1); wrefresh(winProgram); break; case KEY_TAB://FIXME смена активного окна //goto TERMINATE; ActiveWindow = WIN_MEM; paintbox(winProgram, 3); paintbox(winRAM, 1); ActiveWindow = WIN_MEM; break; } } break; case WIN_REG: { switch (ch) { case KEY_TAB: paintbox(winREG, 3); paintbox(winTerminal, 1); ActiveWindow = WIN_TER; goto TERMINATE; break; } } break; case WIN_TER: { switch (ch) { case KEY_TAB: paintbox(winTerminal, 3); paintbox(winProgram, 1); ActiveWindow = WIN_PRO; break; } } break; } } TERMINATE: free(Memory); delwin(winRAM); delwin(winREG); delwin(winTerminal); // refresh(); endwin(); // sc_regSet(4,1); // sc_regSet(1,1); mt_clrscr(); //bc_printA("\n"); //bc_setbigcharpos(r[3],0,0,0b10000001); int bcint0 [2] = {1717976064, 3958374}; //0b01100110011001100011110000000000, 0b00000000001111000110011001100110 int bcint1 [2] = {1010315264, 3158064}; //0b00111100001110000011000000000000, 0b00000000001100000011000000110000 int bcint2 [2] = {1010842624, 8258050}; //0b00111100010000000011110000000000, 0b00000000011111100000001000000010 int bcint3 [2] = {2120252928, 8282238}; //0b01111110011000000111111000000000, 0b00000000011111100110000001111110 int bcint4 [2] = {2120640000, 6316158}; //0b01111110011001100110011000000000, 0b00000000011000000110000001111110 int bcint5 [2] = {1040350720, 4079680}; //0b00111110000000100111111000000000, 0b00000000001111100100000001000000 int bcint6 [2] = {35789824, 1974814}; //0b00000010001000100001110000000000, 0b00000000000111100010001000011110 int bcint7 [2] = {811630080, 396312}; //0b00110000011000000111111000000000, 0b00000000000001100000110000011000 int bcint8 [2] = {1013332992, 3958374}; //0b00111100011001100011110000000000, 0b00000000001111000110011001100110; int bcint9 [2] = {2087074816, 3956832}; //0b01111100011001100011110000000000, 0b00000000001111000110000001100000 int bcintA [2] = {2118269952, 4342338}; //0b01111110010000100011110000000000, 0b00000000010000100100001001000010 int bcintB [2] = {1044528640, 4080194}; //0b00111110010000100011111000000000, 0b00000000001111100100001001000010 int bcintC [2] = {37895168, 3949058}; //0b00000010010000100011110000000000, 0b00000000001111000100001000000010 int bcintD [2] = {1111637504, 4080194}; //0b01000010010000100011111000000000, 0b00000000001111100100001001000010 int bcintE [2] = {2114092544, 8258050}; //0b01111110000000100111111000000000, 0b00000000011111100000001000000010 int bcintF [2] = {33717760, 131646}; //0b00000010000000100111111000000000, 0b00000000000000100000001000111110 int bcintp [2] = {2115508224, 1579134}; //0b01111110000110000001100000000000, 0b00000000000110000001100001111110 /* bc_printbigchar(bcintp, 5, 5, cl_blue, cl_red); bc_box(2, 1, 50, 20); */ int a; rk_readkey(&a); printf("%d\n", a); return 0; }
int main(int argc, char *argv[]) { if(argc != 1 && argc != 3 && argc != 5 && argc != 7) { printf("Usage: [-u nickname][-n name][-e email]\n"); return -1; } nick = NULL; name = NULL; email = NULL; int i; for(i = 1; i < argc; i++) { if(strcmp(argv[i], "-u") == 0) nick = argv[i + 1]; else if(strcmp(argv[i], "-n") == 0) name = argv[i + 1]; else if(strcmp(argv[i], "-e") == 0) email = argv[i + 1]; } // Determinar a pid do processo pid = getpid(); // Determinar o tamanho do terminal struct winsize ws; if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) { perror("ioctl: TIOCGWINSZ"); return -1; } int lines = ws.ws_row; int columns = ws.ws_col; // Inicializar ncurses 'stdscr' e 'curscr' initscr(); // Iniciar cores start_color(); init_pair(1, COLOR_YELLOW, COLOR_BLUE); init_pair(2, COLOR_WHITE, 0); bkgd(COLOR_PAIR(2)); // Outras configuracoes clear(); // Apaga o ecra echo(); // Permite echo do teclado refresh(); // Actualiza a informacao da janela base // Criar janelas sobre a janela 'stdscr' title_sw = subwin(stdscr, 1, columns, 0, 0); display_sw = subwin(stdscr, lines-3, columns, 1, 0); delimiter_sw = subwin(stdscr, 1, columns, lines-2, 0); keyboard_sw = subwin(stdscr, 1, columns, lines-1, 0); // Titulo da janela wbkgd(title_sw, COLOR_PAIR(1) | A_BOLD); wmove(title_sw, 0, 5); wprintw(title_sw, "Local Relay Chat Client"); wrefresh(title_sw); // Janela de display scrollok(display_sw, true); wrefresh(display_sw); // Espacador wbkgd(delimiter_sw, COLOR_PAIR(1) | A_BOLD); wmove(delimiter_sw, 0, 1); wrefresh(delimiter_sw); // Janela de escrita wmove(keyboard_sw, 0, 0); wrefresh(keyboard_sw); // Adicionar o nick, nome e email caso nao existam char buffer[MAX_BUF_LEN]; if(nick == NULL) { wprintw(display_sw, " Nick?\n"); wrefresh(display_sw); bzero(buffer, MAX_BUF_LEN); wgetstr(keyboard_sw, buffer); wclear(keyboard_sw); wrefresh(keyboard_sw); wprintw(display_sw, "%s\n", buffer); nick = strdup(buffer); } if(name == NULL) { wprintw(display_sw, " Name?\n"); wrefresh(display_sw); bzero(buffer, MAX_BUF_LEN); wgetstr(keyboard_sw, buffer); wclear(keyboard_sw); wrefresh(keyboard_sw); wprintw(display_sw, "%s\n", buffer); name = strdup(buffer); } if(email == NULL) { wprintw(display_sw, " Email?\n"); wrefresh(display_sw); bzero(buffer, MAX_BUF_LEN); wgetstr(keyboard_sw, buffer); wclear(keyboard_sw); wrefresh(keyboard_sw); wprintw(display_sw, "%s\n", buffer); email = strdup(buffer); } // Actualizar o nick update_nick(); // Mensagem de ajuda wprintw(display_sw, START_MESSAGE); wrefresh(display_sw); // Janela de escrita wmove(keyboard_sw, 0, 0); wrefresh(keyboard_sw); // Semaforo sem_init(&ncurses_mutex, 0, 1); // Criar 3 threads que monitorizam o envio e recepcao de mensagens pthread_t display_message_tid; if(pthread_create(&display_message_tid, NULL, display_messages_thread, NULL) != 0) { endwin(); printf("pthread_create: display_messages_thread\n"); return -1; } pthread_t display_information_tid; if(pthread_create(&display_information_tid, NULL, display_information_thread, NULL) != 0) { endwin(); printf("pthread_create: display_information_thread\n"); return -1; } pthread_t keyboard_tid; if(pthread_create(&keyboard_tid, NULL, keyboard_thread, NULL) != 0) { endwin(); printf("pthread_create: keyboard_thread\n"); return -1; } // Esperar pela keyboard_thread int *ret_val; if(pthread_join(keyboard_tid, (void **) &ret_val) != 0) { endwin(); printf("pthread_join: keyboard_thread\n"); return - 1; } // Terminar ncurses endwin(); return 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, fmt = 0xa, use_slk = 1; bool blink_state = FALSE; int cursor_state_1 = 2, cursor_state_2 = 3; int show_slk_index_line = 0; int redraw = 1; // 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 'f': sscanf( argv[i] + 2, "%x", &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; 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[40]; const int color_block_start = 52; const int color_block_size = 14; int c; 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( redraw) { mvaddstr( 1, COL1, "'Normal' white-on-black"); #ifdef WACS_S1 mvaddwstr( 2, 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 WACS_S1 mvaddstr( 2, COL1, "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"); attrset( COLOR_PAIR( 6)); attron( A_STRIKEOUT); mvaddstr( 10, 40, "Strikeout"); attrset( COLOR_PAIR( 1)); for( i = 0; i < 128; i++) { /* Show extended characters: */ char buff[5]; sprintf( buff, "%2x %c", i + 128, (char)(i + 128)); mvaddstr( 5 + i % 16, (i / 16) * 5, buff); } #if(CHTYPE_LONG >= 2) /* "non-standard" 64-bit chtypes */ for( i = 0; i < 3; 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 = strlen( output_text[i]); move( 21 + i, 1); for( j = 0; j < len; 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)); #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 mvaddstr( 19, color_block_start, cursor_state_text[cursor_state_1]); mvaddstr( 20, color_block_start, cursor_state_text[cursor_state_2]); curs_set( (cursor_state_1 << 8) | cursor_state_2); for( i = 0; i < 256; i++) { attrset( COLOR_PAIR( i)); if( i > 2) init_pair((short)i, (short)i, COLOR_BLACK); if( !(i % color_block_size)) move( i / color_block_size, color_block_start); attron( A_REVERSE); addstr( " "); } move( 18, 77); 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", &fmt); if( use_slk) slk_setup( show_slk_index_line ? -fmt : fmt); } if( c != KEY_MOUSE) { sprintf( buff, "Key %s hit ", keyname( c)); 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 <= 256 / color_block_size) { int new_color = (mouse_event.x - color_block_start) / 2 + mouse_event.y * color_block_size; if( new_color >= 256) new_color = -1; PDC_set_line_color( (short)new_color); } else if( mouse_event.x >= color_block_start) { if( mouse_event.y == 19) /* blink/non-blink toggle */ cursor_state_1 = (cursor_state_1 + 1) % N_CURSORS; else if( mouse_event.y == 20) /* cycle cursor state */ cursor_state_2 = (cursor_state_2 + 1) % N_CURSORS; } } } endwin(); return 0; }
static int log_working_directory (int entering) { static char *buf = NULL; static unsigned int len = 0; unsigned int need; const char *fmt; char *p; /* Get enough space for the longest possible output. */ need = strlen (program) + INTSTR_LENGTH + 2 + 1; need += COLOR_MAX_SPACE; if (starting_directory) need += strlen (starting_directory); /* Use entire sentences to give the translators a fighting chance. */ if (makelevel == 0) if (starting_directory == 0) if (entering) fmt = _("%s: Entering an unknown directory\n"); else fmt = _("%s: Leaving an unknown directory\n"); else if (entering) fmt = _("%s: Entering directory '%s'\n"); else fmt = _("%s: Leaving directory '%s'\n"); else if (starting_directory == 0) if (entering) fmt = _("%s[%u]: Entering an unknown directory\n"); else fmt = _("%s[%u]: Leaving an unknown directory\n"); else if (entering) fmt = _("%s[%u]: Entering directory '%s'\n"); else fmt = _("%s[%u]: Leaving directory '%s'\n"); need += strlen (fmt); if (need > len) { buf = xrealloc (buf, need); len = need; } /* mmc: now start typing into the buffer: */ if (color_flag) { /* fixme: negative value on error! */ p = buf + start_color (buf, entering?color_dir_enter:color_dir_leave); } else p = buf; if (print_data_base_flag) { *(p++) = '#'; *(p++) = ' '; } if (makelevel == 0) { if (starting_directory == 0) sprintf (p, fmt, program); else sprintf (p, fmt, program, starting_directory); } else if (starting_directory == 0) sprintf (p, fmt, program, makelevel); else sprintf (p, fmt, program, makelevel, starting_directory); if (color_flag) /* we overwrite the newline! */ /* this is optional, we yes, we have to overwrite: */ stop_color (buf + strlen(buf) -1); strcat (buf, "\n"); /* I'd say stderr! */ _outputs (NULL, 0, buf); return 1; }
static void test_inserts(int level) { static bool first = TRUE; int ch; int limit; int row = 1; int col; int row2, col2; int length; char buffer[BUFSIZ]; WINDOW *look = 0; WINDOW *work = 0; WINDOW *show = 0; int margin = (2 * MY_TABSIZE) - 1; Options option = (Options) ((unsigned) (m_opt ? oMove : oDefault) | (unsigned) ((w_opt || (level > 0)) ? oWindow : oDefault)); if (first) { static char cmd[80]; setlocale(LC_ALL, ""); putenv(strcpy(cmd, "TABSIZE=8")); initscr(); (void) cbreak(); /* take input chars one at a time, no wait for \n */ (void) noecho(); /* don't echo input */ keypad(stdscr, TRUE); } limit = LINES - 5; if (level > 0) { look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1); work = newwin(limit - 2, COLS - (2 * level), 1, level); show = newwin(4, COLS, limit + 1, 0); box(look, 0, 0); wnoutrefresh(look); limit -= 2; } else { work = stdscr; show = derwin(stdscr, 4, COLS, limit + 1, 0); } keypad(work, TRUE); for (col = margin + 1; col < COLS; col += MY_TABSIZE) mvwvline(work, row, col, '.', limit - 2); mvwvline(work, row, margin, ACS_VLINE, limit - 2); mvwvline(work, row, margin + 1, ACS_VLINE, limit - 2); limit /= 2; mvwaddstr(work, 1, 2, "String"); mvwaddstr(work, limit + 1, 2, "Chars"); wnoutrefresh(work); buffer[length = 0] = '\0'; legend(show, level, option, buffer, length); wnoutrefresh(show); doupdate(); /* * Show the characters inserted in color, to distinguish from those that * are shifted. */ if (has_colors()) { start_color(); init_pair(1, COLOR_WHITE, COLOR_BLUE); wbkgdset(work, COLOR_PAIR(1) | ' '); } while ((ch = wgetch(work)) != 'q') { if (ch == ERR) { beep(); break; } wmove(work, row, margin + 1); switch (ch) { case 'w': test_inserts(level + 1); touchwin(look); touchwin(work); touchwin(show); wnoutrefresh(look); wnoutrefresh(work); wnoutrefresh(show); doupdate(); break; case CTRL('N'): case KEY_DOWN: if (row < limit) { ++row; /* put the whole string in, all at once */ col2 = margin + 1; switch (option) { case oDefault: if (n_opt > 1) { for (col = 0; col < length; col += n_opt) { col2 = ColOf(buffer, col, margin); if (move(row, col2) != ERR) { InsNStr(buffer + col, LEN(col)); } } } else { if (move(row, col2) != ERR) { InsStr(buffer); } } break; case oMove: if (n_opt > 1) { for (col = 0; col < length; col += n_opt) { col2 = ColOf(buffer, col, margin); MvInsNStr(row, col2, buffer + col, LEN(col)); } } else { MvInsStr(row, col2, buffer); } break; case oWindow: if (n_opt > 1) { for (col = 0; col < length; col += n_opt) { col2 = ColOf(buffer, col, margin); if (wmove(work, row, col2) != ERR) { WInsNStr(work, buffer + col, LEN(col)); } } } else { if (wmove(work, row, col2) != ERR) { WInsStr(work, buffer); } } break; case oMoveWindow: if (n_opt > 1) { for (col = 0; col < length; col += n_opt) { col2 = ColOf(buffer, col, margin); MvWInsNStr(work, row, col2, buffer + col, LEN(col)); } } else { MvWInsStr(work, row, col2, buffer); } break; } /* do the corresponding single-character insertion */ row2 = limit + row; for (col = 0; col < length; ++col) { col2 = ColOf(buffer, col, margin); switch (option) { case oDefault: if (move(row2, col2) != ERR) { InsCh(UChar(buffer[col])); } break; case oMove: MvInsCh(row2, col2, UChar(buffer[col])); break; case oWindow: if (wmove(work, row2, col2) != ERR) { WInsCh(work, UChar(buffer[col])); } break; case oMoveWindow: MvWInsCh(work, row2, col2, UChar(buffer[col])); break; } } } else { beep(); } break; case KEY_BACKSPACE: ch = '\b'; /* FALLTHRU */ default: if (ch <= 0 || ch > 255) { beep(); break; } buffer[length++] = ch; buffer[length] = '\0'; /* put the string in, one character at a time */ col = ColOf(buffer, length - 1, margin); switch (option) { case oDefault: if (move(row, col) != ERR) { InsStr(buffer + length - 1); } break; case oMove: MvInsStr(row, col, buffer + length - 1); break; case oWindow: if (wmove(work, row, col) != ERR) { WInsStr(work, buffer + length - 1); } break; case oMoveWindow: MvWInsStr(work, row, col, buffer + length - 1); break; } /* do the corresponding single-character insertion */ switch (option) { case oDefault: if (move(limit + row, col) != ERR) { InsCh(UChar(ch)); } break; case oMove: MvInsCh(limit + row, col, UChar(ch)); break; case oWindow: if (wmove(work, limit + row, col) != ERR) { WInsCh(work, UChar(ch)); } break; case oMoveWindow: MvWInsCh(work, limit + row, col, UChar(ch)); break; } wnoutrefresh(work); legend(show, level, option, buffer, length); wnoutrefresh(show); doupdate(); break; } } if (level > 0) { delwin(show); delwin(work); delwin(look); } }
int main(int argc, char **argv){ #ifdef DEBUG DEBUG_FILE = fopen("debug.txt", "w"); #endif initscr(); keypad(stdscr, TRUE); noecho(); clear(); start_color(); init_pair(COL_BLUE, COLOR_BLUE, COLOR_BLACK); init_pair(COL_YELLOW, COLOR_YELLOW, COLOR_BLACK); init_pair(COL_RED, COLOR_RED, COLOR_BLACK); init_pair(COL_WHITE, COLOR_WHITE, COLOR_BLACK); init_pair(COL_GREEN, COLOR_GREEN, COLOR_BLACK); init_pair(COL_CYAN, COLOR_CYAN, COLOR_BLACK); WINDOWMAX_Y = getmaxy(stdscr); WINDOWMAX_X = getmaxx(stdscr); INPUTMODE = INM_NORMAL; dprintf("Window size is %ix%i\n", WINDOWMAX_X, WINDOWMAX_Y); USECOLOR = 1; GCRUNFREQ = 50; CONSIZE = WINDOWMAX_Y - CHUNKSIZE - 5; const char *PATTERN = NULL; const char *BOARDNAME = NULL; int getoptval; while((getoptval = getopt(argc, argv, "cg:p:n:s:")) != -1){ switch(getoptval) { //Disable color case 'c': USECOLOR = 0; break; case 'p': PATTERN = optarg; break; case 'n': BOARDNAME = optarg; break; case 'g': GCRUNFREQ = atoi(optarg); break; case 's': CONSIZE = atoi(optarg); break; } } CONSIZE = clamp(CONSIZE, 5, 15); consoleBuffer = calloc(CONSIZE * GSTRINGSIZE, 1); cprintf("Welcome to the game of life! Press space/zxc to begin!"); cprintf("Use arrows/wasd to move. Press q to quit."); struct board *b; if(PATTERN){ b = readNewBoard(PATTERN); if(BOARDNAME){ setBoardName(b, BOARDNAME); } }else{ b = createBoard(BOARDNAME); initializeBoard(b); } //START TESTS /*#define on(x, y) curChunk(b)->board[at(x, y)] = 1*/ /*on(1, 1);*/ /*on(2, 2);*/ /*on(3, 2);*/ /*on(2, 3);*/ /*on(3, 1);*/ /*goto CLEANUP;*/ //END TESTS while(1){ erase(); drawBoard(b); inputRenderer(); consoleRenderer(); refresh(); if(!input(b)) goto CLEANUP; } CLEANUP: #ifdef DEBUG fclose(DEBUG_FILE); #endif free(consoleBuffer); freeBoard(b); endwin(); printf("Program complete"); return 0; }
void NWindow::StartColor() { start_color(); }
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++) { unsigned int color = CRT_colorSchemes[COLORSCHEME_DEFAULT][i]; CRT_colorSchemes[COLORSCHEME_BROKENGRAY][i] = color == (A_BOLD | ColorPairGrayBlack) ? 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_startsWith(CRT_termType, "xterm") || 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)); char sequence[3] = "\033a"; for (char c = 'a'; c <= 'z'; c++) { sequence[1] = c; define_key(sequence, KEY_ALT('A' + (c - 'a'))); } } #ifndef DEBUG signal(11, CRT_handleSIGSEGV); #endif signal(SIGTERM, CRT_handleSIGTERM); signal(SIGQUIT, 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 }
/* * 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; /* Let's learn about our terminal */ use_alt_charset = loaded_terminfo && tgetstr("acs_chars", NULL); /* Parse args */ for (i = 1; i < argc; i++) { if (prefix(argv[i], "-b")) use_big_screen = TRUE; #ifdef A_ALTCHARSET else if (prefix(argv[i], "-a")) use_alt_charset = 0; else if (prefix(argv[i], "-g")) use_alt_charset = 1; #endif 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 < 24) || (COLS < 80)) { quit("Angband needs at least an 80x24 'curses' screen"); } #ifdef A_COLOR /*** Init the Color-pairs and set up a translation table ***/ /* Do we have color, and enough color, available? */ can_use_color = ((start_color() != ERR) && has_colors() && (COLORS >= 8) && (COLOR_PAIRS >= 8)); #ifdef HAVE_USE_DEFAULT_COLORS /* Should we use curses' "default color" */ if (use_default_colors() == OK) bg_color = -1; #endif #ifdef HAVE_CAN_CHANGE_COLOR /* Can we change colors? */ can_fix_color = (can_use_color && can_change_color() && orig_colors && (COLORS >= 16) && (COLOR_PAIRS > 8)); #endif /* Attempt to use customized colors */ if (can_fix_color) { /* Prepare the color pairs */ for (i = 0; i < (BASIC_COLORS / 2); i++) { /* Reset the color */ if (init_pair(i + 1, i, bg_color) == ERR) { quit("Color pair init failed"); } /* Set up the colormap */ colortable[i] = (COLOR_PAIR(i + 1) | A_NORMAL); colortable[i + (BASIC_COLORS / 2)] = (COLOR_PAIR(i + 1) | A_BRIGHT); } /* Take account of "gamma correction" XXX XXX XXX */ /* Prepare the "Angband Colors" */ Term_xtra_gcu_react(); } /* Attempt to use colors */ else 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_RED) | 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 #ifdef A_ALTCHARSET /* Build a quick access table for the "alternate character set". */ if (use_alt_charset) { acs_table[1] = ACS_DIAMOND; acs_table[16] = ACS_S1; acs_table[2] = ACS_CKBOARD; acs_table[18] = ACS_HLINE; acs_table[7] = ACS_DEGREE; acs_table[20] = ACS_S9; acs_table[8] = ACS_PLMINUS; acs_table[21] = ACS_LTEE; acs_table[11] = ACS_LRCORNER; acs_table[22] = ACS_RTEE; acs_table[12] = ACS_URCORNER; acs_table[23] = ACS_BTEE; acs_table[13] = ACS_ULCORNER; acs_table[24] = ACS_TTEE; acs_table[14] = ACS_LLCORNER; acs_table[25] = ACS_VLINE; acs_table[15] = ACS_PLUS; acs_table[31] = ACS_BULLET; } #endif /*** Low level preparation ***/ /* 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 < MAX_TERM_DATA; i++) { if (use_big_screen && i > 0) break; /* 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); }
int main (int argc, char **argv) { int rc = 0; char c[4096]; getOsVer(); memset (&descriptors, '\0', sizeof(char *) * MAX_DESC); fd =setupSocket (); if (fd == -1) { fprintf(stderr,"Unable to continue without socket\n"); exit(1); } struct stat stbuf; fstat(1, &stbuf); if (stbuf.st_mode & S_IFCHR) { wantColors = 1; wantCurses = 1;} else {wantColors = 0; wantCurses = 0;} int arg = 1; for (arg = 1; arg < argc; arg++) { if (strcmp(argv[arg], "nc") == 0) wantCurses = 0; else if (strcmp(argv[arg], "once") == 0) {wantCurses = 0; wantOnce = 1; wantColors = 0;} else if (strcmp(argv[arg], "udp") == 0) { wantUDP = 1; wantTCP = 0;} else if (strcmp(argv[arg], "tcp") == 0) { wantTCP = 1; wantUDP = 0;} else { printHelp(); exit(2);} } nstat_msg_query_src_req qsreq; char ch; // Want both - we'll just filter int udpAdded = 0; int tcpAdded = 0 ; int gettingCounts = 0 ; int gotCounts = 0; addAll (fd, NSTAT_PROVIDER_TCP); if (wantCurses) { initscr(); cbreak(); noecho(); start_color(); nodelay (stdscr,1); } print_header(wantCurses); while (1) { //rc > 0) { if (wantCurses || wantOnce) { fd_set fds; struct timeval to; to.tv_sec = 0; to.tv_usec = DELAY; FD_ZERO (&fds); FD_SET (fd, &fds); // select on socket, rather than read.. rc = select(fd +1, &fds, NULL, NULL, &to); if (rc > 0) rc = read(fd,c,2048); else { // Timed out on select: now we can print if (wantOnce ) { print_descriptors(); exit(0);} else { qsreq.hdr.type= NSTAT_MSG_TYPE_QUERY_SRC ; // 1004 qsreq.srcref= 0xffffffff; //NSTAT_SRC_REF_ALL; qsreq.hdr.context = 1005; // This way I can tell if errors get returned for dead sources rc = write (fd, &qsreq, sizeof(qsreq)); } } } else rc = read (fd, c, 2048); // check rc. Meh. if (rc > 0) { nstat_msg_hdr *ns = (nstat_msg_hdr *) c; switch (ns->type) { case 10001: case 10002: case 10003: case 10004: rc = process_nstat_msg(c,rc); break; case 0: // Got all sources, or all counts // if we were getting sources, ask now for all descriptions if (!tcpAdded) { tcpAdded++; addAll (fd, NSTAT_PROVIDER_UDP); } else { if (!udpAdded) udpAdded++; } if (tcpAdded && udpAdded ) { if (!gettingCounts) { qsreq.hdr.type= NSTAT_MSG_TYPE_QUERY_SRC ; // 1004 qsreq.srcref= 0xffffffff; //NSTAT_SRC_REF_ALL; qsreq.hdr.context = 1005; // This way I can tell if errors get returned for dead sources rc = write (fd, &qsreq, sizeof(qsreq)); gettingCounts++; } else gotCounts++; } break; case 1: //Error message - these are usually for dead sources (context will be 1005) break; default: break; } } if (wantCurses) { ch = getch(); // could do lowercase instead of 'H'/'h', etc... if (ch != ERR) { if (ch == 'H' || ch =='h') printf("Too late now :-)\n"); if (ch == 'U' || ch =='u') {wantUDP = !wantUDP; setMessage(wantUDP ? "Showing UDP Sockets" :"Not showing UDP sockets"); } if (ch == 'T' || ch == 't') { wantTCP = !wantTCP; setMessage(wantTCP ? "Showing TCP Sockets" : "Not showing TCP sockets"); } if (ch == 'L' || ch == 'l') { wantListen= !wantListen; setMessage("Toggling TCP listeners"); } if (ch == 'P' || ch == 'p') { wantPackets = !wantPackets; setMessage(wantPackets ? "Showing Packets" : "Showing Bytes"); } if (ch == 'C' || ch == 'c') { wantColors = !wantColors; setMessage("Toggling color display"); } if (ch == 'K' || ch == 'k') { wantHumanReadable = !wantHumanReadable; } if (ch =='Q' || ch == 'q') { if (wantCurses) {endwin();}exit(0);} } } if (wantOnce > 1) exit(0); if (!wantOnce && gotCounts) { print_descriptors(); if (!wantCurses) memset (&descriptors, '\0', sizeof(char *) * MAX_DESC); } } // end while return (0); }
int main() { WINDOW *my_wins[3]; PANEL *my_panels[3]; PANEL_DATA panel_datas[3]; PANEL_DATA *temp; int ch; /* Initialize curses */ initscr(); start_color(); cbreak(); noecho(); keypad(stdscr, TRUE); /* Initialize all the colors */ init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_BLUE, COLOR_BLACK); init_pair(4, COLOR_CYAN, COLOR_BLACK); init_wins(my_wins, 3); /* Attach a panel to each window */ /* Order is bottom up */ my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */ my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */ my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */ /* Initialize panel datas saying that nothing is hidden */ panel_datas[0].hide = FALSE; panel_datas[1].hide = FALSE; panel_datas[2].hide = FALSE; set_panel_userptr(my_panels[0], &panel_datas[0]); set_panel_userptr(my_panels[1], &panel_datas[1]); set_panel_userptr(my_panels[2], &panel_datas[2]); /* Update the stacking order. 2nd panel will be on top */ update_panels(); /* Show it on the screen */ attron(COLOR_PAIR(4)); mvprintw(LINES - 3, 0, "Show or Hide a window with 'a'(first window) 'b'(Second Window) 'c'(Third Window)"); mvprintw(LINES - 2, 0, "F1 to Exit"); attroff(COLOR_PAIR(4)); doupdate(); while((ch = getch()) != KEY_F(1)) { switch(ch) { case 'a': temp = (PANEL_DATA *)panel_userptr(my_panels[0]); if(temp->hide == FALSE) { hide_panel(my_panels[0]); temp->hide = TRUE; } else { show_panel(my_panels[0]); temp->hide = FALSE; } break; case 'b': temp = (PANEL_DATA *)panel_userptr(my_panels[1]); if(temp->hide == FALSE) { hide_panel(my_panels[1]); temp->hide = TRUE; } else { show_panel(my_panels[1]); temp->hide = FALSE; } break; case 'c': temp = (PANEL_DATA *)panel_userptr(my_panels[2]); if(temp->hide == FALSE) { hide_panel(my_panels[2]); temp->hide = TRUE; } else { show_panel(my_panels[2]); temp->hide = FALSE; } break; } update_panels(); doupdate(); } endwin(); return 0; }
int main(int argc, char **argv) { int key; int colsold; int graphlines; struct iface ifa; WINDOW *title, *rxgraph, *txgraph, *rxstats, *txstats; bool colors = true; bool siunits = false; double delay = 0.5; memset(&ifa, 0, sizeof(ifa)); ARGBEGIN { case 'v': eprintf("%s-%s\n", argv0, VERSION); case 'C': colors = false; break; case 's': siunits = 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"); initscr(); curs_set(0); noecho(); keypad(stdscr, TRUE); timeout(delay * 1000); if (colors && has_colors()) { start_color(); use_default_colors(); init_pair(1, COLOR_GREEN, -1); init_pair(2, COLOR_RED, -1); } signal(SIGWINCH, sighandler); mvprintw(0, 0, "collecting data from %s for %.2f seconds\n", ifa.ifname, delay); ifa.rxs = ecalloc(COLS - 3, sizeof(*ifa.rxs)); ifa.txs = ecalloc(COLS - 3, sizeof(*ifa.txs)); graphlines = (LINES - 7) / 2; title = newwin(1, COLS, 0, 0); rxgraph = newwin(graphlines, COLS, 1, 0); txgraph = newwin(graphlines, COLS, graphlines + 1, 0); rxstats = newwin(LINES - (graphlines * 2 + 1), COLS / 2, graphlines * 2 + 1, 0); txstats = newwin(LINES - (graphlines * 2 + 1), COLS - COLS / 2, graphlines * 2 + 1, COLS / 2); if (!getdata(&ifa, delay, COLS - 3)) eprintf("can't read rx and tx bytes for %s\n", ifa.ifname); while ((key = getch()) != 'q') { if (key != ERR) resize = 1; if (!getdata(&ifa, delay, COLS - 3)) eprintf("can't read rx and tx bytes for %s\n", ifa.ifname); if (resize) { colsold = COLS; endwin(); refresh(); arrayresize(&ifa.rxs, COLS - 3, colsold - 3); arrayresize(&ifa.txs, COLS - 3, colsold - 3); graphlines = (LINES - 7) / 2; wresize(title, 1, COLS); wresize(rxgraph, graphlines, COLS); wresize(txgraph, graphlines, COLS); wresize(rxstats, LINES - (graphlines * 2 + 1), COLS / 2); wresize(txstats, LINES - (graphlines * 2 + 1), COLS - COLS / 2); mvwin(txgraph, graphlines + 1, 0); mvwin(rxstats, graphlines * 2 + 1, 0); mvwin(txstats, graphlines * 2 + 1, COLS / 2); resize = 0; } werase(title); mvwprintw(title, 0, COLS / 2 - 8, "[ interface: %s ]", ifa.ifname); wnoutrefresh(title); printgraphw(rxgraph, "Received", ifa.rxs, ifa.rxmax, siunits, graphlines, COLS, COLOR_PAIR(1)); printgraphw(txgraph, "Transmitted", ifa.txs, ifa.txmax, siunits, graphlines, COLS, COLOR_PAIR(2)); printstatsw(rxstats, "Received", ifa.rxs[COLS - 4], ifa.rxavg, ifa.rxmax, ifa.rx, siunits, COLS / 2); printstatsw(txstats, "Transmitted", ifa.txs[COLS - 4], ifa.txavg, ifa.txmax, ifa.tx, siunits, COLS - COLS / 2); doupdate(); } delwin(title); delwin(rxgraph); delwin(txgraph); delwin(rxstats); delwin(txstats); endwin(); free(ifa.rxs); free(ifa.txs); return EXIT_SUCCESS; }
uHTRPowerMezzMenu::uHTRPowerMezzMenu(std::map< int, std::string> config_lines, bool isV2,const char tstr[]) : yinit_(0),xinit_(0) { //Handle signals struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; /* Restart functions if interrupted by handler */ sprintf(tester,"%s",tstr); for (std::map< int, std::string>::iterator it = config_lines.begin(); it!= config_lines.end(); it++) { Board b; b.id = it->first; std::string config_line = it->second; b.adChan = atoi(parseto(config_line).c_str()); sprintf(b.adapter, "%s", parseto(config_line).c_str()); sprintf(b.hostname, "%s", parseto(config_line,":").c_str()); sprintf(b.port, "%s", parseto(config_line).c_str()); // Initialize i2c device bool isRPi = false; if(strcmp(b.adapter, "RPi") == 0) isRPi = true; else if(strcmp(b.adapter, "S20") == 0) isRPi = false; else { printf("i2c adapter: %s is invalid!!! (Options are \"RPi\" and \"S20\")\n", b.adapter); } b.s20 = new uHTRPowerMezzInterface(0, isV2, isRPi,b.hostname,b.port); b.s20->setMUXChannel(0,b.adChan); if(isRPi && (b.adChan < 1 || b.adChan > 6)) { printf("Invalid RPi adapter channel (1 - 6 are valid)!!!\n"); continue; } else if(!isRPi) { b.adChan = -1; // unnecessary for s20 adapter } // Grab mezzanines char slot[32]; float voltage; bool mezzIn[]= {false,false,false,false,false}; b.mezzanines = new Mezzanines(); for(std::string mezz = parseto(config_line); mezz != ""; mezz = parseto(config_line)) { if(sscanf(mezz.c_str(), "%s %f\n", slot, &voltage) == 2) { b.slots.push_back(std::make_pair(std::string(slot),voltage)); if(strcmp(slot, "PM_3_3") == 0 && !mezzIn[0]) { b.mezzanines->push_back(new PM(*b.s20, V2_MUX_PM_3_3, voltage, true, b.adChan)); mezzIn[0]=true; } else if(strcmp(slot, "APM_2_5") == 0 && !mezzIn[1]) { b.mezzanines->push_back(new APM(*b.s20, V2_MUX_APM_2_5, voltage, true, b.adChan)); mezzIn[1]=true; } else if(strcmp(slot, "PM_1_B") == 0 && !mezzIn[2]) { b.mezzanines->push_back(new PM(*b.s20, V2_MUX_PM_1_B, voltage, true, b.adChan)); mezzIn[2]=true; } else if(strcmp(slot, "APM_1_6") == 0 && !mezzIn[3]) { b.mezzanines->push_back(new APM(*b.s20, V2_MUX_APM_1_6, voltage, true, b.adChan)); mezzIn[3]=true; } else if(strcmp(slot, "PM_1_A") == 0 && !mezzIn[4]) { b.mezzanines->push_back(new PM(*b.s20, V2_MUX_PM_1_A, voltage, true, b.adChan)); mezzIn[4]=true; } else { printf("Invalid or duplicate Mezzanine slot: %s (options are PM_3_3, APM_2_5, PM_1_B, APM_1_6, PM_1_A)!!!\n", slot); } } } b.pid = 0; b.time = 0; b.voltage = 0; boards_[b.id] = b; } selected_board_ = boards_.begin(); initscr(); if (has_colors()) { start_color(); init_pair(1, COLOR_GREEN, COLOR_BLACK ); init_pair(2, COLOR_BLUE, COLOR_BLACK ); init_pair(3, COLOR_RED, COLOR_BLACK ); } erase(); noecho(); nodelay(stdscr, true); keypad(stdscr,true); cbreak(); curs_set(0); io::enable_curses(yinit_ + 7 + boards_.size(), LINES - 2 ,xinit_ + 2); n_checks_ = shutdown_time_; }
int setup_ncurses_interface() { int screen_x, screen_y; int i, x, y; initscr(); noecho(); nonl(); raw(); getmaxyx(stdscr, screen_y, screen_x); /* screen is too small to be useful*/ if(screen_y < 10) finish("Terminal is too small to run vifm\n"); if(screen_x < 30) finish("Terminal is too small to run vifm\n"); if(! has_colors()) finish("Vifm requires a console that can support color.\n"); start_color(); // Changed for pdcurses use_default_colors(); x = 0; for (i = 0; i < cfg.color_scheme_num; i++) { for(x = 0; x < 12; x++) init_pair(col_schemes[i].color[x].name, col_schemes[i].color[x].fg, col_schemes[i].color[x].bg); } werase(stdscr); menu_win = newwin(screen_y - 1, screen_x , 0, 0); wbkgdset(menu_win, COLOR_PAIR(WIN_COLOR)); werase(menu_win); sort_win = newwin(14, 30, (screen_y -12)/2, (screen_x -30)/2); wbkgdset(sort_win, COLOR_PAIR(WIN_COLOR)); werase(sort_win); change_win = newwin(20, 30, (screen_y -20)/2, (screen_x -30)/2); wbkgdset(change_win, COLOR_PAIR(WIN_COLOR)); werase(change_win); error_win = newwin(10, screen_x -2, (screen_y -10)/2, 1); wbkgdset(error_win, COLOR_PAIR(WIN_COLOR)); werase(error_win); lborder = newwin(screen_y - 2, 1, 0, 0); wbkgdset(lborder, COLOR_PAIR(BORDER_COLOR)); werase(lborder); if (curr_stats.number_of_windows == 1) lwin.title = newwin(0, screen_x -2, 0, 1); else lwin.title = newwin(0, screen_x/2 -1, 0, 1); wattrset(lwin.title, A_BOLD); wbkgdset(lwin.title, COLOR_PAIR(BORDER_COLOR)); werase(lwin.title); if (curr_stats.number_of_windows == 1) lwin.win = newwin(screen_y - 3, screen_x -2, 1, 1); else lwin.win = newwin(screen_y - 3, screen_x/2 -2, 1, 1); keypad(lwin.win, TRUE); wbkgdset(lwin.win, COLOR_PAIR(WIN_COLOR)); wattrset(lwin.win, A_BOLD); wattron(lwin.win, A_BOLD); werase(lwin.win); getmaxyx(lwin.win, y, x); lwin.window_rows = y -1; lwin.window_width = x -1; mborder = newwin(screen_y, 2, 0, screen_x/2 -1); wbkgdset(mborder, COLOR_PAIR(BORDER_COLOR)); werase(mborder); if (curr_stats.number_of_windows == 1) rwin.title = newwin(0, screen_x -2 , 0, 1); else rwin.title = newwin(1, screen_x/2 -1 , 0, screen_x/2 +1); wbkgdset(rwin.title, COLOR_PAIR(BORDER_COLOR)); wattrset(rwin.title, A_BOLD); wattroff(rwin.title, A_BOLD); werase(rwin.title); if (curr_stats.number_of_windows == 1) rwin.win = newwin(screen_y - 3, screen_x -2 , 1, 1); else rwin.win = newwin(screen_y - 3, screen_x/2 -2 , 1, screen_x/2 +1); keypad(rwin.win, TRUE); wattrset(rwin.win, A_BOLD); wattron(rwin.win, A_BOLD); wbkgdset(rwin.win, COLOR_PAIR(WIN_COLOR)); werase(rwin.win); getmaxyx(rwin.win, y, x); rwin.window_rows = y - 1; rwin.window_width = x -1; rborder = newwin(screen_y - 2, 1, 0, screen_x -1); wbkgdset(rborder, COLOR_PAIR(BORDER_COLOR)); werase(rborder); stat_win = newwin(1, screen_x, screen_y -2, 0); wbkgdset(stat_win, COLOR_PAIR(BORDER_COLOR)); werase(stat_win); status_bar = newwin(1, screen_x - 19, screen_y -1, 0); keypad(status_bar, TRUE); wattrset(status_bar, A_BOLD); wattron(status_bar, A_BOLD); wbkgdset(status_bar, COLOR_PAIR(STATUS_BAR_COLOR)); werase(status_bar); pos_win = newwin(1, 13, screen_y - 1, screen_x -13); wattrset(pos_win, A_BOLD); wattron(pos_win, A_BOLD); wbkgdset(pos_win, COLOR_PAIR(STATUS_BAR_COLOR)); werase(pos_win); num_win = newwin(1, 6, screen_y - 1, screen_x -19); wattrset(num_win, A_BOLD); wattron(num_win, A_BOLD); wbkgdset(num_win, COLOR_PAIR(STATUS_BAR_COLOR)); werase(num_win); wnoutrefresh(lwin.title); wnoutrefresh(lwin.win); wnoutrefresh(rwin.win); wnoutrefresh(rwin.title); wnoutrefresh(stat_win); wnoutrefresh(status_bar); wnoutrefresh(pos_win); wnoutrefresh(num_win); wnoutrefresh(lborder); wnoutrefresh(mborder); wnoutrefresh(rborder); return 1; }
static int pre_loop_hook (pingobj_t *ping) /* {{{ */ { pingobj_iter_t *iter; int width = 0; int height = 0; int main_win_height; initscr (); cbreak (); noecho (); nodelay (stdscr, TRUE); getmaxyx (stdscr, height, width); if ((height < 1) || (width < 1)) return (EINVAL); if (has_colors () == TRUE) { start_color (); init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0); init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0); init_pair (OPING_RED, COLOR_RED, /* default = */ 0); } main_win_height = height - (4 * host_num); main_win = newwin (/* height = */ main_win_height, /* width = */ 0, /* y = */ 0, /* x = */ 0); /* Allow scrolling */ scrollok (main_win, TRUE); /* wsetscrreg (main_win, 0, main_win_height - 1); */ /* Allow hardware accelerated scrolling. */ idlok (main_win, TRUE); wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0); wrefresh (main_win); for (iter = ping_iterator_get (ping); iter != NULL; iter = ping_iterator_next (iter)) { ping_context_t *context; context = ping_iterator_get_context (iter); if (context == NULL) continue; if (context->window != NULL) { delwin (context->window); context->window = NULL; } context->window = newwin (/* height = */ 4, /* width = */ 0, /* y = */ main_win_height + (4 * context->index), /* x = */ 0); } /* Don't know what good this does exactly, but without this code * "check_resize" will be called right after startup and *somehow* * this leads to display errors. If we purge all initial characters * here, the problem goes away. "wgetch" is non-blocking due to * "nodelay" (see above). */ while (wgetch (stdscr) != ERR) { /* eat up characters */; } return (0); } /* }}} int pre_loop_hook */
int main( int argc, char *argv[] ) { ChewingContext *ctx; FILE *fout; FILE *fout2; char *prefix = CHEWING_DATA_PREFIX; char *out_file = "tmp.txt"; char *out_file2 = "tmp_out.txt"; int ch; int width, height; int add_phrase_length; /*if ( argc < 2 ) { fprintf( stderr, "usage: genkeystroke filename\n" ); exit( 1 ); } else { fout = fopen( argv[ 1 ], "w" );*/ fout = fopen( out_file, "w" ); if ( ! fout ) { fprintf( stderr, "Error: failed to open %s\n", out_file ); exit( 1 ); } fout2 = fopen( out_file2, "w" ); if ( ! fout2 ) { fprintf( stderr, "Error: failed to open %s\n", out_file2 ); exit( 1 ); } /*}*/ /* Initialize curses library */ setlocale(LC_CTYPE, ""); initscr(); if ( has_colors() == TRUE ) { start_color(); init_pair( 1, COLOR_WHITE, COLOR_BLUE ); init_pair( 2, COLOR_RED, COLOR_YELLOW ); init_pair( 3, COLOR_WHITE, COLOR_RED ); hasColor = 1; } cbreak(); noecho(); keypad( stdscr, 1 ); getmaxyx( stdscr, height, width ); start_color(); clear(); refresh(); /* Initialize libchewing */ /* for the sake of testing, we should not change existing hash data */ chewing_Init( prefix, TEST_HASH_DIR ); /* Request handle to ChewingContext */ ctx = chewing_new(); /* Set keyboard type */ chewing_set_KBType( ctx, chewing_KBStr2Num( "KB_DEFAULT" ) ); /* Fill configuration values */ chewing_set_candPerPage( ctx, 9 ); chewing_set_maxChiSymbolLen( ctx, 16 ); chewing_set_addPhraseDirection( ctx, 1 ); chewing_set_selKey( ctx, selKey_define, 10 ); chewing_set_spaceAsSelection( ctx, 1 ); chewing_set_autoShiftCur( ctx, 1 ); chewing_set_phraseChoiceRearward( ctx, 1 ); clear(); mvaddstr( 0, 0, "Any key to start testing..." ); while ( TRUE ) { ch = getch(); switch ( ch ) { case KEY_LEFT: chewing_handle_Left( ctx ); fprintf( fout, "<L>" ); break; case KEY_SLEFT: chewing_handle_ShiftLeft( ctx ); fprintf( fout, "<SL>" ); break; case KEY_RIGHT: chewing_handle_Right( ctx ); fprintf( fout, "<R>" ); break; case KEY_SRIGHT: chewing_handle_ShiftRight( ctx ); fprintf( fout, "<SR>" ); break; case KEY_UP: chewing_handle_Up( ctx ); fprintf( fout, "<U>" ); break; case KEY_DOWN: chewing_handle_Down( ctx ); fprintf( fout, "<D>" ); break; case KEY_SPACE: chewing_handle_Space( ctx ); fprintf( fout, " " ); break; case KEY_ENTER: chewing_handle_Enter( ctx ); fprintf( fout, "<E>" ); break; case KEY_BACKSPACE: chewing_handle_Backspace( ctx ); fprintf( fout, "<B>" ); break; case KEY_ESC: chewing_handle_Esc( ctx ); fprintf( fout, "<EE>" ); break; case KEY_DC: chewing_handle_Del( ctx ); fprintf( fout, "<DC>" ); break; case KEY_HOME: chewing_handle_Home( ctx ); fprintf( fout, "<H>" ); break; case KEY_END: chewing_handle_End( ctx ); fprintf( fout, "<EN>" ); break; case KEY_TAB: chewing_handle_Tab( ctx ); fprintf( fout, "<T>" ); break; case CTRL_0: case CTRL_1: case CTRL_2: case CTRL_3: case CTRL_4: case CTRL_5: case CTRL_6: case CTRL_7: case CTRL_8: case CTRL_9: add_phrase_length = ( ch - CTRL_0 + '0' ); chewing_handle_CtrlNum( ctx, add_phrase_length ); fprintf( fout, "<C%c>", add_phrase_length ); break; case KEY_CTRL_('B'): /* emulate CapsLock */ chewing_handle_Capslock( ctx ); fprintf( fout, "<CB>"); break; case KEY_CTRL_('D'): case EOF: goto end; case KEY_CTRL_('H'): /* emulate Shift */ if ( chewing_get_ShapeMode( ctx ) == FULLSHAPE_MODE ) chewing_set_ShapeMode( ctx, HALFSHAPE_MODE ); else chewing_set_ShapeMode( ctx, FULLSHAPE_MODE ); break; default: chewing_handle_Default( ctx, (char) ch ); fprintf( fout, "%c", (char) ch ); break; } drawline( 0, 0 ); drawline( 2, 0 ); show_interval_buffer( 3, 0, ctx ); drawline( 4, 0 ); show_choose_buffer( 5, 0, ctx ); drawline( 6, 0 ); show_zuin_buffer( 7, 0, ctx ); show_full_shape( 7, 5, ctx ); drawline( 8, 0 ); mvaddstr( 9, 0, "Ctrl + d : leave" ); mvaddstr( 9, 20, "Ctrl + b : toggle Eng/Chi mode" ); mvaddstr( 10, 0, "F1, F2, F3, ..., F9 : Add user defined phrase"); mvaddstr( 11, 0, "Crtl + h : toggle Full/Half shape mode" ); show_commit_string( ctx ); store_commit_string( ctx, fout2 ); show_userphrase( 7, 12, ctx ); show_edit_buffer( 1, 0, ctx ); } end: endwin(); /* Release Chewing context */ chewing_delete( ctx ); /* Termate Chewing services */ chewing_Terminate(); fprintf( fout, "\n" ); fprintf( fout2, "\n" ); fclose( fout ); fclose( fout2 ); return 0; }