
/*
 * Demo zur Curses-Color-Unterstuetzung
 */
#include <ncurses.h>
short int  i=0,f, b, R, B, G;

#define FORGROUND 1
#define BACKGROUND 0

void modf(int setting);		
void fillwin(void);
void process(void);
void setfb(char setting);
void modfb(int setting);		


void main(int argc, char ** argv) 
{
	initscr();
	keypad(stdscr, TRUE);
	cbreak();
	noecho();
	scrollok(stdscr, TRUE);
	
	if(!has_colors()) {
                endwin();
		fprintf(stderr, "\ncolor not supported \n");
		exit(1);
	}
	
	start_color();
	init_pair(1, COLOR_WHITE, COLOR_BLACK);
	attron(COLOR_PAIR(1));
	
	process();
	endwin();
}

void fillwin(void)
{
	register int y, x;
	
	move(0,0);
	for(y = 0; y < LINES; y++)
		for(x = 0; x < COLS; x++)
			addch(' ');
}

void process(void)
{
	while(1) {
		fillwin();
		mvprintw(8, 15, "Terminal supports %d Colors", COLORS);
		mvprintw(10, 15, "Function keys are:");
		mvprintw(12, 15, "F1 = Set Foreground");
		mvprintw(13, 15, "F2 = Set Background");
		mvprintw(14, 15, "F3 = Modify RED content");
		mvprintw(15, 15, "F4 = Modify GREEN content");
		mvprintw(16, 15, "F5 = Modify BLUE content");
		mvprintw(17, 15, "F8 = Quit Program");
		refresh();
		
		switch(getch()) {
		case KEY_F(1):
			setfb(FORGROUND);
			break;
		case KEY_F(2):
			setfb(BACKGROUND);
			break;
		case KEY_F(3):
			modfb(COLOR_RED);
			break;
		case KEY_F(4):
			modfb(COLOR_GREEN);
			break;
		case KEY_F(5):
			modfb(COLOR_BLUE);
			break;
		case KEY_F(8):
			return;
		default:
			beep();
		}
	}
}

void setfb(char setting)
{
	while(1) {
		fillwin();
		touchwin(stdscr);
		mvprintw(12, 10, "Use <--  --> Keys");
		mvprintw(13, 10, "F1 to select");
		refresh();
		switch(getch()) {
		case KEY_LEFT:
			if(setting == FORGROUND)
				f = f == 0 ? COLORS - 1: f - 1;
			else
				b = b == 0 ? COLORS - 1: b - 1;
			break;
		case KEY_RIGHT:
			if(setting == FORGROUND)
				f = f == COLORS - 1 ? 0: f + 1;
			else
				b = b == COLORS - 1 ? 0: b + 1;
			break;
		case KEY_F(1):
			return;
		default:
			beep();
		}
		init_pair(++i, f, b);
		attrset(COLOR_PAIR(i));
		if(i==2) i=0;
		
	}
}

void modfb(int setting)		
{
	if(!can_change_color()) {
		beep();
		return;
	}
		
	fillwin();
	mvprintw(12, 10, "Use <--  --> Keys");
	mvprintw(13, 10, "F1 to select");
	refresh();
	while(1) {
		switch(getch()) {
		case KEY_LEFT:
			if(setting == COLOR_RED)
				R = R == 0 ? 1000 : R - 1;
			else if(setting == COLOR_GREEN)
				G = G == 0 ? 1000 : G - 1;
			else	
				B = B == 0 ? 1000 : B - 1;
			break;
		case KEY_RIGHT:
			if(setting == COLOR_RED)
				R = R == 1000 ? 0 : R + 1;
			else if(setting == COLOR_GREEN)
				G = G == 1000 ? 0 : G + 1;
			else	
				B = B == 1000 ? 0 : B + 1;
			break;
		case KEY_F(1):
			return;
		default:
			beep();
		}
		init_color(f, R, G, B);
	}
}
					

