예제 #1
0
void drawLeft(WINDOW *left, unsigned char players, unsigned char id,
    unsigned char bombs, unsigned char mines, struct data *pData){

    unsigned int i;

    //Add borders
    wborder(left, ' ', '|', ' ', '-', ' ', '|', '-', '+');

    //Write all the information we have so far
    for(i = 0; i < players; i++){
        //Set the appropriate color
        wcolor_set(left, i + 2 , NULL);

        if(pData[i].stats){
            mvwprintw(left, 2*i, 0, "%s", pData[i].name);
            mvwprintw(left, 2*i, 17, "%3d", pData[i].score);

            //Print the bombs you have
            if(i == id){
                mvwprintw(left, 2*i + 1, 0, "          Bombs: %3d", bombs);
            }
        }
        else {
            mvwprintw(left, 2*i, 0, "--------Open--------");
        }
    }

    //Print mines
    wcolor_set(left, 8, NULL);
    mvwprintw(left, 15, 0, "%3d/%3d mines", mines, mines);
}
예제 #2
0
void drawRight(WINDOW *right){
    //Borders
    wborder(right, '|', ' ', ' ', '-', '|', ' ', '+', '-');

    //Red
    wcolor_set(right, 8, NULL);

    mvwprintw(right, 0, 1, "NebSweeper Curses");
    mvwprintw(right, 1, 1, "%s", VERSION);
    mvwprintw(right, 2, 1, "Copyright 201{0,1}");
    mvwprintw(right, 3, 1, "Flavio Zavan");

    //Yelow
    wcolor_set(right, 5, NULL);
    
    mvwprintw(right, 5, 1, "Licensed under the");
    mvwprintw(right, 6, 1, "GNU/GPL version 3");

    //Green
    wcolor_set(right, 3, NULL);

    mvwprintw(right, 11, 1, "Keys:");
    mvwprintw(right, 12, 1, "Arrows: Move Cursor");
    mvwprintw(right, 13, 1, "Space: Sweep/Bomb");
    mvwprintw(right, 14, 1, "B: Toggle Bomb");
    mvwprintw(right, 15, 1, "Return: Chat");
}
예제 #3
0
void toolsMenu(WINDOW *menu, WINDOW *message, WINDOW *alphabet, Cryptogram *cr)
{
    char key;
    
    wclear(message);
    cr->paintStats(message);
    wrefresh(message);
    while (1)
    {
        wclear(menu);
        wcolor_set(menu, 1, NULL);
        wattron(menu, WA_REVERSE);
        mvwprintw(menu, 0, 0, "%s", TOOLSMENU);
        wattroff(menu, WA_REVERSE);
        wmove(menu, 0, strlen(TOOLSMENU));
        wrefresh(menu);

        noecho();
        key = getch();
        echo();
        switch(key)
        {
            case 'R':
            case 'r':
                cr->randomizeKeys();
                cr->calcPlaintext();
                return;
            case 'T':
            case 't':
                wclear(menu);
                wcolor_set(menu, 1, NULL);
                mvwprintw(menu, 0, 0, "Please wait, randomizing...");
                wmove(menu, 0, 27);
                wrefresh(menu);
                cr->randomizeMessage();
                cr->calcPlaintext();
                return;
            case 'G':
            case 'g':
                wclear(menu);
                wcolor_set(menu, 1, NULL);
                mvwprintw(menu, 0, 0, "Please wait, generating...");
                wmove(menu, 0, 27);
                wrefresh(menu);
                cr->newRandomMessage();
                cr->calcPlaintext();
                return;
            case '3':
                for (int i=0; i < 26; i++)
                    cr->set(i + 'A', ((i+13)%26) + 'A');
                cr->calcPlaintext();
                return;
            case 'C':
            case 'c':
                return;
        }
    }
}
예제 #4
0
void Screen::PrintInv(WINDOW * const window, Inventory * const inv) const {
	werase(window);
	wstandend(window);
	switch ( inv->Kind() ) {
		case DWARF:
			mvwaddstr(window, 2, 7, "Head\n Right hand\n  ");
			waddstr(window, "Left hand\n       Body\n       ");
			waddstr(window, "Legs");
		break;
		case WORKBENCH: mvwaddstr(window, 2, 4, "Product"); break;
	}
	mvwprintw(window, 2+inv->Size(), 40, "All weight: %6hu mz",
		inv->Weight());
	QString str;
	for (ushort i=0; i<inv->Size(); ++i) {
		mvwprintw(window, 2+i, 12, "%c)", 'a'+i);
		if ( inv->Number(i) ) {
			wcolor_set(window, Color(inv->GetInvKind(i),
				inv->GetInvSub(i)), NULL);
			wprintw(window, "[%c]%s",
					CharName( inv->GetInvKind(i),
						inv->GetInvSub(i) ),
					qPrintable(inv->InvFullName(str, i)) );
			if ( 1<inv->Number(i) ) {
				waddstr(window,
					qPrintable(inv->NumStr(str, i)));
			}
			if ( ""!=inv->GetInvNote(str, i) ) {
				waddstr(window,
					qPrintable((" ~:"+(( str.size()<24 ) ?
						str : str.left(13)+"..."))));
			}
			wstandend(window);
			mvwprintw(window, 2+i, 53, "%5hu mz",
				inv->GetInvWeight(i));
		}
	}
	wcolor_set(window, Color(inv->Kind(), inv->Sub()), NULL);
	box(window, 0, 0);
	(void)wmove(window, 0, 1);
	if ( player->PlayerInventory()==inv ) {
		wprintw(window, "[%c]Your inventory",
			CharName(inv->Kind(), inv->Sub()));
	} else {
		wprintw(window, "[%c]%s",
			CharName(inv->Kind(), inv->Sub()),
			qPrintable(inv->FullName(str)));
	}
	wnoutrefresh(window);
}
예제 #5
0
파일: attr_on.c 프로젝트: andreiw/polaris
int
color_set(short co, void *opts)
{
	(void) wcolor_set(stdscr, co, opts);

	return (OK);
}
예제 #6
0
파일: fmtext.c 프로젝트: alexmv/barnowl
static void _owl_fmtext_wcolor_set(WINDOW *w, short pair)
{
  if (owl_global_get_hascolors(&g)) {
      wcolor_set(w,pair,NULL);
      wbkgdset(w, COLOR_PAIR(pair));
  }
}
예제 #7
0
MENUPAN*
menu_pan_create(MENU *menu, int y, int x, int id)
{
    MENUPAN *menupan;


    assert(menu);

    menupan=(MENUPAN *)malloc(sizeof(MENUPAN));
    if(!menupan) {
        set_error(ERR_NOMEM);
        lpr_error("menu_pan_create");
    }

    menupan->id=id;
    menupan->menu=menu;
    menupan->win=new_panel(newwin(item_count(menu)+2, MSIZE, y, x));
    menupan->sub=new_panel(derwin(menupan->win->win,
                                  item_count(menu), MSIZE-2, 1, 1));
    wcolor_set(menupan->win->win, 1, NULL);
    set_menu_fore(menu, COLOR_PAIR(1) | A_REVERSE);
    set_menu_back(menu, COLOR_PAIR(1));
    set_menu_grey(menu, COLOR_PAIR(1));
    set_menu_win(menu, menupan->win->win);
    set_menu_sub(menu, menupan->sub->win);


    box(menupan->win->win, 0, 0);
    menupan_hide(menupan);

    return menupan;
}
예제 #8
0
void Screen::Arrows(WINDOW * const & window, const ushort x, const ushort y)
const {
	wcolor_set(window, WHITE_RED, NULL);
	mvwaddstr(window, 0, x, "vv");
	mvwaddstr(window, SCREEN_SIZE+1, x, "^^");
	HorizontalArrows(window, y);
}
예제 #9
0
void wsetcolor (WINDOW *w,int n,int m)
{
   if (m==1) wattr_set (w,A_BOLD,0,0);
   else wattr_set (w,A_NORMAL,0,0);
   wcolor_set (w,n,0);
   if ((nocolor==1) && ((n==2) || (n==3) || (n==5) || (n==7) || (n==10) || (n==11) || (n==12) || (n==13))) wattrset (w,A_REVERSE);
}
예제 #10
0
void Screen::HorizontalArrows(
		WINDOW * const & window,
		const ushort y,
		const short color)
const {
	wcolor_set(window, color, NULL);
	mvwaddch(window, y, 0, '>');
	mvwaddch(window, y, SCREEN_SIZE*2+1, '<');
}
예제 #11
0
void Screen::PrintBlock(
		const ushort x, const ushort y, const ushort z,
		WINDOW * const window)
const {
	Block * const block=w->GetBlock(x, y, z);
	const int kind=block->Kind();
	const int sub =block->Sub();
	wcolor_set(window, Color(kind, sub), NULL);
	waddch(window, CharName(kind, sub));
}
예제 #12
0
/* Initialze other windows. */
static void init_other_windows()
{
	int i;
	int xPos = 40;
	int yPos = 4;
        int lastColor = 1;
	other_chat_windows = (other_window*)malloc( sizeof(other_window) * 10 );

	for(i = 0; i < 10; i ++) {	
		other_chat_windows[i].window = newwin(2,20,yPos,xPos);
		memset(other_chat_windows[i].userName, '\0', sizeof(other_chat_windows[i].userName));
		memset(other_chat_windows[i].buffer,   '\0', sizeof(other_chat_windows[i].buffer));
		other_chat_windows[i].canDeepSix = 1;
		other_chat_windows[i].status     = ' ';

		/* Move window to new location. */
		if(i % 2 == 0) {
			if(lastColor == 1) 
                            wcolor_set(other_chat_windows[i].window, 1, NULL);
                        else
                            wcolor_set(other_chat_windows[i].window, 2, NULL);
                        
                        mvprintw(yPos+2, xPos, "--------------------");
			yPos ++;
			xPos = 60;
                        lastColor ++;
		} else {
                        if(lastColor == 1) 
                            wcolor_set(other_chat_windows[i].window, 1, NULL);
                        else
                            wcolor_set(other_chat_windows[i].window, 2, NULL);

                        mvprintw(yPos-1, xPos, "--------------------");
			yPos += 2;
			xPos = 40;
		}


                /* This ensures zig-zagging of colors. */
                if(lastColor > 1) lastColor = 0;
	}
}
예제 #13
0
파일: slk.c 프로젝트: msandiford/Freemacs
int slk_color(short color_pair)
{
    int rc;

    PDC_LOG(("slk_color() - called\n"));

    rc = wcolor_set(SP->slk_winptr, color_pair, NULL);
    _redraw();

    return rc;
}
예제 #14
0
void QueryInputWindow::refresh()
{
	wclear(this->window);
	mvwprintw(this->window, 0, 0, this->buffer.c_str());
	wcolor_set(this->window, 1, NULL);

	if(this->buffer.size() > 0 && this->cursorOffset < this->buffer.size())
	{
		stringstream ss;
		ss<<this->buffer[0];
		string character = ss.str();

		mvwprintw(this->window, 0, this->cursorOffset, character.c_str());
	}
	else
		mvwprintw(this->window, 0, this->cursorOffset, " ");

	wcolor_set(this->window, 2, NULL);

	IWindow::refresh();
}
예제 #15
0
int
vdk_screen_set_colors(vdk_screen_t *screen,short color_pair)
{
    if(screen == NULL) return -1;
    if(screen->state & VDK_SCREEN_PAUSED) return -1;
    if(!(screen->state & VDK_SCREEN_COLORIZED)) return -1;
    if(color_pair < 0) return -1;

    wbkgdset(stdscr,COLOR_PAIR(color_pair));
    wcolor_set(stdscr,color_pair,NULL);
    pair_content(color_pair,&screen->fg,&screen->bg);

    return 0;
}
예제 #16
0
파일: slk.c 프로젝트: apprisi/illumos-gate
int
slk_color(short co)
{
	int code = ERR;

#ifdef M_CURSES_TRACE
	__m_trace("slk_color(%d)", co);
#endif

	if (__m_screen->_slk._w != (WINDOW *) 0)
		code = wcolor_set(__m_screen->_slk._w, co, (void *) 0);

	return __m_return_code("slk_color", code);
}
예제 #17
0
void drawMiddle(WINDOW *middle, unsigned char field[16][16]){
    unsigned int i, n;

    //Borders
    wborder(middle, ' ', ' ', ' ', '-', ' ', ' ', '-', '-');
    
    //The field stats completely unrevealed
    wcolor_set(middle, 11, NULL);

    for(i = 0; i < 16; i++){
        //Reset the cursor
        wmove(middle, i, ((COLS-42)/2)-8);
        for(n = 0; n < 16; n++){
            waddch(middle, '#');
        }
    }
}
예제 #18
0
QString & Screen::PassString(QString & str) const {
	static const ushort note_length=144;
	echo();
	werase(notifyWin);
	wcolor_set(notifyWin, BLACK_WHITE, NULL);
	mvwaddch(notifyWin, 0, 0, ':');
	wstandend(notifyWin);
	char temp_str[note_length+1];
	wgetnstr(notifyWin, temp_str, note_length);
	str=temp_str;
	fputs(qPrintable(QString::number(w->Time())+": Command: "+str+'\n'),
		notifyLog);
	werase(notifyWin);
	wnoutrefresh(notifyWin);
	noecho();
	return str;
}
예제 #19
0
static void draw(u16 word, u16 row, u16 col) {
  wmove(term.vidwin, row, col);

  char letter = word & 0x7f;
  bool blink = word & 0x80;
  char fg = word >> 12;
  char bg = (word >> 8) & 0xf;

  if (!letter) letter = ' ';

  // use color_set() rather than COLOR_PAIR() since we may have more than 256
  // colors. unfortunately that doesn't really solve the problem, since every
  // linux that i can find still doesn't ship ncurses 6. how sad.
  wcolor_set(term.vidwin, color(fg, bg), NULL);
  if (blink) wattron(term.vidwin, A_BLINK);
  waddch(term.vidwin, letter);
  if (blink) wattroff(term.vidwin, A_BLINK);
}
예제 #20
0
파일: Curses.cpp 프로젝트: ruby6117/ccode
Point CursesWindow::putCh(int ch, const Point & pos, int color, int attr, bool preserveOldLoc)
{
  int x = pos.x(), y = pos.y();
  wstandend(m_win);
  if (!color) color = defaultColor();
  if (color) wcolor_set(m_win, color, 0);
  if (attr) wattr_on(m_win, attr, 0);
  int oldy, oldx;
  getyx(m_win, oldy, oldx);
  if (pos.isNull()) y = oldy;
  if (pos.isNull()) x = oldx;
  if (y < 0) y = oldy+y;
  if (x < 0) x = oldx+x;
  wmove(m_win, y, x);
  waddch(m_win, ch);
  if (preserveOldLoc)
    wmove(m_win, oldy, oldx);
  wstandend(m_win);  
  return curs();
}
예제 #21
0
void drawScreen(WINDOW *menu, 
                WINDOW *message, 
                WINDOW *alphabet, 
                Cryptogram *cr)
{
    // Print the menu...
    wclear(menu);
    wcolor_set(menu, 1, NULL);
    wattron(menu, WA_REVERSE);
    mvwprintw(menu, 0, 0, "%s", MENUBAR);
    wattroff(menu, WA_REVERSE);
    wmove(menu, 0, strlen(MENUBAR));

    // Print the alphabet...
    cr->paintAlphabet(alphabet);

    // Paint the message...
    cr->paintMessage(message);
    
    wrefresh(menu);
    wrefresh(message);
    wrefresh(alphabet);
}
예제 #22
0
NCURSES_EXPORT(int) (color_set) (short a1, void * z)
{
	T((T_CALLED("color_set(%d,%p)"), a1, (const void *)z)); returnCode(wcolor_set(stdscr,a1,z));
}
예제 #23
0
int main(int argc, char* argv[])
{
	int is_running = 1;
	int x_terminal_size, y_terminal_size;
        int is_lurking = 0;
        int is_yelling = 0;
        int in_deepsix = 0;
        int sending_im = 0;
        int i;

	/* josh-note:
			These need to be uncommented for the client connection to work. */
/*	int client_id = init_client("Henry");                   create a client. */
/*      init_user_list(client_id);                      init the client size user list. */

	log_init();
	log_writeln(" --------------------------- ");
	log_writeln(" > Starting BlackChat");

        signal(SIGALRM, scroll_ended_handler);

        for(i = 0; i < 26; i ++) {   /* set our message to null */
                memset(yell_messages[i], '\0', MAX_MESSAGE_LENGTH * sizeof(wchar_t)); 
        }

	transcript_buffer   = (wchar_t*)malloc(sizeof(wchar_t)*transcript_buffer_size);
	f_transcript_buffer = (wchar_t*)malloc(sizeof(wchar_t)*f_transcript_buffer_size);
    memset(client_buffer, '\0', sizeof(client_buffer));
	memset(transcript_buffer, '\0', sizeof(transcript_buffer));

	get_terminal_size(&x_terminal_size, &y_terminal_size);
	log_writeln(" > ... detecting current terminal size xy:(%d,%d)", x_terminal_size, y_terminal_size);

	log_writeln(" > ... initializing ncurses screen in raw mode");
	initscr();
//	start_color();
	init_pair(0, COLOR_WHITE,   COLOR_BLACK);
	init_pair(1, COLOR_GREEN,   COLOR_BLACK);
	init_pair(2, COLOR_YELLOW,  COLOR_BLACK);
        init_pair(3, COLOR_CYAN,    COLOR_BLACK);
        init_pair(4, COLOR_MAGENTA, COLOR_BLACK);
	raw();
	keypad(stdscr, TRUE);
	noecho();

	color_set(0, NULL);
	
	log_writeln(" > ... creating transcript and client window");
	transcript_window  				= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS,   0,0);
	fullscreen_transcript_window	= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS*2, 0,0);
	client_chat_window 				= newwin(MAX_ROWS,MAX_COLUMNS,24,0);
        lurk_win           			= newwin(MAX_ROWS,MAX_COLUMNS,24,0);
        yell_win           			= newwin(23,40,0,0);
        deepsix_win        			= newwin(23,40,0,0);
        im_win						= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS,   0,0);
        status_win					= newwin(3,40,21,40);
        info_win					= newwin(3,40,0,40);
   //     box(yell_win, '|', '-');

        set_yell_message(0, L"Hello World");
        set_yell_message(1, L"Yo dog!");
        set_yell_message(2, L"Hey everyone!");
        set_yell_message(3, L"Whats up?");
        set_yell_message(12,L"I agree.");

        wcolor_set(lurk_win,           4, NULL);
        wcolor_set(transcript_window,  3, NULL);
        wcolor_set(client_chat_window, 4, NULL);
        wcolor_set(yell_win,           2, NULL);
        wprintw(lurk_win, "Lurking... Use CTRL-L to unLurk or CTRL-Q to quit.");
	log_writeln(" > ... creating other 9 windows");
	init_other_windows();

	log_writeln(" > ... [beginning transcript]");
	write_to_transcript_window(L"***************************************");
	write_to_transcript_window(L"******** Wecome to BlackChat! *********");
	write_to_transcript_window(L"***************************************");
        
	set_window_user_name(0, L"chris");
	set_window_user_name(1, L"sue");
	set_window_user_name(2, L"dan");
	set_window_user_name(3, L"joe");
	append_text_to_window(0, L"Sup!");
	append_text_to_window(1, L"yo everyone, I'm in love with blackchat!");
	append_text_to_window(2, L"hey, my name is Dan!");
	append_text_to_window(3, L"Hey!?");

	can_deepsix_user(0, 0);
	set_user_status(1, 'L');
	set_user_status(2, 'L');
	
	/* Set our info window text. */
	wprintw(info_win, "       Black Chat  v1.0\n");
	wprintw(info_win, "UI: Henry Stratmann|Client: Josh Hartman\n");
	wprintw(info_win, "Server: Tyler Reid |Protocol: Tim Rhoads\n");
	

	while(is_running) {
		int ch = getch();
/*		wchar_t buf[512];          //get wchar_ts

		sprintf(buf, "key pressed: '%c'  int value: %d\n", ch, ch);
		write_to_transcript_window(buf);
  */                                      //end get wchar_t

            /* Check if were in "Lurk" mode. */
            if(is_lurking) {
                    switch(ch) {
                            case 12: /* lurk-off */
                                    is_lurking = 0;
                                    print_client_chat_buffer();
                                    break;
                            case 17: /* quit */
                                    is_running = 0;
                                    break;
                            default:
                                    wrefresh(lurk_win);
                    }
            }
            /* Check if were in IM mode. */
            else if(sending_im) {
            		/*
            		 TODO: Display list of users (like deepsix) to send IM to.
            		 	All IM's will be displayed on the main transcript with some type of "marker"
            		 	indicating that this was an IM.
            		 */
            		if(ch >= 48 && ch <= 57) {
            				/* josh-note:
            					Have josh send IM based on "ch" */
            		}
            
            
            		/* quit */
                    if(ch == 17) {
                    		is_running = 0;
                    }
                    
                    /* exit IM */
                    sending_im = 0;
                    window_page_up(transcript_window,            &transcript_current_line, TRANSCRIPT_MAX_COLUMNS,   transcript_buffer);
                    window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
            }
            /* Check if were in deepsix mode. */
            else if(in_deepsix) {
            		/* kick user */
            		if(ch >= 48 && ch <= 57) {
            				/* josh-note:
            					Have josh make a "kick_user(ch-48)" command. 
            					Also, have josh keep track of who user voted for and display message on transcript as to how user voted
            					and/or if they already voted for the user. */		
            		}
            
            		/* quit */
                    if(ch == 17) {
                    		is_running = 0;
                    }
                    
                    /* exit deepsix */
                    in_deepsix = 0;
                    window_page_up(transcript_window,            &transcript_current_line, TRANSCRIPT_MAX_COLUMNS,   transcript_buffer);
                    window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
            }
            /* Check if were yelling. */
            else if(is_yelling) {
                    // redrawwin(yell_win);
                    // wrefresh(yell_win);
                    int index = ch - 97;
        

                    /* Write our comment to our transcript window.  */
                    if(index >= 0 && index < 26) {
                            if( yell_messages[index][0] != '\0' ) {
                                    write_to_transcript_window( yell_messages[index] );
                            }
                    }
                    
                    is_yelling = 0;
                    redrawwin(client_chat_window);
                    wrefresh(client_chat_window);
                    redrawwin(transcript_window);
                    wrefresh(transcript_window);
            } else {
		/* Check what keys we pressed. */
		switch(ch) {
		        /*
			 * Check if we pressed a control key. */
			if(iscntrl(ch)) {
				case 7:  /* CTRL-G */
					gaudy_mode_on = (gaudy_mode_on == 1) ? 0 : 1;
					if(gaudy_mode_on) {
						client_buffer[ client_cursor_position++ ] = 2;
					} else {
						client_buffer[ client_cursor_position++ ] = 3;
					}

					/* Print out updates to the window. */
					print_client_chat_buffer();
					break;

				case 127:/* Backsapce Key (grok hack) */
				case 8:  /* CTRL-H */
					client_buffer[ wcslen(client_buffer)-1 ] = '\0';
					print_client_chat_buffer();
					break;
					
				case 9:  /* CTRL-I   /   TAB */
					if(!sending_im) {
						sending_im = 1;
						draw_im_window();
					}
					break;
					
				case 10: /* CTRL-J and CTRL-M */
		/* UNCOMMENT ME FOR USE WITH SERVER */
					{
						wchar_t *buf = NULL;


						/* If we had gaudy mode on, we need to disable it. */
						if(gaudy_mode_on) {
							client_buffer[ client_cursor_position++ ] = 3;
                                                	client_buffer[ client_cursor_position++ ] = ' ';
							gaudy_mode_on = 0;
						}


						/* Get our buffer togther to write to the transcript window. */
						buf = (wchar_t*)malloc( (wcslen(L"[Client Says]: ")+wcslen(client_buffer)+1) * sizeof(wchar_t) );
						write_to_transcript_window(L"[Client Says]: ");
						write_to_transcript_window(client_buffer);
						
					//	sprintf(buf, "[Client Says]: %ls", client_buffer);
					//	write_to_transcript_window(buf);
					}
					clear_text_from_client_typing_window();
				/*	write_out(client_id);                    enter key is pressed so send a message to the server. */
						    break;

				case 11: /* CTRL-K */
					{
						int i;
						for(i = client_cursor_position+1; i < wcslen(client_buffer); i ++) {
							client_buffer[i] = '\0';
						}
					}
					break;

					    case 12: /* CTRL-L */
							if(!is_lurking) {
							    redrawwin(lurk_win);
							    wrefresh(lurk_win);
							    is_lurking = 1;
							}
						    break;

				case 14: /* CTRL-N */
                                        alarm(5);
					user_is_scrolling = 1;
					transcript_current_line ++;

					window_page_down( transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS,
							  transcript_buffer );
							  
					window_page_down( fullscreen_transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS*2,
							  f_transcript_buffer );
					break;
				case 16: /* CTRL-P */
                                        alarm(5);
					user_is_scrolling = 1;
					transcript_current_line --;

					window_page_up( transcript_window,
						    	&transcript_current_line,
							TRANSCRIPT_MAX_COLUMNS,
							transcript_buffer );
							
					window_page_up( fullscreen_transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS*2,
							  f_transcript_buffer );
					break;
		
				case 17: /* CTRL-Q */ 
					log_writeln(" > ... recived quit signal from client");
					is_running = 0;
					break;
		
				case 20: /* CTRL-T */
					if(transcript_maxed) {
						transcript_maxed = 0;
						window_page_up(transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS, transcript_buffer);
						wclear(fullscreen_transcript_window);
						wrefresh(fullscreen_transcript_window);
					} else {
						transcript_maxed = 1;
						window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
						wclear(transcript_window);
						wrefresh(transcript_window);
					}
					break;
		
				case 21: /* CTRL-U */
					client_current_line = 0;
					client_cursor_position = 0;
					memset(client_buffer, '\0', wcslen(client_buffer)+1);	
					print_client_chat_buffer();
					break;

				case 23: /* CTRL-W */
					delete_last_word_in_buffer(client_buffer);
					print_client_chat_buffer();
					break;
                                case 25: /* CTRL-Y */
                                        {
                                            if(!is_yelling)
                                            {
                                                redrawwin(yell_win);
                                                wrefresh(yell_win);
                                                is_yelling = 1;
                                            }
                                        }
                                        break; 
				case 29: /* CTRL-] */
                                        alarm(0);
					user_is_scrolling = 0;
					print_transcript_chat_buffer();
					break;
                                case 30: /* CTRL-6 */
                                        if(!in_deepsix)
                                        {
                                            draw_deepsix_window();
                                            in_deepsix = 1;
                                        }
                                        break;

                                /*
                                 * If we encountered an unkown escape wchar_tcter, break out of here so we don't
                                 * print it. */
                                break;              /* TODO: Fix me! */
			}
#if 0
			/* Scroll the clients typing window down. */
			case KEY_DOWN:
				client_current_line ++;
				if(client_current_line*MAX_COLUMNS > wcslen(client_buffer)) client_current_line --;

					    wclear(client_chat_window);
					    wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
					    break;
			/* Scroll the clients typing window up. */
			case KEY_UP:
				client_current_line --;
				if(client_current_line < 0) client_current_line = 0;

					    wclear(client_chat_window);
					    wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
					    break;
#endif
			/* Delete the previous chracter. */
			case KEY_BACKSPACE:
				/* Check if were deleting the last wchar_tacter. */
				if( client_cursor_position == wcslen(client_buffer) ) {
					client_buffer[ client_cursor_position-1 ] = '\0';
					client_cursor_position --;
					print_client_chat_buffer();
				} else {
					/* If were here, that means were NOT deleting the last wchar_tacter. */
					int i;
					for(i = client_cursor_position-1; i < wcslen(client_buffer); i ++) {
						client_buffer[i] = client_buffer[i+1];
					}
					client_cursor_position --;
					print_client_chat_buffer();
				}
				break;

			/* If were here, that means we didn't press any "special" keys so that means were
			 * trying to write some generic wchar_tacters to our chat window. */
			default:
				/* Make sure we don't print a control wchar_tacter. */
				if(!iscntrl(ch)) {
					/* Check if were inserting a wchar_tacter before the end of our client
					 * typing buffer. */
					if( client_cursor_position != wcslen(client_buffer) ) {
	
						/* Move all wchar_tacters in front of the cursor up one. */
						int i;
						for(i = wcslen(client_buffer)+1; i > client_cursor_position; i --) {
							client_buffer[i] = client_buffer[i-1];
						}
					}

					/* Add the wchar_tacter to our buffer. */
					client_buffer[ client_cursor_position++ ] = ch;

					/* Print our new/updated buffer. */
					print_client_chat_buffer();
					break;
				}
			}
		}

        	/* Read from the server. */
        	/* josh-note
        			Uncomment this! */
/*      	read_from_server(client_id); */

        	refresh_all_windows(is_lurking);
	}

	log_writeln(" > ... [ending transcript]");
	log_writeln(" > ... freeing resources");
	free_other_windows();
	free(transcript_buffer);

	delwin(transcript_window);
	delwin(fullscreen_transcript_window);
	delwin(client_chat_window);
	delwin(status_win);
	delwin(info_win);
	delwin(im_win);
	delwin(deepsix_win);
	delwin(yell_win);
	endwin();
        
    /* josh-note
    		This should be uncommented to close down the client socket. */
/*  close_client(client_id); */

	log_writeln(" > ... closing client log");
	log_writeln(" > ... bye bye for now!");
	log_close();
	return 0;
}
예제 #24
0
파일: fmtext.c 프로젝트: arlynap/barnowl
void _owl_fmtext_wcolor_set(WINDOW *w, short pair) /*noproto*/
{
  if (owl_global_get_hascolors(&g)) {
      wcolor_set(w,pair,NULL);
  }
}
예제 #25
0
void Screen::PrintFront(WINDOW * const window) const {
	const int dir=player->Dir();
	if ( UP==dir || DOWN==dir ) {
		wstandend(window);
		werase(window);
		box(window, 0, 0);
		mvwaddstr(window, 0, 1, "No view");
		wnoutrefresh(window);
		return;
	}
	short x_step, z_step,
	      x_end, z_end,
	      * x, * z,
	      i, j, k;
	const ushort pX=player->X();
	const ushort pY=player->Y();
	const ushort pZ=player->Z();
	const ushort begin_x = ( pX/SHRED_WIDTH )*SHRED_WIDTH +
		( SHRED_WIDTH-SCREEN_SIZE )/2;
	const ushort begin_y = ( pY/SHRED_WIDTH )*SHRED_WIDTH +
		( SHRED_WIDTH-SCREEN_SIZE )/2;
	ushort x_start, z_start, k_start;
	ushort arrow_Y, arrow_X;
	switch ( dir ) {
		case NORTH:
			x=&i;
			x_step=1;
			x_start=begin_x;
			x_end=x_start+SCREEN_SIZE;
			z=&j;
			z_step=-1;
			z_start=pY-1;
			z_end=pY-SHRED_WIDTH-1;
			arrow_X=(pX-begin_x)*2+1;
		break;
		case SOUTH:
			x=&i;
			x_step=-1;
			x_start=SCREEN_SIZE-1+begin_x;
			x_end=begin_x-1;
			z=&j;
			z_step=1;
			z_start=pY+1;
			z_end=pY+SHRED_WIDTH+1;
			arrow_X=(SCREEN_SIZE-pX+begin_x)*2-1;
		break;
		case WEST:
			x=&j;
			x_step=-1;
			x_start=SCREEN_SIZE-1+begin_y;
			x_end=begin_y-1;
			z=&i;
			z_step=-1;
			z_start=pX-1;
			z_end=pX-SHRED_WIDTH-1;
			arrow_X=(SCREEN_SIZE-pY+begin_y)*2-1;
		break;
		case EAST:
			x=&j;
			x_step=1;
			x_start=begin_y;
			x_end=SCREEN_SIZE+begin_y;
			z=&i;
			z_step=1;
			z_start=pX+1;
			z_end=pX+SHRED_WIDTH+1;
			arrow_X=(pY-begin_y)*2+1;
		break;
		default:
			fprintf(stderr,
				"Screen::PrintFront(WINDOW *): \
				unlisted dir: %d\n",
				(int)dir);
			return;
	}
	if ( pZ+SCREEN_SIZE/2>=HEIGHT ) {
		k_start=HEIGHT-2;
		arrow_Y=HEIGHT-pZ;
	} else if ( pZ-SCREEN_SIZE/2<0 ) {
		k_start=SCREEN_SIZE-1;
		arrow_Y=SCREEN_SIZE-pZ;
	} else {
		k_start=pZ+SCREEN_SIZE/2;
		arrow_Y=SCREEN_SIZE/2+1;
	}
	const int block_side=w->Anti(dir);
	(void)wmove(window, 1, 1);
	for (k=k_start; k_start-k<SCREEN_SIZE; --k, waddstr(window, "\n_")) {
		for (*x=x_start; *x!=x_end; *x+=x_step) {
			for (*z=z_start; *z!=z_end; *z+=z_step)
				if ( w->Transparent(i, j, k) != INVISIBLE ) {
					if ( (w->Enlightened(i, j, k,
							block_side) &&
							player->
							Visible(i, j, k)) ||
							player->
							GetCreativeMode() )
					{
						PrintBlock(i, j, k, window);
						waddch(window,
							CharNumberFront(i, j));
					} else {
						wstandend(window);
						waddch(window, OBSCURE_BLOCK);
						waddch(window, ' ');
					}
					break;
				}
			if ( *z==z_end ) { //far decorations
				*z-=z_step;
				if ( player->Visible(i, j, k ) ) {
					wcolor_set(window, Color(BLOCK, SKY),
						NULL);
					waddch(window, CharName(BLOCK, SKY));
				} else {
					wstandend(window);
					waddch(window, OBSCURE_BLOCK);
				}
				waddch(window, ' ');
			}
		}
	}
	wstandend(window);
	box(window, 0, 0);
	switch ( dir ) {
		case NORTH: mvwaddstr(window, 0, 1, "North view"); break;
		case SOUTH: mvwaddstr(window, 0, 1, "South view"); break;
		case EAST:  mvwaddstr(window, 0, 1, "East view");  break;
		case WEST:  mvwaddstr(window, 0, 1, "West view");  break;
	}
	Arrows(window, arrow_X, arrow_Y);
	if ( shiftFocus ) {
		HorizontalArrows(window, arrow_Y-=shiftFocus, WHITE_BLUE);
	}
	wnoutrefresh(window);
}
예제 #26
0
void Screen::Print() {
	w->ReadLock();

	if ( updated || !player ) {
		w->Unlock();
		return;
	}
	updated=true;

	switch ( player->UsingType() ) {
		case OPEN:
			PrintInv(rightWin,
				player->UsingBlock()->HasInventory());
			break;
		default: PrintFront(rightWin);
	}
	switch ( player->UsingSelfType() ) {
		case OPEN:
			if ( player->PlayerInventory() ) {
				PrintInv(leftWin,
					player->PlayerInventory());
				break;
			} //no break;
		default: PrintNormal(leftWin);
	}

	const short dur=player->HP();
	const short breath=player->Breath();
	const short satiation=player->Satiation();

	werase(hudWin);
	ushort i;
	//quick inventory
	Inventory * const inv=player->GetP() ?
		player->GetP()->HasInventory() : 0;
	if ( inv ) {
		for (i=0; i<inv->Size(); ++i) {
			wstandend(hudWin);
			const int x=36+i*2;
			mvwaddch(hudWin, 0, x, 'a'+i);
			if ( inv->Number(i) ) {
				wcolor_set(hudWin,
					Color( inv->GetInvKind(i),
						inv->GetInvSub(i) ), NULL);
				mvwaddch(hudWin, 1, x,
					CharName( inv->GetInvKind(i),
						inv->GetInvSub(i) ));
				mvwprintw(hudWin, 2, x, "%hu", inv->Number(i));
			}
		}
	}

	w->Unlock();

	wstandend(leftWin);
	QString str;
	if ( -1!=dur ) { //HitPoints line
		str=QString("%1").arg(dur, -10, 10, QChar('.'));
		mvwaddstr(leftWin, SCREEN_SIZE+1, 1, "HP[..........]");
		wcolor_set(leftWin, WHITE_RED, NULL);
		mvwaddstr(leftWin, SCREEN_SIZE+1, 4,
			qPrintable(str.left(10*dur/MAX_DURABILITY+1)));
		wstandend(leftWin);
	}
	if ( -1!=breath ) { //breath line
		str=QString("%1").arg(breath, -10, 10, QChar('.'));
		mvwaddstr(leftWin, SCREEN_SIZE+1, SCREEN_SIZE*2-13,
			"BR[..........]");
		wcolor_set(leftWin, WHITE_BLUE, NULL);
		mvwaddstr(leftWin, SCREEN_SIZE+1, SCREEN_SIZE*2-13+3,
			qPrintable(str.left(10*breath/MAX_BREATH+1)));
	}
	//action mode
	(void)wmove(hudWin, 0, 0);
	wstandend(hudWin);
	waddstr(hudWin, "Action: ");
	switch ( actionMode ) {
		case USE:      waddstr(hudWin, "Use in inventory"); break;
		case THROW:    waddstr(hudWin, "Throw"); break;
		case OBTAIN:   waddstr(hudWin, "Obtain"); break;
		case WIELD:    waddstr(hudWin, "Wield"); break;
		case INSCRIBE: waddstr(hudWin, "Inscribe in inventory"); break;
		case EAT:      waddstr(hudWin, "Eat"); break;
		case BUILD:    waddstr(hudWin, "Build"); break;
		case CRAFT:    waddstr(hudWin, "Craft"); break;
		case TAKEOFF:  waddstr(hudWin, "Take off"); break;
		default:       waddstr(hudWin, "Unknown");
			fprintf(stderr,
				"Screen::Print: Unlisted actionMode: %d\n",
				actionMode);
	}
	if ( -1!=satiation ) { //satiation line
		(void)wmove(hudWin, 1, 0);
		if ( SECONDS_IN_DAY<satiation ) {
			wcolor_set(hudWin, BLUE_BLACK, NULL);
			waddstr(hudWin, "Gorged");
		} else if ( 3*SECONDS_IN_DAY/4<satiation ) {
			wcolor_set(hudWin, GREEN_BLACK, NULL);
			waddstr(hudWin, "Full");
		} else if (SECONDS_IN_DAY/4>satiation) {
			wcolor_set(hudWin, RED_BLACK, NULL);
			waddstr(hudWin, "Hungry");
		}
	}
	//shifted focus
	wstandend(hudWin);
	if ( shiftFocus ) {
		mvwaddstr(hudWin, 0, 100, ( -1==shiftFocus ) ?
			"Focus shift down" : "Focus shift up");
	}
	if ( player->GetCreativeMode() ) {
		mvwaddstr(leftWin, SCREEN_SIZE+1, 1, "Creative Mode");
		//coordinates
		mvwprintw(hudWin, 1, 0, "xyz: %hu, %hu, %hu. XY: %ld, %ld",
			player->X(), player->Y(), player->Z(),
			player->GetLatitude(), player->GetLongitude());
		wcolor_set(leftWin, BLACK_WHITE, NULL);
		switch ( player->Dir() ) {
			case NORTH:
				mvwaddstr(leftWin, SCREEN_SIZE+1,
					SCREEN_SIZE*2-8, "^ North ^");
			break;
			case SOUTH:
				mvwaddstr(leftWin, SCREEN_SIZE+1,
					SCREEN_SIZE*2-8, "v South v");
			break;
			case EAST:
				mvwaddstr(leftWin, SCREEN_SIZE+1,
					SCREEN_SIZE*2-8, ">   East>");
			break;
			case WEST:
				mvwaddstr(leftWin, SCREEN_SIZE+1,
					SCREEN_SIZE*2-8, "<West   <");
			break;
		}
	} else if ( player->GetP() && player->GetP()->IsFalling() ) {
			mvwaddstr(hudWin, 2, 0, "Falling!");
	}
	wnoutrefresh(hudWin);
	wnoutrefresh(leftWin);
	doupdate();
}
예제 #27
0
파일: main-0.3.c 프로젝트: alanszlosek/knox
// pass number of terminals on commandline
int main(int argc, char *argv[]) {
	// Virtual Terminal related
	struct virtualTerminal *vt;

	// nCurses related variables
	WINDOW *ncursesScreen;
	int screenWidth, screenHeight, vtColumns, vtRows; // to hold screen's height and width

	// Miscellaneous variables
	unsigned int input;
	char ch;
	char inputString[33];
	int i, j, k, done, fdMax, fdCurrent, inputSize;
	int *vtCoordinates, *vtPointer;
	fd_set fileDescriptors;
	struct timespec timeout;
	struct sigaction sa;
	linkedList *llTerminals;
	linkedListNode *llNode;

	//mtrace();
	// Set up signal handling
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = &signalHandler;
	sigaction(SIGTERM, &sa, NULL);

	// Initializations
	llTerminals = listNew();
	done = fdMax = 0;
	timeout.tv_sec = 0;
	timeout.tv_nsec = 500000000; // 10E-9

	// Initialize terminal
	ncursesScreen = initscr();
	if(ncursesScreen == NULL) {
		perror("Error initializing nCurses\n");
		exit(1);
	}

	if(has_colors()) {
		start_color();
	}

	keypad(ncursesScreen, true); // cause nCurses to package key combos into special, single values
	noecho(); // don't echo input
	refresh(); // clear the main window

	// Get main window dimensions. This will be used when creating additional virtual terminals
	getmaxyx(ncursesScreen, screenHeight, screenWidth);
	//vtRows = (vtRows / 2); // - (vtRows % 4);
	//vtCols = (vtCols / 2); // - (vtCols % 4);

	//fprintf(stderr, "Rows: %d Cols: %d\n", vtRows, vtCols);

	// set j equal to number of terminals
	if(argc > 1)
		j = atoi(argv[1]);
	else
		j = 1;


	//vtPointer = vtCoordinates = rectangleCoordinates_favorWidth(screenWidth, screenHeight, j, 1);
	vtPointer = vtCoordinates = rectangleCoordinates_favorHeight(screenWidth, screenHeight, j, 0);
	for(i = 0; i < j; i++) {
		vt = vtCreate( *(vtPointer + 2), *(vtPointer + 3), *vtPointer, *(vtPointer + 1), i);
		listAppendCargo(llTerminals, vt);
		vtPointer += 4;
	}

	llNode = listFirst(llTerminals);
	vt = (struct virtualTerminal*) nodeCargo(llNode);
	fdCurrent = vt->fd;
	//fprintf(stderr, "fd %d\n",fdCurrent);
	k = 0;

	while(!done) {
		FD_ZERO(&fileDescriptors);
		FD_SET(0, &fileDescriptors);
		llNode = listFirst(llTerminals);
		fdMax = 0;
		while(llNode != NULL) {
			vt = (struct virtualTerminal*) nodeCargo(llNode);
			if(vt->fd > 0 && vt->state != VT_PAUSED) { // fd will be -1 if shell program has exited
				j = vt->fd;
				if(j > fdMax)
					fdMax = j;
				FD_SET(j, &fileDescriptors);
			}
			llNode = listNext(llNode);
		}

		pselect(fdMax + 1, &fileDescriptors, NULL, NULL, &timeout, NULL); 

		if(FD_ISSET(0, &fileDescriptors)) {
			inputSize = read(0, &ch, 1);
			//for(i = 0; i < inputSize; i++) {
				switch(ch) { //inputString[i]) {
			
					case '`': // tab
						wcolor_set(((struct virtualTerminal*)listNodeIndex(llTerminals ,k))->window, 1, NULL);
						k++;
						if(k == llTerminals->length)
							k = 0;
						fdCurrent = TtyTerminalIO_get_associated_fd( ((struct virtualTerminal*)listNodeIndex(llTerminals ,k))->terminalIO );
						break;

					case '~':
						done = 1;
						break;

					default:
						//ch = inputString[i];

						write(fdCurrent, &ch, 1);
						break;
				}
			//}
		}

		j = 0; // temporarily keep track of whether any windows were updated
		llNode = listFirst(llTerminals);
		while(llNode != NULL) {
			vt = (struct virtualTerminal*) nodeCargo(llNode);
			if(vt->fd > 0 && FD_ISSET(vt->fd, &fileDescriptors) && vt->state != VT_PAUSED) { // fd will be -1 if shell has closed
				VTCore_dispatch(vt->core);
			
				wnoutrefresh(vt->wBorder); // updates backbuffered nCurses window
				wnoutrefresh(vt->window); // updates backbuffered nCurses window
				j = 1; // specifies whether we should flush nCurses buffered windows
			}
			llNode = listNext(llNode);
		}
		if(j)
			doupdate(); // updates were made, wnoutrefresh() was called, now flush updates

		switch(previousSignal) {
			case SIGTERM:
				fprintf(stderr, "Caught SIGTERM\n");
				done = 1;
				break;
			default:
				break;
		}
	}

	llNode = listFirst(llTerminals);
	while(llNode != NULL) {
		vt = (struct virtualTerminal*) nodeCargo(llNode);
		//fprintf(stderr,"Terminal %d\n", vt->id);
		llNode = listNext(llNode);
	}

	free(vtCoordinates);
	listDelete(llTerminals, vtDestroy);
	endwin();

	return 0;
}
예제 #28
0
void fileMenu(WINDOW *menu, Cryptogram *cr)
{
    char filename[255];
    char key;
    char *editor = NULL;
    char command[1024] = "";
    while (1)
    {
        wclear(menu);
        wcolor_set(menu, 1, NULL);
        wattron(menu, WA_REVERSE);
        mvwprintw(menu, 0, 0, "%s", FILEMENU);
        wattroff(menu, WA_REVERSE);
        wmove(menu, 0, strlen(FILEMENU));
        wrefresh(menu);

        noecho();
        key = getch();
        echo();
        switch(key)
        {
            case 'L':
            case 'l':
                wclear(menu);
                mvwprintw(menu, 0, 0, "File to open? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                cr->loadFile(filename);
                cr->calcPlaintext();
                return;
            case 'T':
            case 't':
                wclear(menu);
                mvwprintw(menu, 0, 0, "Text file to save? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                cr->saveFileText(filename);
                cr->calcPlaintext();
                return;
            case 'B':
            case 'b':
                wclear(menu);
                mvwprintw(menu, 0, 0, "Binary file to save? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                cr->saveFileBinary(filename);
                cr->calcPlaintext();
                return;
            case 'N':
            case 'n':
                wclear(menu);
                mvwprintw(menu, 0, 0, "File to create? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                editor = getenv("VISUAL");
                if (!editor)
                    editor = getenv("EDITOR");
                if (!editor)
                    return;
                strncpy(command, editor, 512);
                strcat(command, " ");
                strcat(command, filename);
                system(command);
                cr->loadFile(filename);
                cr->calcPlaintext();
                return;
            case 'S':
            case 's':
                wclear(menu);
                mvwprintw(menu, 0, 0, "File to save keys to? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                cr->saveKeys(filename);
                return;
            case 'K':
            case 'k':
                wclear(menu);
                mvwprintw(menu, 0, 0, "File to load keys from? ");
                wrefresh(menu);
                wgetnstr(menu, filename, 255);
                filename[254] = 0;
                cr->loadKeys(filename);
                return;
            case 'C':
            case 'c':
                return;
        }
    }
}
예제 #29
0
int color_set(short color_pair, void *opts)
{
    PDC_LOG(("color_set() - called\n"));

    return wcolor_set(stdscr, color_pair, opts);
}
예제 #30
0
int main(int argc, char *argv[]) {
	wispy_device_list list;
	int x = 0, r = 0, y = 0, ndev = 0;
	wispy_sample_sweep *sb = NULL;
	wispy_sweep_cache *sweepcache = NULL;
	spectool_server sr;
	char errstr[WISPY_ERROR_MAX];
	int ret;

	WINDOW *window;
	WINDOW *sigwin;
	WINDOW *chwin;

	int graph_bg = 0, graph_peak = 0, graph_avg = 0;

	int amp_offset_mdbm = 0, amp_res_mdbm = 0, base_db_offset = 0;
	int min_db_draw = 0, start_db = 0;
	int nuse = 0, mod, avg, avgc, pos, group;

	int range = 0;
	int device = -1;
	int list_only = 0;

	static struct option long_options[] = {
		{ "net", required_argument, 0, 'n' },
		{ "list", no_argument, 0, 'l' },
		{ "device", required_argument, 0, 'd' },
		{ "range", required_argument, 0, 'r' },
		{ "help", no_argument, 0, 'h' },
		{ 0, 0, 0, 0 }
	};
	int option_index;

	char *neturl = NULL;

	ndev = wispy_device_scan(&list);

	while (1) {
		int o = getopt_long(argc, argv, "n:ld:r:h",
							long_options, &option_index);

		if (o < 0)
			break;

		if (o == 'h') {
			Usage();
			return;
		} else if (o == 'n') {
			neturl = strdup(optarg);
			continue;
		} else if (o == 'r') {
			if (sscanf(optarg, "%d", &range) != 1) {
				printf("Expected number for range, see listing for supported ranges\n");
				Usage();
				return;
			}
			continue;
		} else if (o == 'd') {
			if (sscanf(optarg, "%d", &device) != 1) {
				printf("Expected number for device, see listing for detected devices\n");
				Usage();
				return;
			}

			if (device < 0 || device >= ndev) {
				printf("Device number invalid, see listing for detected devices\n");
				Usage();
				return;
			}

			continue;
		} else if (o == 'l') {
			list_only = 1;
		}
	}

	if (list_only) {
		if (ndev <= 0) {
			printf("No wispy devices found, bailing\n");
			exit(1);
		}

		printf("Found %d devices...\n", ndev);

		for (x = 0; x < ndev; x++) {
			printf("Device %d: %s id %u\n", 
				   x, list.list[x].name, list.list[x].device_id);

			for (r = 0; r < list.list[x].num_sweep_ranges; r++) {
				wispy_sample_sweep *ran = 
					&(list.list[x].supported_ranges[r]);

				printf("  Range %d: \"%s\" %d%s-%d%s @ %0.2f%s, %d samples\n", r, 
					   ran->name,
					   ran->start_khz > 1000 ? 
					   ran->start_khz / 1000 : ran->start_khz,
					   ran->start_khz > 1000 ? "MHz" : "KHz",
					   ran->end_khz > 1000 ? ran->end_khz / 1000 : ran->end_khz,
					   ran->end_khz > 1000 ? "MHz" : "KHz",
					   (ran->res_hz / 1000) > 1000 ? 
					   		((float) ran->res_hz / 1000) / 1000 : ran->res_hz / 1000,
					   (ran->res_hz / 1000) > 1000 ? "MHz" : "KHz",
					   ran->num_samples);
			}

		}

		exit(0);
	}
	signal(SIGINT, sighandle);

	if (neturl != NULL) {
		printf("Initializing network connection...\n");

		if (spectool_netcli_init(&sr, neturl, errstr) < 0) {
			printf("Error initializing network connection: %s\n", errstr);
			exit(1);
		}

		if (spectool_netcli_connect(&sr, errstr) < 0) {
			printf("Error opening network connection: %s\n", errstr);
			exit(1);
		}

		printf("Connected to server, waiting for device list...\n");
	} else if (neturl == NULL) {
		if (ndev <= 0) {
			printf("No wispy devices found, bailing\n");
			exit(1);
		}

		printf("Found %d wispy devices...\n", ndev);

		if (ndev > 1 && device == -1) {
			printf("spectool-curses can only display one device, specify one with "
				   "spectool-curses -d\n");
			exit(1);
		} else if (device == -1) {
			device = 0;
		}

		if (range < 0 || range >= list.list[device].num_sweep_ranges) {
			printf("Invalid range for device %d, see listing for supported ranges\n",
				   device);
			exit(1);
		}

		dev = (wispy_phy *) malloc(WISPY_PHY_SIZE);
		dev->next = NULL;

		if (wispy_device_init(dev, &(list.list[device])) < 0) {
			printf("Error initializing WiSPY device %s id %u\n",
				   list.list[device].name, list.list[device].device_id);
			printf("%s\n", wispy_get_error(dev));
			exit(1);
		}

		if (wispy_phy_open(dev) < 0) {
			printf("Error opening WiSPY device %s id %u\n",
				   list.list[device].name, list.list[device].device_id);
			printf("%s\n", wispy_get_error(dev));
			exit(1);
		}

		wispy_phy_setcalibration(dev, 1);

		/* Configure the range */
		wispy_phy_setposition(dev, range, 0, 0);

		wispy_device_scan_free(&list); 
	}

	sweepcache = wispy_cache_alloc(50, 1, 1);

	/* Fire up curses */
	initscr();
	start_color();
	cbreak();
	noecho();

	init_pair(1, COLOR_BLACK, COLOR_BLACK);
	init_pair(2, COLOR_BLUE, COLOR_BLUE);
	init_pair(3, COLOR_GREEN, COLOR_GREEN);
	init_pair(4, COLOR_YELLOW, COLOR_BLACK);
	init_pair(5, COLOR_YELLOW, COLOR_BLUE);
	init_pair(6, COLOR_YELLOW, COLOR_GREEN);

	window = subwin(stdscr, LINES - 2, COLS - 5, 0, 5);
	sigwin = subwin(stdscr, LINES - 2, 5, 0, 0);

	box(window, 0, 0);
	mvwaddstr(sigwin, 0, 0, " dBm ");

	wrefresh(window);
	wrefresh(sigwin);
	refresh();

	/* Naive poll that doesn't use select() to find pending data */
	while (1) {
		fd_set rfds;
		fd_set wfds;
		int maxfd = 0;
		struct timeval tm;

		FD_ZERO(&rfds);
		FD_ZERO(&wfds);

		if (wispy_phy_getpollfd(dev) >= 0) {
			FD_SET(wispy_phy_getpollfd(dev), &rfds);

			if (wispy_phy_getpollfd(dev) > maxfd)
				maxfd = wispy_phy_getpollfd(dev);
		}

		if (neturl != NULL) {
			if (spectool_netcli_getpollfd(&sr) >= 0) {
				FD_SET(spectool_netcli_getpollfd(&sr), &rfds);

				if (spectool_netcli_getpollfd(&sr) > maxfd)
					maxfd = spectool_netcli_getpollfd(&sr);
			}

			if (spectool_netcli_getwritepend(&sr) > 0) {
				FD_SET(spectool_netcli_getwritefd(&sr), &wfds);

				if (spectool_netcli_getwritefd(&sr) > maxfd)
					maxfd = spectool_netcli_getwritefd(&sr);
			}
		}

		tm.tv_sec = 0;
		tm.tv_usec = 10000;

		if (select(maxfd + 1, &rfds, &wfds, NULL, &tm) < 0) {
			printf("wispy_raw select() error: %s\n", strerror(errno));
			exit(1);
		}

		if (spectool_netcli_getwritefd(&sr) >= 0 &&
			FD_ISSET(spectool_netcli_getwritefd(&sr), &wfds)) {
			if (spectool_netcli_writepoll(&sr, errstr) < 0) {
				printf("Error write-polling network server %s\n", errstr);
				exit(1);
			}
		}

		ret = SPECTOOL_NETCLI_POLL_ADDITIONAL;
		while (spectool_netcli_getpollfd(&sr) >= 0 &&
			   FD_ISSET(spectool_netcli_getpollfd(&sr), &rfds) &&
			   (ret & SPECTOOL_NETCLI_POLL_ADDITIONAL)) {

			if ((ret = spectool_netcli_poll(&sr, errstr)) < 0) {
				printf("Error polling network server %s\n", errstr);
				exit(1);
			}

			if ((ret & SPECTOOL_NETCLI_POLL_NEWDEVS)) {
				/* Only enable the first device */
				spectool_net_dev *ndi = sr.devlist;

				dev = spectool_netcli_enabledev(&sr, ndi->device_id, errstr);
			}
		}

		if (wispy_phy_getpollfd(dev) < 0) {
			if (wispy_get_state(dev) == WISPY_STATE_ERROR) {
				printf("Error polling wispy device %s\n",
					   wispy_phy_getname(dev));
				printf("%s\n", wispy_get_error(dev));
				exit(1);
			}
		}

		if (FD_ISSET(wispy_phy_getpollfd(dev), &rfds) == 0) {
			continue;
		}

		do {
			r = wispy_phy_poll(dev);

			if ((r & WISPY_POLL_CONFIGURED)) {
				wispy_sample_sweep *ran = &(dev->device_spec->supported_ranges[0]);

				amp_offset_mdbm = ran->amp_offset_mdbm;
				amp_res_mdbm = ran->amp_res_mdbm;
				base_db_offset =
					WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm,
									   ran->rssi_max);
				min_db_draw =
					WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm, 0);

				continue;
			} else if ((r & WISPY_POLL_ERROR)) {
				printf("Error polling wispy device %s\n",
					   wispy_phy_getname(dev));
				printf("%s\n", wispy_get_error(dev));
				exit(1);
			} else if ((r & WISPY_POLL_SWEEPCOMPLETE)) {
				sb = wispy_phy_getsweep(dev);
				if (sb == NULL)
					continue;

				wispy_cache_append(sweepcache, sb);

				min_db_draw =
					WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm,
									   sb->min_rssi_seen > 2 ?
									   sb->min_rssi_seen - 1 : sb->min_rssi_seen);

			}
		} while ((r & WISPY_POLL_ADDITIONAL));

		/* Redraw the windows */
		werase(sigwin);
		mvwaddstr(sigwin, 0, 0, " dBm ");

		start_db = 0;
		for (x = base_db_offset - 1; x > min_db_draw; x--) {
			if (x % 10 == 0) {
				start_db = 0;
				break;
			}
		}

		if (start_db == 0)
			start_db = base_db_offset;

		for (x = start_db; x > min_db_draw; x -= 10) {
			int py;

			py = (float) (LINES - 4) * 
				(float) ((float) (abs(x) + base_db_offset) /
						 (float) (abs(min_db_draw) + base_db_offset));

			snprintf(errstr, WISPY_ERROR_MAX, "%d", x);
			mvwaddstr(sigwin, py + 1, 0, errstr);
		}

		werase(window);

		if (sweepcache->latest == NULL) {
			wrefresh(window);
			wrefresh(sigwin);
			refresh();
			continue;
		}

		/* Interpolate the data down into an appropriate graph */
		mod = ceilf((float) sweepcache->avg->num_samples / (float) (COLS - 7));
		group = mod * 2;

		r = 0;
		for (x = 0; x < (COLS - 7); x++) {
			int py, pyc;

			avg = 0;
			avgc = 0;
			nuse = 0;

			r = ((float) x / (float) (COLS - 7)) * 
				(float) sweepcache->peak->num_samples;

			for (pos = -1 * (group / 2); pos < (group / 2); pos++) {
				if (r + pos >= sweepcache->peak->num_samples || r + pos < 0)
					continue;

				avg += sweepcache->peak->sample_data[r + pos];
				avgc += sweepcache->latest->sample_data[r + pos];
				nuse++;
			}

			if (nuse == 0)
				continue;

			avg = WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm, (avg / nuse));
			avgc = WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm, (avgc / nuse));

			py = (float) (LINES - 4) *
				(float) ((float) (abs(avg) + base_db_offset) /
						 (float) (abs(min_db_draw) + base_db_offset));

			pyc = (float) (LINES - 4) *
				(float) ((float) (abs(avgc) + base_db_offset) /
						 (float) (abs(min_db_draw) + base_db_offset));

			for (y = 0; y < (LINES - 4); y++) {
				if (pyc == y) {
					if (py > y)
						wcolor_set(window, 4, NULL);
					else
						wcolor_set(window, 5, NULL);

					mvwaddstr(window, y + 1, x + 1, "#");
					continue;
				}

				if (py > y)
					continue;

				wcolor_set(window, 2, NULL);
				mvwaddstr(window, y + 1, x + 1, " ");
			}
		}

		r = 0;
		for (x = 0; x < (COLS - 7); x++) {
			int py, pyc;

			avg = 0;
			avgc = 0;
			nuse = 0;

			r = ((float) x / (float) (COLS - 7)) * 
				(float) sweepcache->avg->num_samples;

			for (pos = -1 * (group / 2); pos < (group / 2); pos++) {
				if (r + pos >= sweepcache->avg->num_samples || r + pos < 0)
					continue;

				avg += sweepcache->avg->sample_data[r + pos];
				avgc += sweepcache->latest->sample_data[r + pos];
				nuse++;
			}

			if (nuse == 0)
				continue;

			avg = WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm, (avg / nuse));
			avgc = WISPY_RSSI_CONVERT(amp_offset_mdbm, amp_res_mdbm, (avgc / nuse));

			py = (float) (LINES - 4) *
				(float) ((float) (abs(avg) + base_db_offset) /
						 (float) (abs(min_db_draw) + base_db_offset));

			pyc = (float) (LINES - 4) *
				(float) ((float) (abs(avgc) + base_db_offset) /
						 (float) (abs(min_db_draw) + base_db_offset));

			for (y = 0; y < (LINES - 4); y++) {
				if (pyc == y && y >= py) {
					wcolor_set(window, 6, NULL);

					mvwaddstr(window, y + 1, x + 1, "#");
					continue;
				}

				if (py > y)
					continue;

				wcolor_set(window, 3, NULL);
				mvwaddstr(window, y + 1, x + 1, "m");
			}
		}

		wcolor_set(window, 0, NULL);
		box(window, 0, 0);

		wrefresh(window);
		wrefresh(sigwin);
		refresh();
	}

	endwin();
	return 0;
}