Exemplo n.º 1
0
Arquivo: tasks.c Projeto: auca/com.341
int main(int argc, char **argv)
{
        int exit_status = 0;

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

        pid_t *pid_list = NULL;

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

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

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

        bool show_kernel_threads = false;

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            memset(pid_list, 0, pid_list_size);

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                if (pad) {
                    delwin(pad);
                }

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

                    exit_status =
                        EXIT_FAILURE;

                    goto cleanup;
                }

                keypad(pad, true);
            }

            size_t header_height =
                Header_Height;

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

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

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

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

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

            werase(pad);

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

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

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

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

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

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

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

                    ++real_pad_height;
                }
            }

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

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

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

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

                        break;
                    case 'q':
                        goto cleanup;
                }

                int pad_height_limit =
                    real_pad_height - 2;

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

                int pad_width_limit =
                    header_length - 5;

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

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

        endwin();

        return exit_status;
}
Exemplo n.º 2
0
int main(int argc, char** argv)
{
	(void) argc;
	(void) argv;
	
	if (signal(SIGINT, TerminationHandler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);
	if (signal(SIGHUP, TerminationHandler) == SIG_IGN)
		signal(SIGHUP, SIG_IGN);
	if (signal(SIGTERM, TerminationHandler) == SIG_IGN)
		signal(SIGTERM, SIG_IGN);

	console.setPrompt(">");
	CommandHandler::AddAllCommands(console, updater);
	CommandHandler::AddAllLogCallback(console);
	console.addCommand(Console::Command("exit", command_exit));
	console.print(std::string("Client Terminal Test"));

	int row, col;
	int c = 0;

	initscr();
	noecho();
	cbreak();
	keypad(stdscr, FALSE);

	timeout(100);
	getmaxyx(stdscr, row, col);

	std::thread thread(&UpdateThread);

	while(!_exit)
	{
		{
			std::lock_guard<std::mutex> lock(_mutex);
			clear();
			int curr = row - 1;

			std::stringstream current;
			current << console.getPrompt() << " " << console.editing() << ' ';
			std::string edit = current.str();
			edit = edit.length() < (size_t) col ? edit : edit.substr(0, col);
			mvprintw(curr--, 0, edit.c_str());


			const std::list<std::string>& output = console.out();
			std::list<std::string>::const_iterator it = output.begin();
			for(; curr >= 0 && it != output.end(); curr--, it++) {
				std::string op = it->length() < (size_t) col ? *it : it->substr(0, col);
				mvprintw(curr, 0, op.c_str());
			}

			move(row - 1, std::min((int) (console.getPrompt().length() + 1 + console.getCursorPos()), col-2));
		}

		c = getch();

		{
			std::lock_guard<std::mutex> lock(_mutex);
			switch(c)
			{
			case KEY_UP:
				console.historyUp();
				break;
			case KEY_DOWN:
				console.historyDown();
				break;
			case KEY_LEFT:
				console.cursorLeft();
				break;
			case KEY_RIGHT:
				console.cursorRight();
				break;
			case KEY_RESIZE:
				getmaxyx(stdscr, row, col);
				break;
			case KEY_BACKSPACE:
			case 8:
			case 127:
				console.keyBackspace();
				break;
			case KEY_DC:
				console.keyDelete();
				break;
			case KEY_EOL:
			case KEY_EOS:
				console.keyEnd();
				break;
			case KEY_HOME:
				console.keyHome();
				break;
			case KEY_ENTER:
			case '\n':
				console.executeCurrentCommand();
				break;
			case KEY_STAB:
			case '\t':
				console.autocomplete();
				break;
			case KEY_MOUSE:
				break;
			default:
				{
					//std::stringstream out;
					//out << (int) c << std::endl;
					//console.print(out.str());
					console.put((char) c);
					break;
				}
			}
		}
	}

	endwin();

	if (thread.joinable())
		thread.join();

	CommandHandler::DelAllLogCallback();

	return 0;
}
Exemplo n.º 3
0
/* render help dialog */
void
load_help_popup (WINDOW * main_win)
{
  int c, quit = 1;
  size_t i, n;
  int y, x, h = HELP_WIN_HEIGHT, w = HELP_WIN_WIDTH;
  int w2 = w - 2;
  WINDOW *win;
  GMenu *menu;

  n = ARRAY_SIZE (help_main);
  getmaxyx (stdscr, y, x);

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu =
    new_gmenu (win, HELP_MENU_HEIGHT, HELP_MENU_WIDTH, HELP_MENU_Y,
               HELP_MENU_X);
  menu->size = n;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (help_main[i]);
    menu->items[i].checked = 0;
  }
  post_gmenu (menu);

  draw_header (win, "GoAccess Quick Help", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[UP/DOWN] to scroll - [q] to quit");

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, HELP_MENU_WIDTH, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, HELP_MENU_WIDTH, 0);
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }
  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Exemplo n.º 4
0
int main(int argc, char *argv[]) {
	// Set the tiltle of the window
	system("title ");

	// Pdcurses initiation functions
	initscr();
	scrollok(stdscr, TRUE);
	raw();
	noecho();
	clear();
	keypad(stdscr, TRUE);

	// Get max height and width of the console. 
	getmaxyx(stdscr, max_y, max_x);

	// Color functions/declarations
	start_color();
	init_color(COLOR_RED, 1000, 500, 500);
	init_pair(1, 15, 9);
	init_pair(2, 0, 7);
	init_pair(3, 15, 0);
	init_pair(4, 15, 1);
	init_pair(5, 12, 0);
	init_pair(6, 10, 0);
	init_pair(7, 13, 0);
	init_pair(8, 11, 0);

	// Title of the app (with blue background)
	titlebar();

	attron(COLOR_PAIR(3));		// Function to enable coloured text based on color pair (init_pair) declared before.
	mvprintw(2, 1, "Welcome to rF3.Calendar!");
	mvprintw(3, 1, "------------------------");
	mvprintw(5, 1, "Please select the month / year...");
	mvprintw(6, 1, "Press key LEFT or RIGHT to change and ENTER to select.");
	mvprintw(7, 1, "To quit this program, press Q.");
	refresh();

	// Adding example events to the vector
	event_saved = true;
	data.save_name("Example Event");
	data.save_loc("Engineering Faculty");
	data.min = 20;
	data.hour = 11;
	srand(time_t(NULL));
	for (int o = 1; o < 31; o++) {
		data.day = rand() % (10 - 1 + 1) + 1;
		data.nmon = rand() % (12 - 1 + 1) + 1;
		data.year = rand() % (2014 - 1990 + 1) + 1990;
		myVector.push_back(data);
	}

	// Old code
	// Show the calendar and user must select one
	//show_calendar(true,14,10);

	set_month();
	menu();

	return 0;
}
int window_address_book_newentry_print()
{
  int y,x;
  char buf[250];
  curseson(); cbreak(); noecho(); nonl(); keypad(stdscr,TRUE);

  getmaxyx(stdscr,y,x);
  attrset(A_NORMAL);
  attrset(COLOR_PAIR(1));

  if (gui_window_address_book_newentry.x1==-999)
    {}
  else x = gui_window_address_book_newentry.x1;

  attrset(COLOR_PAIR(0));
  snprintf(buf, 199, "%199.199s", " ");
  mvaddnstr(gui_window_address_book_newentry.y0+1,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  mvaddnstr(gui_window_address_book_newentry.y0+2,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  mvaddnstr(gui_window_address_book_newentry.y0+3,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  mvaddnstr(gui_window_address_book_newentry.y0+4,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  
  attrset(COLOR_PAIR(1));
  snprintf(buf,
	   x - gui_window_address_book_newentry.x0,
	   "SIP url : ");
  mvaddnstr(gui_window_address_book_newentry.y0,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  snprintf(buf,
	   x - gui_window_address_book_newentry.x0,
	   "TEL url : ");
  mvaddnstr(gui_window_address_book_newentry.y0+1,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  snprintf(buf,
	   x - gui_window_address_book_newentry.x0,
	   "Email   : ");
  mvaddnstr(gui_window_address_book_newentry.y0+2,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  snprintf(buf,
	   x - gui_window_address_book_newentry.x0,
	   "Phone   : ");
  mvaddnstr(gui_window_address_book_newentry.y0+3,
	    gui_window_address_book_newentry.x0,
	    buf,
	    x-gui_window_address_book_newentry.x0-1);
  
  window_address_book_newentry_draw_commands();

  return 0;
}
Exemplo n.º 6
0
Arquivo: chat.c Projeto: alevy/toxic
static void chat_onKey(ToxWindow *self, Tox *m, wint_t key)
{
    ChatContext *ctx = self->chatwin;
    StatusBar *statusbar = self->stb;

    int x, y, y2, x2;
    getyx(self->window, y, x);
    getmaxyx(self->window, y2, x2);
    int cur_len = 0;

    if (key == 0x107 || key == 0x8 || key == 0x7f) {  /* BACKSPACE key: Remove character behind pos */
        if (ctx->pos > 0) {
            cur_len = MAX(1, wcwidth(ctx->line[ctx->pos - 1]));
            del_char_buf_bck(ctx->line, &ctx->pos, &ctx->len);

            if (x == 0)
                wmove(self->window, y-1, x2 - cur_len);
            else
                wmove(self->window, y, x - cur_len);
        } else {
            beep();
        }
    }

    else if (key == KEY_DC) {      /* DEL key: Remove character at pos */
        if (ctx->pos != ctx->len)
            del_char_buf_frnt(ctx->line, &ctx->pos, &ctx->len);
        else
            beep();
    }

    else if (key == T_KEY_DISCARD) {    /* CTRL-U: Delete entire line behind pos */
        if (ctx->pos > 0) {
            discard_buf(ctx->line, &ctx->pos, &ctx->len);
            wmove(self->window, y2 - CURS_Y_OFFSET, 0);
        } else {
            beep();
        }
    }

    else if (key == T_KEY_KILL) {    /* CTRL-K: Delete entire line in front of pos */
        if (ctx->pos != ctx->len)
            kill_buf(ctx->line, &ctx->pos, &ctx->len);
        else
            beep();
    }

    else if (key == KEY_HOME) {    /* HOME key: Move cursor to beginning of line */
        if (ctx->pos > 0) {
            ctx->pos = 0;
            wmove(self->window, y2 - CURS_Y_OFFSET, 0);
        }
    } 

    else if (key == KEY_END) {     /* END key: move cursor to end of line */
        if (ctx->pos != ctx->len) {
            ctx->pos = ctx->len;
            mv_curs_end(self->window, MAX(0, wcswidth(ctx->line, (CHATBOX_HEIGHT-1)*x2)), y2, x2);
        }
    }

    else if (key == KEY_LEFT) {
        if (ctx->pos > 0) {
            --ctx->pos;
            cur_len = MAX(1, wcwidth(ctx->line[ctx->pos]));

            if (x == 0)
                wmove(self->window, y-1, x2 - cur_len);
            else
                wmove(self->window, y, x - cur_len);
        } else {
            beep();
        }
    } 

    else if (key == KEY_RIGHT) {
        if (ctx->pos < ctx->len) {
            cur_len = MAX(1, wcwidth(ctx->line[ctx->pos]));
            ++ctx->pos;

            if (x == x2-1)
                wmove(self->window, y+1, 0);
            else
                wmove(self->window, y, x + cur_len);
        } else {
            beep();
        }
    } 

    else if (key == KEY_UP) {    /* fetches previous item in history */
        fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot,
                        &ctx->hst_pos, LN_HIST_MV_UP);
        mv_curs_end(self->window, ctx->len, y2, x2);
    }

    else if (key == KEY_DOWN) {    /* fetches next item in history */
        fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot,
                        &ctx->hst_pos, LN_HIST_MV_DWN);
        mv_curs_end(self->window, ctx->len, y2, x2);
    }

    else if (key == '\t') {    /* TAB key: completes command */
        if (ctx->len > 1 && ctx->line[0] == '/') {
            int diff = complete_line(ctx->line, &ctx->pos, &ctx->len, chat_cmd_list, AC_NUM_CHAT_COMMANDS,
                                     MAX_CMDNAME_SIZE);

            if (diff != -1) {
                if (x + diff > x2 - 1) {
                    int ofst = (x + diff - 1) - (x2 - 1);
                    wmove(self->window, y+1, ofst);
                } else {
                    wmove(self->window, y, x+diff);
                }
            } else {
                beep();
            }
        } else {
            beep();
        }
    }

    else
#if HAVE_WIDECHAR
    if (iswprint(key))
#else
    if (isprint(key))
#endif
    {   /* prevents buffer overflows and strange behaviour when cursor goes past the window */
        if ( (ctx->len < MAX_STR_SIZE-1) && (ctx->len < (x2 * (CHATBOX_HEIGHT - 1)-1)) ) {
            add_char_to_buf(ctx->line, &ctx->pos, &ctx->len, key);

            if (x == x2-1)
                wmove(self->window, y+1, 0);
            else
                wmove(self->window, y, x + MAX(1, wcwidth(key)));
        }
    }
    /* RETURN key: Execute command or print line */
    else if (key == '\n') {
        uint8_t line[MAX_STR_SIZE];

        if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1)
            memset(&line, 0, sizeof(line));

        wclear(ctx->linewin);
        wmove(self->window, y2 - CURS_Y_OFFSET, 0);
        wclrtobot(self->window);
        bool close_win = false;

        if (!string_is_empty(line))
            add_line_to_hist(ctx->line, ctx->len, ctx->ln_history, &ctx->hst_tot, &ctx->hst_pos);

        if (line[0] == '/') {
            if (close_win = !strcmp(line, "/close")) {
                int f_num = self->num;
                delwin(ctx->linewin);
                delwin(statusbar->topline);
                del_window(self);
                disable_chatwin(f_num);
            } else if (strncmp(line, "/me ", strlen("/me ")) == 0)
                send_action(self, ctx, m, line + strlen("/me "));
              else
                execute(ctx->history, self, m, line, CHAT_COMMAND_MODE);
        } else if (!string_is_empty(line)) {
            uint8_t selfname[TOX_MAX_NAME_LENGTH];
            tox_get_self_name(m, selfname, TOX_MAX_NAME_LENGTH);

            print_time(ctx->history);
            wattron(ctx->history, COLOR_PAIR(GREEN));
            wprintw(ctx->history, "%s: ", selfname);
            wattroff(ctx->history, COLOR_PAIR(GREEN));

            if (line[0] == '>') {
                wattron(ctx->history, COLOR_PAIR(GREEN));
                wprintw(ctx->history, "%s\n", line);
                wattroff(ctx->history, COLOR_PAIR(GREEN));
            } else
                wprintw(ctx->history, "%s\n", line);

            if (!statusbar->is_online || tox_send_message(m, self->num, line, strlen(line) + 1) == 0) {
                wattron(ctx->history, COLOR_PAIR(RED));
                wprintw(ctx->history, " * Failed to send message.\n");
                wattroff(ctx->history, COLOR_PAIR(RED));
            }
        }

        if (close_win) {
            free(ctx);
            free(statusbar);
        } else {
            reset_buf(ctx->line, &ctx->pos, &ctx->len);
        }
    }
}
Exemplo n.º 7
0
static void _draw_display(CTX *ctx)
{
  char buf[1024];
  int len, pos_x = 0, pos_y = 0;

  getmaxyx( stdscr, ctx->rows, ctx->cols );

  clear();

  /* draw title */
  attron( COLOR_PAIR( 6 ) );
  attron( A_BOLD );
  strcpy( buf, "  -= preloader by 2of1 =-" );
  printw( "%s", buf );
  for( int i = 0; i < ctx->cols - pos_x - strlen( buf ); i++ ) addch( ' ' );
  attroff( A_BOLD );
  attroff( COLOR_PAIR( 6 ) );
  pos_y++;

  /* draw status bar */
  move( ctx->rows - 1, 0 );
  attron( COLOR_PAIR( 8 ) );
  sprintf( buf, "  %s", ctx->filename );
  attron( A_BOLD );
  printw( "%s", buf );
  attroff( A_BOLD );
  len = strlen( buf );
  sprintf( buf,
           "  [%d symbol%s, %d sig match%s]",
           ctx->symbols.count,
           ctx->symbols.count > 1 ? "s" : "",
           ctx->symbols.num_sigs,
           ctx->symbols.num_sigs > 1 ? "es" : "" );
  printw( "%s", buf );
  len += strlen( buf );
  for( int i = 0; i < ctx->cols - pos_x - len; i++ ) addch( ' ' );;
  attroff( COLOR_PAIR( 8 ) );

  switch( ctx->state ) {
  case STATE_NORMAL:
  {
    /* draw symbols */
    /* work out number of rows we have for list */
    /* print from list item ptr to end of list or num free rows (item ptr is moved up and down by up/down arrow) */
    /* format: *_if_selected function_name_bold(sig...normal) */
    pos_y = 2;
    int list_rows = ctx->rows - 1 /* top */ - 3 /* bottom */;
    for( int i = 0; i < list_rows; i ++ ) {
      if( ctx->symbols.display_offset + i == ctx->symbols.count) break;

      move( pos_y, 2 );

      attron( COLOR_PAIR( 5 ) );
      attron( A_BOLD );
      printw( "%c ",
              ctx->symbols.flags[ctx->symbols.display_offset + i] & SYMBOL_SELECTED ? '*' : ' ' );
      attroff( A_BOLD );
      attroff( COLOR_PAIR( 5 ) );

      if (i == ctx->symbols.selected_offset - ctx->symbols.display_offset)
        attron( COLOR_PAIR( 1 ) );
      else
        attron( COLOR_PAIR( 2 ) );

      attron( A_BOLD );
      printw( "%s ",
              ll_access( ctx->symbols.func, ctx->symbols.display_offset + i ) );
      attroff( A_BOLD );

      printw( "%s",
              ll_access( ctx->symbols.sig, ctx->symbols.display_offset + i ) );

      char *str = _strip_path( ll_access( ctx->symbols.lib,
                               ctx->symbols.display_offset + i ) );
      mvprintw( pos_y, ctx->cols - strlen( str ) - 4, "[%s]", str );

      if (i == ctx->symbols.selected_offset - ctx->symbols.display_offset)
        attroff( COLOR_PAIR( 1 ) );
      else
        attroff( COLOR_PAIR( 2 ) );

      pos_y++;
    }

    break;
  }
  case STATE_PROCESSING_SYMS:
  case STATE_PROCESSING_LIBS:
  case STATE_RESOLVING_SYMBOLS:
  {
    static int count = 0;
    static char swirl[] = "|/-\\";
    static char *c = swirl;

    if( count >> 24 != ctx->state ) {
      count = ctx->state << 24;
    }

    move( 2, 2 );
    attron( COLOR_PAIR( 2 ) );
    attron( A_BOLD );

    if( *(++c) == '\0' ) c = swirl;
    printw( "%c %s %s %d, please be patient...",
            *c,
            ctx->state == STATE_RESOLVING_SYMBOLS ? "matching" : "processing",
            ctx->state == STATE_PROCESSING_SYMS || STATE_RESOLVING_SYMBOLS ? "symbol" : "library",
            ++count & 0xffffff );

    attroff( A_BOLD );

    printw( " (%s)", (char *)ctx->extra );

    attroff( COLOR_PAIR( 2 ) );

    break;
  }
  }

  refresh();
}
Exemplo n.º 8
0
int getHeight() {
    int y, x;
    getmaxyx(stdscr, y, x);
    return y;
}
Exemplo n.º 9
0
void curses_init_options()
{
    set_wc_option_mod_status(WC_ALIGN_MESSAGE|WC_ALIGN_STATUS|WC_COLOR|
     WC_HILITE_PET|WC_POPUP_DIALOG, SET_IN_GAME);

    set_wc2_option_mod_status(WC2_GUICOLOR, SET_IN_GAME);

    /* Remove a few options that are irrelevant to this windowport */
    set_option_mod_status("DECgraphics", SET_IN_FILE);
    set_option_mod_status("perm_invent", SET_IN_FILE);
    set_option_mod_status("eight_bit_tty", SET_IN_FILE);

    /* Make sure that DECgraphics is not set to true via the config
    file, as this will cause display issues.  We can't disable it in
    options.c in case the game is compiled with both tty and curses.*/
    if (iflags.DECgraphics)
    {
        switch_graphics(CURS_GRAPHICS);
    }
	
#ifdef PDCURSES
    /* PDCurses for SDL, win32 and OS/2 has the ability to set the
     terminal size programatically.  If the user does not specify a
     size in the config file, we will set it to a nice big 110x32 to
     take advantage of some of the nice features of this windowport. */
    if (iflags.wc2_term_cols == 0)
    {
        iflags.wc2_term_cols = 110;
    }
    
    if (iflags.wc2_term_rows == 0)
    {
        iflags.wc2_term_rows = 32;
    }
    
    resize_term(iflags.wc2_term_rows, iflags.wc2_term_cols);
    getmaxyx(base_term, term_rows, term_cols);
    
    /* This is needed for an odd bug with PDCurses-SDL */
    switch_graphics(ASCII_GRAPHICS);
    if (iflags.IBMgraphics)
    {
        switch_graphics(IBM_GRAPHICS);
    }
    else if (iflags.cursesgraphics)
    {
        switch_graphics(CURS_GRAPHICS);
    }
    else
    {
        switch_graphics(ASCII_GRAPHICS);
    }
#endif  /* PDCURSES */
    if (!iflags.wc2_windowborders)
    {
        iflags.wc2_windowborders = 3; /* Set to auto if not specified */
    }
    
    if (!iflags.wc2_petattr)
    {
        iflags.wc2_petattr = A_REVERSE;
    }
    else    /* Pet attribute specified, so hilite_pet should be true */
    {
        iflags.hilite_pet = TRUE;
    }

#ifdef NCURSES_MOUSE_VERSION
    if (iflags.wc_mouse_support)
    {
    	mousemask(BUTTON1_CLICKED, NULL);
    }
#endif
}
Exemplo n.º 10
0
static void prompt_onDraw(ToxWindow *self, Tox *m)
{
    ChatContext *ctx = self->chatwin;

    int x, y, x2, y2;
    getyx(ctx->history, y, x);
    getmaxyx(ctx->history, y2, x2);

    if (!ctx->hst->scroll_mode)
        curs_set(1);

    line_info_print(self);

    /* if len is >= screen width offset max x by X_OFST to account for prompt char */
    int px2 = ctx->len >= x2 ? x2 : x2 - X_OFST;

    if (px2 <= 0)
        return;

    /* len offset to account for prompt char (0 if len is < width of screen) */
    int p_ofst = px2 != x2 ? 0 : X_OFST;

    if (ctx->len > 0) {
        uint8_t line[MAX_STR_SIZE];

        if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1)
            reset_buf(ctx->line, &ctx->pos, &ctx->len);
        else
            mvwprintw(ctx->history, ctx->orig_y, X_OFST, line);

        int k = ctx->orig_y + ((ctx->len + p_ofst) / px2);

        ctx->at_bottom = k == y2 - 1;
        bool botm = k == y2;
        bool edge = (ctx->len + p_ofst) % px2 == 0;

        /* move point of line origin up when input scrolls screen down */
        if (edge && botm)
            --ctx->orig_y;

    } else {    /* Mark point of origin for new line */
        ctx->orig_y = y;    
    }

    wattron(ctx->history, COLOR_PAIR(GREEN));
    mvwprintw(ctx->history, ctx->orig_y, 0, "$ ");
    wattroff(ctx->history, COLOR_PAIR(GREEN));

    StatusBar *statusbar = self->stb;
    werase(statusbar->topline);
    mvwhline(statusbar->topline, 1, 0, ACS_HLINE, x2);
    wmove(statusbar->topline, 0, 0);

    if (statusbar->is_online) {
        int colour = WHITE;
        const uint8_t *status_text = "Unknown";

        switch (statusbar->status) {
        case TOX_USERSTATUS_NONE:
            status_text = "Online";
            colour = GREEN;
            break;
        case TOX_USERSTATUS_AWAY:
            status_text = "Away";
            colour = YELLOW;
            break;
        case TOX_USERSTATUS_BUSY:
            status_text = "Busy";
            colour = RED;
            break;
        case TOX_USERSTATUS_INVALID:
            status_text = "ERROR";
            colour = MAGENTA;
            break;
        }
        wattron(statusbar->topline, COLOR_PAIR(colour) | A_BOLD);
        wprintw(statusbar->topline, " [%s]", status_text);
        wattroff(statusbar->topline, COLOR_PAIR(colour) | A_BOLD);

        wattron(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, " %s", statusbar->nick);
        wattroff(statusbar->topline, A_BOLD);
    } else {
        wprintw(statusbar->topline, "[Offline]");
        wattron(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, " %s ", statusbar->nick);
        wattroff(statusbar->topline, A_BOLD);
    }

    if (statusbar->statusmsg[0])
        wprintw(statusbar->topline, " - %s", statusbar->statusmsg);

    /* put cursor back in correct spot */
    int y_m = ctx->orig_y + ((ctx->pos + p_ofst) / px2);
    int x_m = (ctx->pos + X_OFST) % x2;
    wmove(self->window, y_m, x_m);
}
Exemplo n.º 11
0
int getWidth() {
    int y, x;
    getmaxyx(stdscr, y, x);
    return x;
}
Exemplo n.º 12
0
static void prompt_onKey(ToxWindow *self, Tox *m, wint_t key)
{
    ChatContext *ctx = self->chatwin;

    int x, y, y2, x2;
    getyx(ctx->history, y, x);
    getmaxyx(ctx->history, y2, x2);

    /* this is buggy */
    //if (key == T_KEY_ESC) {   /* ESC key: Toggle history scroll mode */
    //    bool scroll = ctx->hst->scroll_mode ? false : true;
    //    line_info_toggle_scroll(self, scroll);
    //}

    /* If we're in scroll mode ignore rest of function */
    if (ctx->hst->scroll_mode) {
        line_info_onKey(self, key);
        return;
    }

    /* BACKSPACE key: Remove one character from line */
    if (key == 0x107 || key == 0x8 || key == 0x7f) {
        if (ctx->pos > 0) {
            del_char_buf_bck(ctx->line, &ctx->pos, &ctx->len);
            wmove(ctx->history, y, x-1);    /* not necessary but fixes a display glitch */
        } else {
            beep();
        }
    }

    else if (key == KEY_DC) {      /* DEL key: Remove character at pos */
        if (ctx->pos != ctx->len) {
            del_char_buf_frnt(ctx->line, &ctx->pos, &ctx->len);
        } else {
            beep();
        }
    }

    else if (key == T_KEY_DISCARD) {    /* CTRL-U: Delete entire line behind pos */
        if (ctx->pos > 0) {
            wmove(ctx->history, ctx->orig_y, X_OFST);
            wclrtobot(ctx->history);
            discard_buf(ctx->line, &ctx->pos, &ctx->len);
        } else {
            beep();
        }
    }

    else if (key == T_KEY_KILL) {    /* CTRL-K: Delete entire line in front of pos */
        if (ctx->len != ctx->pos)
            kill_buf(ctx->line, &ctx->pos, &ctx->len);
        else
            beep();
    }

    else if (key == KEY_HOME || key == T_KEY_C_A) {  /* HOME/C-a key: Move cursor to start of line */
        if (ctx->pos != 0)
            ctx->pos = 0;
    }

    else if (key == KEY_END || key == T_KEY_C_E) {   /* END/C-e key: move cursor to end of line */
        if (ctx->pos != ctx->len)
            ctx->pos = ctx->len;
    }

    else if (key == KEY_LEFT) {
        if (ctx->pos > 0)
            --ctx->pos;
        else
            beep();
    } 

    else if (key == KEY_RIGHT) {
        if (ctx->pos < ctx->len)
            ++ctx->pos;
        else 
            beep();
    } 

    else if (key == KEY_UP) {     /* fetches previous item in history */
        wmove(ctx->history, ctx->orig_y, X_OFST);
        fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot,
                        &ctx->hst_pos, MOVE_UP);

        /* adjust line y origin appropriately when window scrolls down */
        if (ctx->at_bottom && ctx->len >= x2 - X_OFST) {
            int px2 = ctx->len >= x2 ? x2 : x2 - X_OFST;
            int p_ofst = px2 != x2 ? 0 : X_OFST;

            if (px2 <= 0)
                return;

            int k = ctx->orig_y + ((ctx->len + p_ofst) / px2);

            if (k >= y2) {
                --ctx->orig_y;
            }
        }
    }

    else if (key == KEY_DOWN) {    /* fetches next item in history */
        wmove(ctx->history, ctx->orig_y, X_OFST);
        fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot,
                        &ctx->hst_pos, MOVE_DOWN);
    }

    else if (key == '\t') {    /* TAB key: completes command */
        if (ctx->len > 1 && ctx->line[0] == '/') {
            if (complete_line(ctx->line, &ctx->pos, &ctx->len, glob_cmd_list, AC_NUM_GLOB_COMMANDS,
                              MAX_CMDNAME_SIZE) == -1) 
                beep();
        } else {
            beep();
        }
    }

    else
#if HAVE_WIDECHAR
    if (iswprint(key))
#else
    if (isprint(key))
#endif
    {
        if (ctx->len < (MAX_STR_SIZE-1)) {
            add_char_to_buf(ctx->line, &ctx->pos, &ctx->len, key);
        }
    }
    /* RETURN key: execute command */
    else if (key == '\n') {
        wprintw(ctx->history, "\n");
        uint8_t line[MAX_STR_SIZE] = {0};

        if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1)
            memset(&line, 0, sizeof(line));

        if (!string_is_empty(line))
            add_line_to_hist(ctx->line, ctx->len, ctx->ln_history, &ctx->hst_tot, &ctx->hst_pos);

        line_info_add(self, NULL, NULL, NULL, line, PROMPT, 0, 0);
        execute(ctx->history, self, m, line, GLOBAL_COMMAND_MODE);
        reset_buf(ctx->line, &ctx->pos, &ctx->len);
    }
}
Exemplo n.º 13
0
void TerminalChatConsole::step(int ch)
{
	bool complete_redraw_needed = false;

	// empty queues
	while (!m_chat_interface->outgoing_queue.empty()) {
		ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
		switch (evt->type) {
			case CET_NICK_REMOVE:
				m_nicks.remove(((ChatEventNick *)evt)->nick);
				break;
			case CET_NICK_ADD:
				m_nicks.push_back(((ChatEventNick *)evt)->nick);
				break;
			case CET_CHAT:
				complete_redraw_needed = true;
				// This is only used for direct replies from commands
				// or for lua's print() functionality
				m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
				break;
			case CET_TIME_INFO:
				ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
				m_game_time = tevt->game_time;
				m_time_of_day = tevt->time;
		};
		delete evt;
	}
	while (!m_log_output.queue.empty()) {
		complete_redraw_needed = true;
		std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
		if (p.first > m_log_level)
			continue;

		m_chat_backend.addMessage(
			utf8_to_wide(Logger::getLevelLabel(p.first)),
			utf8_to_wide(p.second));
	}

	// handle input
	if (!m_esc_mode) {
		handleInput(ch, complete_redraw_needed);
	} else {
		switch (ch) {
			case ERR: // no input
				break;
			case 27: // ESC
				// Toggle ESC mode
				m_esc_mode = !m_esc_mode;
				break;
			case 'L':
				m_log_level--;
				m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
				break;
			case 'l':
				m_log_level++;
				m_log_level = MYMIN(m_log_level, LL_MAX - 1);
				break;
		}
	}

	// was there a resize?
	int xn, yn;
	getmaxyx(stdscr, yn, xn);
	if (xn != m_cols || yn != m_rows) {
		m_cols = xn;
		m_rows = yn;
		m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
		complete_redraw_needed = true;
	}

	// draw title
	move(0, 0);
	clrtoeol();
	addstr(PROJECT_NAME_C);
	addstr(" ");
	addstr(g_version_hash);

	u32 minutes = m_time_of_day % 1000;
	u32 hours = m_time_of_day / 1000;
	minutes = (float)minutes / 1000 * 60;

	if (m_game_time)
		printw(" | Game %d Time of day %02d:%02d ",
			m_game_time, hours, minutes);

	// draw text
	if (complete_redraw_needed && m_can_draw_text)
		draw_text();

	// draw prompt
	if (!m_esc_mode) {
		// normal prompt
		ChatPrompt& prompt = m_chat_backend.getPrompt();
		std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
		move(m_rows - 1, 0);
		clrtoeol();
		addstr(prompt_text.c_str());
		// Draw cursor
		s32 cursor_pos = prompt.getVisibleCursorPosition();
		if (cursor_pos >= 0) {
			move(m_rows - 1, cursor_pos);
		}
	} else {
		// esc prompt
		move(m_rows - 1, 0);
		clrtoeol();
		printw("[ESC] Toggle ESC mode |"
			" [CTRL+C] Shut down |"
			" (L) in-, (l) decrease loglevel %s",
			Logger::getLevelLabel((LogLevel) m_log_level).c_str());
	}

	refresh();
}
Exemplo n.º 14
0
int window_sessions_list_print(gui_t* gui, int wid)
{
	int y,x;
	char buf[250];

	sipua_set_t* call;

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

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

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

	gui->parent = wid;

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

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

	attrset(A_NORMAL);

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

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

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

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

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

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

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

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

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

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

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

		if (n == max)
			break;

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

	gui->gui_draw_commands(gui);
  
	return 0;
}
Exemplo n.º 15
0
int main()
{
    srandom(time(NULL));
    int ch, row, col, i, status;
    pthread_t score_thread, player_thread;
    Enemy *enemy_list[20];
    pthread_mutex_init (&mutex, NULL);
    initscr();	// start curses mode
//    raw();	// line buffering disabled, control character gotten
    cbreak();
    noecho();	// we dont want what the user type to get out
//    start_color();
    curs_set(0);
    keypad(stdscr, TRUE);	// we get f1, f2, etc.
    getmaxyx(stdscr, row, col);	// get the number of rows and columns
    battle_win = newwin(22, 32, 0, 0);
    box(battle_win, 0, 0);
    score_win = newwin(1, 30, 22, 0);
    mvwaddch(battle_win, 10, 15, '@');
    refresh();
    wrefresh(score_win);
    lose = 1;
    // now we create the threads
    pthread_create(&score_thread, NULL, move_score, NULL);
    pthread_create(&player_thread, NULL, move_player, NULL);
    
    // main thread will control the enemies

    for (i = 0; i < 20; i++) {
        enemy_list[i] = new Asteroid;
    }
    while (lose) {
        for (i = 0; (i < 20) && (lose); i++) {
            status = enemy_list[i]->move_enemy();
            if (status == -1) {
                lose = 0;
            }
            else if (status == 1) {
                delete enemy_list[i];
                enemy_list[i] = new Asteroid;
            }
        }
        usleep(100000);
    }
    pthread_cancel(score_thread);
    pthread_join(score_thread, NULL);
    pthread_cancel(player_thread);
    pthread_join(player_thread, NULL);
    mvwaddch(battle_win, playerposy, playerposx, 'O');
    mvwaddch(battle_win, playerposy-1, playerposx-1, '\\');
    mvwaddch(battle_win, playerposy-1, playerposx, '|');
    mvwaddch(battle_win, playerposy-1, playerposx+1, '/');
    mvwaddch(battle_win, playerposy, playerposx-1, '-');
    mvwaddch(battle_win, playerposy, playerposx+1, '-');
    mvwaddch(battle_win, playerposy+1, playerposx-1, '/');
    mvwaddch(battle_win, playerposy+1, playerposx, '|');
    mvwaddch(battle_win, playerposy+1, playerposx+1, '\\');
    wrefresh(battle_win);
    getch();	// wait for user input
    endwin();	// end curses mode
    printf("Your score is: %d\n", score);
    return 0;
}
Exemplo n.º 16
0
void get_window_size(Window *window, int *y, int *x)
{
	getmaxyx(window->curses_window, *y, *x);
}
Exemplo n.º 17
0
static void nmea_update(void)
{
    char **fields;

    assert(cookedwin != NULL);
    assert(nmeawin != NULL);
    assert(gpgsawin != NULL);
    assert(gpggawin != NULL);
    assert(gprmcwin != NULL);
    assert(gpgstwin != NULL);

    /* can be NULL if packet was overlong */
    fields = session.nmea.field;

    if (session.lexer.outbuffer[0] == (unsigned char)'$'
		&& fields != NULL && fields[0] != NULL) {
	int ymax, xmax;
	timestamp_t now;
	getmaxyx(nmeawin, ymax, xmax);
	assert(ymax > 0);
	if (strstr(sentences, fields[0]) == NULL) {
	    char *s_end = sentences + strlen(sentences);
	    if ((int)(strlen(sentences) + strlen(fields[0])) < xmax - 2) {
		*s_end++ = ' ';
		(void)strlcpy(s_end, fields[0], NMEA_MAX);
	    } else {
		*--s_end = '.';
		*--s_end = '.';
		*--s_end = '.';
	    }
	    (void)mvwaddstr(nmeawin, SENTENCELINE, 1, sentences);
	}

	/*
	 * If the interval between this and last update is
	 * the longest we've seen yet, boldify the corresponding
	 * tag.
	 */
	now = timestamp();
	if (now > last_tick && (now - last_tick) > tick_interval) {
	    char *findme = strstr(sentences, fields[0]);

	    tick_interval = now - last_tick;
	    if (findme != NULL) {
		(void)mvwchgat(nmeawin, SENTENCELINE, 1, xmax - 13, A_NORMAL, 0,
			       NULL);
		(void)mvwchgat(nmeawin, SENTENCELINE, 1 + (findme - sentences),
			       (int)strlen(fields[0]), A_BOLD, 0, NULL);
	    }
	}
	last_tick = now;

	if (strcmp(fields[0], "GPGSV") == 0
	    || strcmp(fields[0], "GNGSV") == 0
	    || strcmp(fields[0], "GLGSV") == 0) {
	    int i;
	    int nsats =
		(session.gpsdata.satellites_visible <
		 MAXSATS) ? session.gpsdata.satellites_visible : MAXSATS;

	    for (i = 0; i < nsats; i++) {
		(void)wmove(satwin, i + 2, 3);
		(void)wprintw(satwin, " %3d %3d%3d %3.0f",
			      session.gpsdata.skyview[i].PRN,
			      session.gpsdata.skyview[i].azimuth,
			      session.gpsdata.skyview[i].elevation,
			      session.gpsdata.skyview[i].ss);
	    }
	    /* add overflow mark to the display */
	    if (nsats <= MAXSATS)
		(void)mvwaddch(satwin, MAXSATS + 2, 18, ACS_HLINE);
	    else
		(void)mvwaddch(satwin, MAXSATS + 2, 18, ACS_DARROW);
	}

	if (strcmp(fields[0], "GPRMC") == 0
	    || strcmp(fields[0], "GNRMC") == 0
	    || strcmp(fields[0], "GLRMC") == 0) {
	    /* time, lat, lon, course, speed */
	    (void)mvwaddstr(gprmcwin, 1, 12, fields[1]);
	    (void)mvwprintw(gprmcwin, 2, 12, "%12s %s", fields[3], fields[4]);
	    (void)mvwprintw(gprmcwin, 3, 12, "%12s %s", fields[5], fields[6]);
	    (void)mvwaddstr(gprmcwin, 4, 12, fields[7]);
	    (void)mvwaddstr(gprmcwin, 5, 12, fields[8]);
	    /* the status field, FAA code, and magnetic variation */
	    (void)mvwaddstr(gprmcwin, 6, 12, fields[2]);
	    (void)mvwaddstr(gprmcwin, 6, 25, fields[12]);
	    (void)mvwprintw(gprmcwin, 7, 12, "%-5s%s", fields[10],
			    fields[11]);

	    cooked_pvt();	/* cooked version of TPV */
	}

	if (strcmp(fields[0], "GPGSA") == 0
	    || strcmp(fields[0], "GNGSA") == 0
	    || strcmp(fields[0], "GLGSA") == 0) {
	    (void)mvwprintw(gpgsawin, MODE_LINE, 7, "%1s%s", fields[1], fields[2]);
	    monitor_satlist(gpgsawin, SATS_LINE, SATS_COL+6);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 8, "%-5s", fields[16]);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 16, "%-5s", fields[17]);
	    (void)mvwprintw(gpgsawin, DOP_LINE, 24, "%-5s", fields[15]);
	    monitor_fixframe(gpgsawin);
	}

#ifdef NTP_ENABLE
	toff_update(gpgsawin, TOFF_LINE, 7);
#endif /* NTP_ENABLE */

	if (strcmp(fields[0], "GPGGA") == 0
	    || strcmp(fields[0], "GNGGA") == 0
	    || strcmp(fields[0], "GLGGA") == 0) {
	    (void)mvwprintw(gpggawin, 1, 12, "%-17s", fields[1]);
	    (void)mvwprintw(gpggawin, 2, 12, "%-17s", fields[2]);
	    (void)mvwprintw(gpggawin, 3, 12, "%-17s", fields[4]);
	    (void)mvwprintw(gpggawin, 4, 12, "%-17s", fields[9]);
	    (void)mvwprintw(gpggawin, 5, 12, "%1.1s", fields[6]);
	    (void)mvwprintw(gpggawin, 5, 22, "%2.2s", fields[7]);
	    (void)mvwprintw(gpggawin, 6, 12, "%-5.5s", fields[8]);
	    (void)mvwprintw(gpggawin, 7, 12, "%-5.5s", fields[11]);
	}
	if (strcmp(fields[0], "GPGST") == 0) {
	    (void)mvwprintw(gpgstwin, 1,  6, "%-10s", fields[1]);
	    (void)mvwprintw(gpgstwin, 1, 21,  "%-8s", fields[2]);
	    (void)mvwprintw(gpgstwin, 2,  6, "%-10s", fields[3]);
	    (void)mvwprintw(gpgstwin, 2, 21,  "%-8s", fields[4]);
	    (void)mvwprintw(gpgstwin, 3,  6, "%-10s", fields[5]);
	    (void)mvwprintw(gpgstwin, 3, 21,  "%-8s", fields[6]);
	    (void)mvwprintw(gpgstwin, 4,  6, "%-10s", fields[7]);
	    (void)mvwprintw(gpgstwin, 4, 21,  "%-8s", fields[8]);
	}
    }

#ifdef PPS_ENABLE
    pps_update(gpgsawin, PPS_LINE, 6);
#endif /* PPS_ENABLE */
}
Exemplo n.º 18
0
int main(int argc, char** argv) {
    WINDOW *lic = NULL;
    int x, y, mr;
    int opt = 0, cnt = 0;
    char remname[256];
    char *licpath = NULL;
    FILE *fout = NULL;
    char *version = NULL;
    if (am_bin_path(instance_path, sizeof (instance_path)) == -1) {
        return 0;
    } else {
        if (am_whitespace(instance_path) > 0) {
            fprintf(stderr, "Whitespace in path: %s \n", instance_path);
            return 0;
        }

        snprintf(log_path, sizeof (log_path), "%s/../logs/install_%s.log", instance_path, TIMESTAMPLONG);
        snprintf(lic_path, sizeof (lic_path), "%s/../legal-notices/license.txt", instance_path);

        fout = fopen(log_path, "a");
        if (fout != NULL) {
            fprintf(fout, "\n\n===================================================");
            print_version(fout, NULL);
            fprintf(fout, "\r\n");
            fclose(fout);
        }

        strcat(instance_path, "../instances");
        snprintf(int_conf_path, sizeof (int_conf_path), "%s/.agents", instance_path);
    }

    net_initialize();

    /* cli mode */
    if (argc > 1) {
        while ((opt = opts(argc, argv, "e:vlxr:o:a:i:p:c:")) != -1)
            switch (opt) {
                case 'e':
                {
                    char encryptpasswd[1024] = "";
                    char origpasswd[1024] = "";
                    char *keystr;
                    char bkeystr[1024] = "";
                    strcpy(origpasswd, oarg);
                    am_trim(origpasswd);
                    keystr = am_random_key();
                    memset(bkeystr, 0, 1024);
                    am_b64encode(keystr, bkeystr);
                    encrypt_base64(origpasswd, encryptpasswd, bkeystr);
                    fprintf(stderr, "\nEncrypted password:\n%s\n\nKey:\n%s\n\n", encryptpasswd, bkeystr);
                    net_shutdown();
                    return (EXIT_SUCCESS);
                }
                    break;
                case 'l':
                {
                    fprintf(stderr, "Agent instances:\n");
                    int n;
                    am_conf_p inst = NULL, temp;
                    if ((n = am_read_instances(instance_path, &inst)) > 0) {
                        temp = inst;
                        while (temp != NULL) {
                            fprintf(stderr, "%s\n", temp->name);
                            temp = temp->next;
                        }
                        am_free(inst);
                    } else
                        fprintf(stderr, "There are no agent instances registered.\n");
                    net_shutdown();
                    return (EXIT_SUCCESS);
                }
                    break;
                case 'v':
                {
                    print_version(stdout, NULL);
                    net_shutdown();
                    return (EXIT_SUCCESS);
                }
                    break;
                case 'r':
                {
                    fprintf(stderr, "Removing \"%s\" instance...\n", oarg);
                    if (remove_instance(oarg)) {
                        fprintf(stderr, "Instance \"%s\" removed.\n", oarg);
                    } else
                        fprintf(stderr, "Error removing \"%s\" instance.\n", oarg);
                    net_shutdown();
                    return (EXIT_SUCCESS);
                }
                    break;
                case 'o':
                    sprintf(openam_url, oarg);
                    cnt = 1;
                    break;
                case 'a':
                    sprintf(agent_url, oarg);
                    cnt = 1;
                    break;
                case 'i':
                    sprintf(agent_id, oarg);
                    cnt = 1;
                    break;
                case 'p':
                    sprintf(agent_pass_file, oarg);
                    cnt = 1;
                    break;
                case 'c':
                    sprintf(web_conf_path, oarg);
                    cnt = 1;
                    break;
                case 'x':
                {
                    asprintf(&licpath, "%s/.license", instance_path);
                    if (licpath) {
                        am_setup_conf(licpath, NULL);
                        free(licpath);
                        licpath = NULL;
                    }
                    net_shutdown();
                    return (EXIT_SUCCESS);
                }
                    break;
                case '?':
                    if (oopt == 'e' || oopt == 'r' || oopt == 'o' || oopt == 'a' || oopt == 'i' || oopt == 'p' || oopt == 'c')
                        fprintf(stderr, "\nError: option -%c requires an argument.\n", oopt);
                    else if (isprint(oopt))
                        fprintf(stderr, "\nError: unknown option `-%c'.\n", oopt);
                    else
                        fprintf(stderr, "\nnError: unknown option character `\\x%x'.\n", oopt);
                    opt = -1;
                default:
                    opt = -1;
            }

        if (cnt == 1) {
            asprintf(&licpath, "%s/.license", instance_path);
            if (licpath && am_file_exists(licpath) == 0) {
                am_free(licpath);
                fprintf(stderr, "\nYou have to accept ForgeRock Web Policy Agent license terms to continue.\n"
                        "Please run agentadmin with -x option or interactively to view and accept the license.\n\n");
                net_shutdown();
                return (EXIT_FAILURE);
            }
            am_free(licpath);
            licpath = NULL;
        }

        if (cnt == 1) {
            url_t u, ua;
            am_trim(openam_url);
            u = URL(openam_url);
            if (u.error == 0) {
                if (validate_am_host(&u) != 0) {
                    fprintf(stderr, "Error validating OpenAM URL\n");
                    net_shutdown();
                    return (EXIT_FAILURE);
                }
            } else {
                fprintf(stderr, "Invalid OpenAM URL value\n");
                net_shutdown();
                return (EXIT_FAILURE);
            }
            am_trim(agent_url);
            ua = URL(agent_url);
            if (ua.error != 0) {
                fprintf(stderr, "Invalid Agent URL value\n");
                net_shutdown();
                return (EXIT_FAILURE);
            } else {
                am_trim(agent_id);
                am_trim(agent_pass_file);
                if (am_read_password(agent_pass_file, agent_pass) == 0) {
                    fprintf(stderr, "Error reading password file\n");
                    net_shutdown();
                    return (EXIT_FAILURE);
                }
                if (validate_agent(&u, agent_id, agent_pass) != 0) {
                    fprintf(stderr, "%s\n", PROFILE_NOT_FOUND);
                    net_shutdown();
                    return (EXIT_FAILURE);
                }
            }
            am_trim(web_conf_path);
            if (web_conf_path == NULL || web_conf_path[0] == '\0') {
                fprintf(stderr, "Varnish vmod directory must not be empty\n");
                net_shutdown();
                return (EXIT_FAILURE);
            } else {
                char *t = NULL;
                asprintf(&t, "%s/libvmod_am.so", web_conf_path);
                if (am_whitespace(web_conf_path) > 0) {
                    fprintf(stderr, "Path to Varnish modules directory must not contain spaces\n");
                    am_free(t);
                    net_shutdown();
                    return (EXIT_FAILURE);
                } else if (am_file_writeable(web_conf_path) == 0) {
                    fprintf(stderr, "Error opening Varnish modules directory\n");
                    am_free(t);
                    net_shutdown();
                    return (EXIT_FAILURE);
                } else if (am_file_exists(t) == 1) {
                    fprintf(stderr, "This Varnish instance is already configured\n");
                    am_free(t);
                    net_shutdown();
                    return (EXIT_FAILURE);
                }
                am_free(t);
            }
            create_varnish_instance(ua);
            fprintf(stderr, "\nVarnish and agent configuration files are here:\n%s\nCheck installation log %s for any errors.\n\n", web_conf_path_out, log_path);
        } else {
            display_usage();
        }
        net_shutdown();
        return (EXIT_SUCCESS);
    }

    print_version(NULL, &version);
    if (version != NULL) {
        snprintf(vers, sizeof (vers), "Version: %s", version);
        free(version);
    }

    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);
    start_color();
    init_pair(1, COLOR_RED, COLOR_BLACK);
    getmaxyx(stdscr, y, x);

    asprintf(&licpath, "%s/.license", instance_path);
    if (am_file_exists(licpath) == 0) {
        lic = license(y, x, &mr);
        wrefresh(lic);
        delwin(lic);
        lic = NULL;
        if (mr == KEY_F(4)) {
            goto all_done;
        } else {
            am_setup_conf(licpath, NULL);
        }
    }

ret_to_menu:

    refresh();

    mr = mainmenu(y, x);

    if (mr == 0) {
        int cr = configure_step(y, x);
        if (cr == KEY_F(4)) {
            goto ret_to_menu;
        }
    } else if (mr >= 2 && mr < menu_size - 1) {
        memset(remname, 0, sizeof (remname));
        if (sscanf(menu_values[mr], "Remove '%[^''']' instance", remname) == 1) {
            if (remove_step(remname, y, x) == KEY_F(4))
                goto ret_to_menu;
        }
        goto ret_to_menu;
    } else if (mr == 1) {
        encrypt_step(y, x);
        goto ret_to_menu;
    }

all_done:

    am_free(licpath);
    clean_main_menu();
    move(0, 0);
    clrtoeol();
    refresh();
    endwin();
    net_shutdown();
    return (EXIT_SUCCESS);
}
Exemplo n.º 19
0
Arquivo: chat.c Projeto: alevy/toxic
static void chat_onDraw(ToxWindow *self, Tox *m)
{
    curs_set(1);
    int x2, y2;
    getmaxyx(self->window, y2, x2);

    ChatContext *ctx = self->chatwin;

    wclear(ctx->linewin);

    if (ctx->len > 0) {
        uint8_t line[MAX_STR_SIZE];
        
        if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1) {
            reset_buf(ctx->line, &ctx->pos, &ctx->len);
            wmove(self->window, y2 - CURS_Y_OFFSET, 0);
        } else {
            mvwprintw(ctx->linewin, 1, 0, "%s", line);
        }
    }

    /* Draw status bar */
    StatusBar *statusbar = self->stb;
    mvwhline(statusbar->topline, 1, 0, ACS_HLINE, x2);
    wmove(statusbar->topline, 0, 0);

    /* Draw name, status and note in statusbar */
    if (statusbar->is_online) {
        char *status_text = "Unknown";
        int colour = WHITE;

        TOX_USERSTATUS status = statusbar->status;

        switch (status) {
        case TOX_USERSTATUS_NONE:
            status_text = "Online";
            colour = GREEN;
            break;
        case TOX_USERSTATUS_AWAY:
            status_text = "Away";
            colour = YELLOW;
            break;
        case TOX_USERSTATUS_BUSY:
            status_text = "Busy";
            colour = RED;
            break;
        }

        wattron(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, " %s ", self->name);
        wattroff(statusbar->topline, A_BOLD);
        wattron(statusbar->topline, COLOR_PAIR(colour) | A_BOLD);
        wprintw(statusbar->topline, "[%s]", status_text);
        wattroff(statusbar->topline, COLOR_PAIR(colour) | A_BOLD);
    } else {
        wattron(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, " %s ", self->name);
        wattroff(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, "[Offline]");
    }

    /* Reset statusbar->statusmsg on window resize */
    if (x2 != self->x) {
        uint8_t statusmsg[TOX_MAX_STATUSMESSAGE_LENGTH] = {'\0'};
        tox_get_status_message(m, self->num, statusmsg, TOX_MAX_STATUSMESSAGE_LENGTH);
        snprintf(statusbar->statusmsg, sizeof(statusbar->statusmsg), "%s", statusmsg);
        statusbar->statusmsg_len = tox_get_status_message_size(m, self->num);
    }

    self->x = x2;

    /* Truncate note if it doesn't fit in statusbar */
    uint16_t maxlen = x2 - getcurx(statusbar->topline) - 4;
    if (statusbar->statusmsg_len > maxlen) {
        statusbar->statusmsg[maxlen] = '\0';
        statusbar->statusmsg_len = maxlen;
    }

    if (statusbar->statusmsg[0]) {
        wattron(statusbar->topline, A_BOLD);
        wprintw(statusbar->topline, " - %s ", statusbar->statusmsg);
        wattroff(statusbar->topline, A_BOLD);
    }

    wprintw(statusbar->topline, "\n");
    mvwhline(ctx->linewin, 0, 0, ACS_HLINE, x2);
}
Exemplo n.º 20
0
/*Fonction jeu
*Gere le jeu en lui-meme
*Deplacement des monstres en fonctions du temps
*Deplacement du joueur et traitement de son deplacement
*/
void jeu(t_case matrice[N][M], int level){
	//declaration ncurses
	int nb_col, col, row;
	int ch = 0;
	getmaxyx(stdscr,row,col); /* get the number of rows and columns */
	nb_col= col/2;
	//declaration
	int dx, dy;
	int i,j;
	t_coord pos_sortie;
	t_coord perso_position;
	int niveau_termine=0;

	//position de la sortie à 3cases du coffre mais invisible
	for(i=0;i<N;i++){
		for(j=0;j<M;j++){
			if(matrice[i][j]==coffre){
				pos_sortie.x=i;
				pos_sortie.y=j-3;
			}
		}
	}

	//traitement
	if(level>=1){
		sauvegarde_map(matrice,level);
		//tant que la vie > 0 et niveau en cours et qu'on appuye pas sur echap
		while(valeur_PV_personnage()>0 && niveau_termine==0 && ch != 27){ 
			//Deplacment des monstres en fonction du temps
			while (!kbhit() && valeur_PV_personnage()>0 ){//tant que l'on n'appuie sur aucune touche, kbhit fais boucler
				//si personnage meurt, 3 coups pour se sauver car les monstres sont inactifs
				if(valeur_invi_personnage()==0)
					generation_mob_suivante(matrice,perso_position);

				else{
					if(valeur_invi_personnage()<=3) modif_invi_personnage(valeur_invi_personnage()+1);						
					else modif_invi_personnage(0);
				}
				//affichage du jeu avec uen temporisation de 1,5s, avec la touche p pour mettre le jeu en pause
				afficher_ecran(matrice,level);
				usleep(150000);
				while(ch == 'p') ch = getch();
			}
			//choix de deplacement (deplacement possible avec les touches zqsd, ZQSD ou les fleches directives)
			ch = getch();
			switch(ch){
				
				case 'z':
				case 'Z':
				case KEY_UP:
					dx=-1;
					dy=0;
					break;
				
				case 'q':
				case 'Q':
				case KEY_LEFT:
					dx=0;
					dy=-1;
					break;
				
				case 's':
				case 'S':
				case KEY_DOWN:
					dx=1;
					dy=0;
					break;
				
				case 'd':
				case 'D':
				case KEY_RIGHT:
					dx=0;
					dy=1;
					break;
				
				default:
					dx=0;
					dy=0;
					break;
			}
			//si deplacement choisi, traitement de la case
			if(dx != 0 || dy != 0){
				valeur_position_personnage(&perso_position);

				if(matrice[perso_position.x+dx][perso_position.y+dy]!=mur_contour && matrice[perso_position.x+dx][perso_position.y+dy]!=mur){
					perso_position.x=perso_position.x+dx;
					perso_position.y=perso_position.y+dy;
					//action en fonction de la nouvelle case

					switch(matrice[perso_position.x][perso_position.y]){
						case vide:
							matrice[perso_position.x-dx][perso_position.y-dy]=vide;
							matrice[perso_position.x][perso_position.y]=hero;
							break;
						case couloir:
							matrice[perso_position.x-dx][perso_position.y-dy]=vide;
							matrice[perso_position.x][perso_position.y]=hero;
							break;
						case porte:
							matrice[perso_position.x-dx][perso_position.y-dy]=vide;
							perso_position.x=perso_position.x+dx;
							perso_position.y=perso_position.y+dy;
							matrice[perso_position.x][perso_position.y]=hero;
							break;
						case cle:
							matrice[perso_position.x-dx][perso_position.y-dy]=vide;
							modif_cle_personnage(1);
							mvprintw(41, nb_col-5,"cle prise");
							matrice[perso_position.x][perso_position.y]=hero;
							break;
						case coffre:
							if(valeur_cle_personnage()==0){	//s'il n'a pas la cle
								perso_position.x=perso_position.x-dx; //personnage ne bouge pas
								perso_position.y=perso_position.y-dy;
								mvprintw(41, nb_col-12,"veuillez prendre la cle");
							}
							else{
								matrice[perso_position.x-dx][perso_position.y-dy]=vide;
								mvprintw(42, nb_col-6,"coffre pris");
								matrice[perso_position.x][perso_position.y]=hero;
								//creation piece sortie pour finir le niveau
								matrice[pos_sortie.x][pos_sortie.y]=sortie;
								matrice[pos_sortie.x-2][pos_sortie.y]=porte;
								matrice[pos_sortie.x-2][pos_sortie.y-1]=mur_contour;
								matrice[pos_sortie.x-2][pos_sortie.y+1]=mur_contour;
								matrice[pos_sortie.x-1][pos_sortie.y]=vide;
								matrice[pos_sortie.x-1][pos_sortie.y-1]=mur_contour;
								matrice[pos_sortie.x-1][pos_sortie.y+1]=mur_contour;
								matrice[pos_sortie.x][pos_sortie.y-1]=mur_contour;
								matrice[pos_sortie.x][pos_sortie.y+1]=mur_contour;
							}
							break;
						case bonus:
							matrice[perso_position.x-dx][perso_position.y-dy]=vide;
							if(rand()%3==0){//une chance sur 3 d'avoir un point d'armure
								gain_armure_personnage(1);
							}
							else{
								gain_bonus_personnage(20); //le bonus vaut 20points
							}
							matrice[perso_position.x][perso_position.y]=hero;
							break;
						case piege:
							degat_personnage();//perd un point de vie
							perso_position.x=perso_position.x-dx; //personnage ne bouge pas
							perso_position.y=perso_position.y-dy;
							break;
						case monstre_agressif:
						case monstre_defensif:
						case monstre_inactif:
							if(position_mob(perso_position)){
								mob_perte_PV(matrice,1);
							}
							perso_position.x=perso_position.x-dx; //personnage ne bouge pas
							perso_position.y=perso_position.y-dy;

							break;
						case sortie:
							niveau_termine=1;
							break;
						default:
							break;
					}
					modif_position_personnage(perso_position);
					afficher_ecran(matrice,level);
				}
			}
		}
		if(niveau_termine==0){
			game_message(matrice,niveau_termine,level); //defaite
		}
		else{
			level++;
			//generation niveau superieur
			if(level<=5){
				init_etage_personnage();
				generation_level(matrice, level);
				jeu(matrice,level);
			}
			//si niveau 5 termine, victoire
			else game_message(matrice,niveau_termine,level);
		}
	}
}
Exemplo n.º 21
0
/*
 * Display text from a file in a dialog box.
 */
int dialog_textbox(const char *title, const char *tbuf,
		   int initial_height, int initial_width)
{
	int i, x, y, cur_x, cur_y, key = 0;
	int height, width, boxh, boxw;
	int passed_end;
	WINDOW *dialog, *box;

	begin_reached = 1;
	end_reached = 0;
	page_length = 0;
	hscroll = 0;
	buf = tbuf;
	page = buf;	/* page is pointer to start of page to be displayed */

do_resize:
	getmaxyx(stdscr, height, width);
	if (height < 8 || width < 8)
		return -ERRDISPLAYTOOSMALL;
	if (initial_height != 0)
		height = initial_height;
	else
		if (height > 4)
			height -= 4;
		else
			height = 0;
	if (initial_width != 0)
		width = initial_width;
	else
		if (width > 5)
			width -= 5;
		else
			width = 0;

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

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

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

	/* Create window for box region, used for scrolling text */
	boxh = height - 4;
	boxw = width - 2;
	box = subwin(dialog, boxh, boxw, y + 1, x + 1);
	wattrset(box, dlg.dialog.atr);
	wbkgdset(box, dlg.dialog.atr & A_COLOR);

	keypad(box, TRUE);

	/* register the new window, along with its borders */
	draw_box(dialog, 0, 0, height, width,
		 dlg.dialog.atr, dlg.border.atr);

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

	print_title(dialog, title, width);

	print_button(dialog, gettext(" Exit "), height - 2, width / 2 - 4, TRUE);
	wnoutrefresh(dialog);
	getyx(dialog, cur_y, cur_x);	/* Save cursor position */

	/* Print first page of text */
	attr_clear(box, boxh, boxw, dlg.dialog.atr);
	refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x);

	while ((key != KEY_ESC) && (key != '\n')) {
		key = wgetch(dialog);
		switch (key) {
		case 'E':	/* Exit */
		case 'e':
		case 'X':
		case 'x':
			delwin(box);
			delwin(dialog);
			return 0;
		case 'g':	/* First page */
		case KEY_HOME:
			if (!begin_reached) {
				begin_reached = 1;
				page = buf;
				refresh_text_box(dialog, box, boxh, boxw,
						 cur_y, cur_x);
			}
			break;
		case 'G':	/* Last page */
		case KEY_END:

			end_reached = 1;
			/* point to last char in buf */
			page = buf + strlen(buf);
			back_lines(boxh);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'K':	/* Previous line */
		case 'k':
		case KEY_UP:
			if (!begin_reached) {
				back_lines(page_length + 1);

				/* We don't call print_page() here but use
				 * scrolling to ensure faster screen update.
				 * However, 'end_reached' and 'page_length'
				 * should still be updated, and 'page' should
				 * point to start of next page. This is done
				 * by calling get_line() in the following
				 * 'for' loop. */
				scrollok(box, TRUE);
				wscrl(box, -1);	/* Scroll box region down one line */
				scrollok(box, FALSE);
				page_length = 0;
				passed_end = 0;
				for (i = 0; i < boxh; i++) {
					if (!i) {
						/* print first line of page */
						print_line(box, 0, boxw);
						wnoutrefresh(box);
					} else
						/* Called to update 'end_reached' and 'page' */
						get_line();
					if (!passed_end)
						page_length++;
					if (end_reached && !passed_end)
						passed_end = 1;
				}

				print_position(dialog);
				wmove(dialog, cur_y, cur_x);	/* Restore cursor position */
				wrefresh(dialog);
			}
			break;
		case 'B':	/* Previous page */
		case 'b':
		case KEY_PPAGE:
			if (begin_reached)
				break;
			back_lines(page_length + boxh);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'J':	/* Next line */
		case 'j':
		case KEY_DOWN:
			if (!end_reached) {
				begin_reached = 0;
				scrollok(box, TRUE);
				scroll(box);	/* Scroll box region up one line */
				scrollok(box, FALSE);
				print_line(box, boxh - 1, boxw);
				wnoutrefresh(box);
				print_position(dialog);
				wmove(dialog, cur_y, cur_x);	/* Restore cursor position */
				wrefresh(dialog);
			}
			break;
		case KEY_NPAGE:	/* Next page */
		case ' ':
			if (end_reached)
				break;

			begin_reached = 0;
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case '0':	/* Beginning of line */
		case 'H':	/* Scroll left */
		case 'h':
		case KEY_LEFT:
			if (hscroll <= 0)
				break;

			if (key == '0')
				hscroll = 0;
			else
				hscroll--;
			/* Reprint current page to scroll horizontally */
			back_lines(page_length);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case 'L':	/* Scroll right */
		case 'l':
		case KEY_RIGHT:
			if (hscroll >= MAX_LEN)
				break;
			hscroll++;
			/* Reprint current page to scroll horizontally */
			back_lines(page_length);
			refresh_text_box(dialog, box, boxh, boxw,
					 cur_y, cur_x);
			break;
		case KEY_ESC:
			key = on_key_esc(dialog);
			break;
		case KEY_RESIZE:
			back_lines(height);
			delwin(box);
			delwin(dialog);
			on_key_resize();
			goto do_resize;
		}
	}
	delwin(box);
	delwin(dialog);
	return key;		/* ESC pressed */
}
Exemplo n.º 22
0
Arquivo: menus.c Projeto: lyuts/vifm
void
draw_menu(menu_info *m)
{
	int i;
	int win_len;
	int x, y;

	getmaxyx(menu_win, y, x);
	win_len = x;
	werase(menu_win);

	normalize_top(m);

	x = m->top;

	box(menu_win, 0, 0);
	wattron(menu_win, A_BOLD);
	checked_wmove(menu_win, 0, 3);
	wprint(menu_win, m->title);
	wattroff(menu_win, A_BOLD);

	for(i = 1; x < m->len; i++, x++)
	{
		int z, off;
		char *buf;
		char *ptr = NULL;
		col_attr_t col;
		int type = WIN_COLOR;

		chomp(m->items[x]);
		if((ptr = strchr(m->items[x], '\n')) || (ptr = strchr(m->items[x], '\r')))
			*ptr = '\0';

		col = cfg.cs.color[WIN_COLOR];

		if(cfg.hl_search && m->matches != NULL && m->matches[x])
		{
			mix_colors(&col, &cfg.cs.color[SELECTED_COLOR]);
			type = SELECTED_COLOR;
		}

		init_pair(DCOLOR_BASE + type, col.fg, col.bg);
		wattron(menu_win, COLOR_PAIR(DCOLOR_BASE + type) | col.attr);

		z = m->hor_pos;
		off = 0;
		while(z-- > 0 && m->items[x][off] != '\0')
		{
			size_t l = get_char_width(m->items[x] + off);
			off += l;
		}

		buf = strdup(m->items[x] + off);
		for(z = 0; buf[z] != '\0'; z++)
			if(buf[z] == '\t')
				buf[z] = ' ';

		checked_wmove(menu_win, i, 2);
		if(get_screen_string_length(buf) > win_len - 4)
		{
			size_t len = get_normal_utf8_string_widthn(buf, win_len - 3 - 4);
			memset(buf + len, ' ', strlen(buf) - len);
			buf[len + 3] = '\0';
			wprint(menu_win, buf);
			mvwaddstr(menu_win, i, win_len - 5, "...");
		}
		else
		{
			const size_t len = get_normal_utf8_string_widthn(buf, win_len - 4);
			buf[len] = '\0';
			wprint(menu_win, buf);
		}
		waddstr(menu_win, " ");

		free(buf);

		wattroff(menu_win, COLOR_PAIR(DCOLOR_BASE + type) | col.attr);

		if(i + 3 > y)
			break;
	}
}
int window_address_book_newentry_run_command(int c)
{
  int y,x;
  getmaxyx(stdscr,y,x);

  if (gui_window_address_book_newentry.x1==-999)
    {}
  else x = gui_window_address_book_newentry.x1;

  switch (c)
    {
    case KEY_DC:
      delch();
      break;
    case KEY_BACKSPACE:
    case 127:
      if (active_gui->xcursor>10)
	{
	  int xcur,ycur;
	  active_gui->xcursor--;
	  getyx(stdscr,ycur,xcur);
	  move(ycur,xcur-1);
	  delch();
	}
      break;
    case '\n':
    case '\r':
    case KEY_ENTER:
    case KEY_DOWN:
      if (gui_window_address_book_newentry.ycursor<3)
	{
	  gui_window_address_book_newentry.ycursor++;
	  gui_window_address_book_newentry.xcursor=10;
	}
      break;
    case KEY_UP:
      if (gui_window_address_book_newentry.ycursor>0)
	{
	  gui_window_address_book_newentry.ycursor--;
	  gui_window_address_book_newentry.xcursor=10;
	}
      break;
    case KEY_RIGHT:
      if (gui_window_address_book_newentry.xcursor<(x-gui_window_address_book_newentry.x0-1))
	gui_window_address_book_newentry.xcursor++;
      break;
    case KEY_LEFT:
      if (gui_window_address_book_newentry.xcursor>0)
	gui_window_address_book_newentry.xcursor--;
      break;

      /* case 20: */  /* Ctrl-T */
    case 1:  /* Ctrl-A */
      {
	int ycur = gui_window_address_book_newentry.y0;
	int xcur = gui_window_address_book_newentry.x0+10;
	char sipurl[200];
	char telurl[200];
	char email[200];
	char phone[200];
	mvinnstr(ycur, xcur, sipurl, x-gui_window_address_book_newentry.x0-10);
	ycur++;
	mvinnstr(ycur, xcur, telurl, x-gui_window_address_book_newentry.x0-10);
	ycur++;
	mvinnstr(ycur, xcur, email, x-gui_window_address_book_newentry.x0-10);
	ycur++;
	mvinnstr(ycur, xcur, phone, x-gui_window_address_book_newentry.x0-10);
	
	_josua_add_contact(sipurl, telurl, email, phone);
	/* mvinnstr(ycur, xcur, tmp, 199); */
      }
      break;
    case 4:  /* Ctrl-D */
      {
	char buf[200];
	attrset(COLOR_PAIR(0));
	snprintf(buf, 199, "%199.199s", " ");
	mvaddnstr(gui_window_address_book_newentry.y0+gui_window_address_book_newentry.ycursor,
		  gui_window_address_book_newentry.x0 + 10,
		  buf,
		  x-gui_window_address_book_newentry.x0-10-1);
	gui_window_address_book_newentry.xcursor=10;
      }
      break;
    case 5:  /* Ctrl-E */
      gui_window_address_book_newentry.xcursor=10;
      gui_window_address_book_newentry.ycursor=0;
      window_address_book_newentry_print();
      break;
    default:
      /*
	fprintf(stderr, "c=%i", c);
	exit(0);
      */
      if (gui_window_address_book_newentry.xcursor<(x-gui_window_address_book_newentry.x0-1))
	{
	  gui_window_address_book_newentry.xcursor++;
	  attrset(COLOR_PAIR(0));
	  echochar(c);
	}
      else
	beep();
      return -1;
    }

  return 0;
}
Exemplo n.º 24
0
Arquivo: menus.c Projeto: lyuts/vifm
/* Draws error message on the screen or redraws the last message when both
 * title_arg and message_arg are NULL. */
static void
redraw_error_msg(const char title_arg[], const char message_arg[],
		int prompt_skip)
{
	/* TODO: refactor this function redraw_error_msg() */

	static const char *title;
	static const char *message;
	static int ctrl_c;

	int sx, sy;
	int x, y;
	int z;
	const char *text;

	if(title_arg != NULL && message_arg != NULL)
	{
		title = title_arg;
		message = message_arg;
		ctrl_c = prompt_skip;
	}

	assert(message != NULL);

	curs_set(FALSE);
	werase(error_win);

	getmaxyx(stdscr, sy, sx);
	getmaxyx(error_win, y, x);

	z = strlen(message);
	if(z <= x - 2 && strchr(message, '\n') == NULL)
	{
		y = 6;
		wresize(error_win, y, x);
		mvwin(error_win, (sy - y)/2, (sx - x)/2);
		checked_wmove(error_win, 2, (x - z)/2);
		wprint(error_win, message);
	}
	else
	{
		int i;
		int cy = 2;
		i = 0;
		while(i < z)
		{
			int j;
			char buf[x - 2 + 1];

			snprintf(buf, sizeof(buf), "%s", message + i);

			for(j = 0; buf[j] != '\0'; j++)
				if(buf[j] == '\n')
					break;

			if(buf[j] != '\0')
				i++;
			buf[j] = '\0';
			i += j;

			if(buf[0] == '\0')
				continue;

			y = cy + 4;
			mvwin(error_win, (sy - y)/2, (sx - x)/2);
			wresize(error_win, y, x);

			checked_wmove(error_win, cy++, 1);
			wprint(error_win, buf);
		}
	}

	box(error_win, 0, 0);
	if(title[0] != '\0')
		mvwprintw(error_win, 0, (x - strlen(title) - 2)/2, " %s ", title);

	if(curr_stats.errmsg_shown == 1)
	{
		if(ctrl_c)
		{
			text = "Press Return to continue or Ctrl-C to skip other error messages";
		}
		else
		{
			text = "Press Return to continue";
		}
	}
	else
	{
		text = "Enter [y]es or [n]o";
	}
	mvwaddstr(error_win, y - 2, (x - strlen(text))/2, text);
}
Exemplo n.º 25
0
Arquivo: main.c Projeto: patlc/tlf
int main(int argc, char *argv[])
{
    int j;
    pthread_t thrd1, thrd2;
    int ret;
    int retval;
    char keyerbuff[3];
    char tlfversion[80] = "";
    int status;

    while ((argc > 1) && (argv[1][0] == '-')) {
	switch (argv[1][1]) {
	    /* verbose option */
	case 'f':
	    if (strlen(argv[1] + 2) > 0) {
		if ((*(argv[1] + 2) == '~') && (*(argv[1] + 3) == '/')) {
		    /* tilde expansion */
		    config_file = g_strconcat( g_get_home_dir(),
			    argv[1] + 3, NULL);
		}
	    	else {
		    config_file = g_strdup(argv[1] + 2);
		}
	    }
	    break;
	case 's':
	    if (strlen(argv[1] + 2) > 0)
		strcpy(synclogfile, argv[1] + 2);
	    break;
	case 'd':		// debug rigctl
	    debugflag = 1;
	    break;
	case 'v':		// verbose startup
	    verbose = 1;
	    break;
	case 'V':		// output version
	    printf("Version: tlf-%s\n", VERSION);
	    exit(0);
	    break;
	case 'n':		// output version
	    nopacket = 1;
	    break;
	default:
	    printf("Use: tlf [-v] Verbose\n");
	    printf("         [-V] Version\n");
	    printf("         [-f] Configuration file\n");
	    printf("         [-d] Debug mode\n");
	    printf("         [-h] This message\n");
	    printf("         [-n] Start without cluster hookup\n");
	    exit(0);
	    break;
	}
	--argc;
	++argv;
    }

    buffer[0] = '\0';
    buffer[79] = '\0';
    bufloc = 0;

    strcat(logline0, backgrnd_str);
    strcat(logline1, backgrnd_str);
    strcat(logline2, backgrnd_str);
    strcat(logline3, backgrnd_str);
    strcat(logline4, backgrnd_str);

    strcat(terminal1, backgrnd_str);
    strcat(terminal2, backgrnd_str);
    strcat(terminal3, backgrnd_str);
    strcat(terminal4, backgrnd_str);

    termbuf[0] = '\0';
    hiscall[0] = '\0';

/* getting users terminal string and (if RXVT) setting rxvt colours on it */
/* LZ3NY hack :) */
    if (strcasecmp(getenv("TERM"), "rxvt") == 0) {
	use_rxvt = 1;
	printf("terminal is:%s", getenv("TERM"));
    } else if (strcasecmp(getenv("TERM"), "xterm") == 0) {
	use_xterm = 1;
	use_rxvt = 1;
    } else
	putenv("TERM=rxvt");	/*or going to native console linux driver */

    if ((mainscreen = newterm(NULL, stdout, stdin)) == NULL) {	/* activate ncurses terminal control */
	perror("initscr");
	printf
	    ("\n Sorry, wrong terminal type !!!!! \nTry a  linux text terminal or set TERM=linux !!!");
	sleep(5);

	exit(EXIT_FAILURE);
    }
//keypad(stdscr,TRUE);

    InitSearchPanel();	/* at least one panel has to be defined
				   for refreshp() to work */

    getmaxyx(stdscr, ymax, xmax);
    if ((ymax < 25) || (xmax < 80)) {
	char c;

	showmsg( "!! TLF needs at least 25 lines and 80 columns !!");
	showmsg( "   Continue anyway? Y/(N)" );
	c = toupper( getch() );
	if (c != 'Y') {
	    showmsg( "73 es cuagn" );
	    sleep(1);
	    endwin();
	    exit(1);
	}
	showmsg("");
    }

    noecho();
    crmode();

    strcpy(sp_return, message[12]);
    strcpy(cq_return, message[13]);

    refreshp();

    if (has_colors()) {
	if (start_color() == ERR) {
	    perror("start_color");
	    endwin();
	    printf
		("\n Sorry, wrong terminal type !!!!! \n\nTry a linux text terminal or set TERM=linux !!!");
	    sleep(5);
	    exit(EXIT_FAILURE);
	}

	sprintf(tlfversion,
		"        Welcome to tlf-%s by PA0R!!" , VERSION);
	showmsg(tlfversion);
	showmsg("");

	showmsg("reading country data");
	readctydata();		/* read ctydb.dat */

	showmsg("reading configuration data");

	status = read_logcfg(); /* read the configuration file */
	status |= read_rules();	/* read the additional contest rules in "rules/contestname"  LZ3NY */

	if (status != PARSE_OK) {
	    showmsg( "Problems in logcfg.dat or rule file detected! Continue Y/(N)?");
	    if (toupper( getchar() ) != 'Y') {
		endwin();
		exit(1);
	    }
	}

	/* make sure logfile is there and has the right format */
	if (checklogfile_new(logfile) != 0) {
	    showmsg( "Giving up" );
	    sleep(2);
	    endwin();
	    exit(1);
	}

//              if (strlen(synclogfile) > 0)
//                      synclog(synclogfile);

	if (*call == '\0') {
	    showmsg
		("WARNING: No callsign defined in logcfg.dat! exiting...\n\n\n");
	    exit(1);
	}

	if (use_rxvt == 1) {	// use rxvt colours
	    init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_RED);
	    if (use_xterm == 1) {
		init_pair(C_HEADER, COLOR_GREEN, COLOR_BLUE);
		init_pair(COLOR_RED, COLOR_WHITE, 8);
		init_pair(C_WINDOW, COLOR_CYAN, COLOR_MAGENTA);
		init_pair(C_DUPE, COLOR_WHITE, COLOR_MAGENTA);
		init_pair(C_INPUT, COLOR_BLUE, COLOR_WHITE);
	    } else {
		init_pair(C_HEADER, COLOR_GREEN, COLOR_YELLOW);
		init_pair(COLOR_RED, COLOR_WHITE, COLOR_RED);
		init_pair(C_WINDOW, COLOR_CYAN, COLOR_RED);
		init_pair(C_DUPE, COLOR_RED, COLOR_MAGENTA);
		init_pair(C_INPUT, COLOR_BLUE, COLOR_YELLOW);
	    }
	    init_pair(C_LOG, COLOR_WHITE, COLOR_BLACK);
	    init_pair(C_BORDER, COLOR_CYAN, COLOR_YELLOW);
	} else {
	    // use linux console colours
	    init_pair(COLOR_BLACK, tlfcolors[0][0], tlfcolors[0][1]); // b/w
	    init_pair(C_HEADER, tlfcolors[1][0], tlfcolors[1][1]);    // Gn/Ye
	    init_pair(COLOR_RED, tlfcolors[2][0], tlfcolors[2][1]);   // W/R
	    init_pair(C_WINDOW, tlfcolors[3][0], tlfcolors[3][1]);    // Cy/W
	    init_pair(C_LOG, tlfcolors[4][0], tlfcolors[4][1]);       // W/B
	    init_pair(C_DUPE, tlfcolors[5][0], tlfcolors[5][1]);      // W/Mag
	    init_pair(C_INPUT, tlfcolors[6][0], tlfcolors[6][1]);     // Bl/Y
	    init_pair(C_BORDER, tlfcolors[7][0], tlfcolors[7][1]);    // W/B
	}

	mults_possible = g_ptr_array_new();

	if (multlist == 1) {
	    showmsg("reading multiplier data      ");
	    load_multipliers();

	}

	attron(COLOR_PAIR(COLOR_BLACK));
	showmsg("reading callmaster data");

	nr_callmastercalls = load_callmaster();

	if (*exchange_list != '\0') {
	    // read initial exchange file
	    main_ie_list = make_ie_list(exchange_list);
	    if (main_ie_list == NULL) {
		showmsg( "Problems in initial exchange file detected! Continue Y/(N)?");
		if (toupper( getchar() ) != 'Y') {
		    endwin();
		    exit(1);
		}
		else {
		    showmsg( "Initial exchange data not loaded! Continuing ...");
		    sleep(2);
		}
	    }
	}

#ifdef HAVE_LIBHAMLIB		// Code for hamlib interface

	showmsg("HAMLIB defined");

	if (trx_control != 0) {

	    shownr("Rignumber is", (int) myrig_model);
	    shownr("Rig speed is", serial_rate);

	    showmsg("Trying to start rig ctrl");

	    /** \todo fix exclusion of newer hamlib models */
	    if ((int) myrig_model > 1999)
		status = init_native_rig();
	    else
		status = init_tlf_rig();
	}
#else
	if (trx_control != 0) {
//                      trx_control = 0;
	    showmsg("No Hamlib library, using native driver");
	    shownr("Rignumber is", rignumber);
	    shownr("Rig speed is", serial_rate);
	    status = init_native_rig();
	    sleep(1);
	}
#endif				// end code for hamlib interface

	if (status  != 0) {
	    showmsg( "Continue without rig control Y/(N)?");
	    if (toupper( getchar() ) != 'Y') {
		endwin();
		exit(1);
	    }
	    trx_control = 0;
	    showmsg( "Disabling rig control!");
	    sleep(1);
	}


	if (keyerport == NET_KEYER) {
	    showmsg("Keyer is cwdaemon");
	}
	if (keyerport == MFJ1278_KEYER || keyerport == GMFSK) {
	    init_controller();
	}

	if (lan_active == 1) {
	    retval = lanrecv_init();

	    if (retval < 0)	/* set up the network */
		shownr("LAN receive  init failed", retval);
	    else
		showmsg("LAN receive  initialized");

	    if (lan_send_init() < 0)
		showmsg("LAN send init failed");
	    else
		showmsg("LAN send initialized");
	}

	checkparameters();	/* check .paras file */

	clear();
	mvprintw(0, 0, "        Welcome to tlf-%s by PA0R!!\n\n" , VERSION);
	refreshp();
	getmessages();		/* read .paras file */

	if (nopacket == 1)
	    packetinterface = 0;

	set_term(mainscreen);

	refreshp();

	if ((nopacket == 0) && (packetinterface != 0)) {

	    if (init_packet() == 0)
		packet();
	    else
		cleanup_telnet();

	}

	if (keyerport == NET_KEYER) {
	    if (netkeyer_init() < 0) {
		mvprintw(24, 0, "Cannot open NET keyer daemon ");
		refreshp();
		sleep(1);

	    } else {
		netkeyer(K_RESET, "0");

		sprintf(weightbuf, "%d", weight);

		write_tone();

		snprintf(keyerbuff, 3, "%2d", GetCWSpeed());
		netkeyer(K_SPEED, keyerbuff);		// set speed

		netkeyer(K_WEIGHT, weightbuf);		// set weight

		if (*keyer_device != '\0')
		    netkeyer(K_DEVICE, keyer_device);	// set device

		sprintf(keyerbuff, "%d", txdelay);
		netkeyer(K_TOD, keyerbuff);		// set TOD

		if (sc_sidetone != 0)			// set soundcard output
		    netkeyer(K_SIDETONE, "");

		if (*sc_volume != '\0')			// set soundcard volume
			netkeyer(K_STVOLUME, sc_volume);
	    }

	    if (keyerport != NET_KEYER)
		write_tone();
	}

	getwwv();		/* get the latest wwv info from packet */

	scroll_log();		/* read the last 5  log lines and set the qso number */

	nr_qsos = readcalls();	/* read the logfile for score and dupe */

	clear_display();	/* tidy up the display */

	qrb();

	attron(COLOR_PAIR(C_LOG) | A_STANDOUT);

	for (j = 13; j <= 23; j++) {	/* wipe lower window */
	    mvprintw(j, 0, backgrnd_str);
	}

	bm_init();			/* initialize bandmap */

	/* Create the first thread */
	ret = pthread_create(&thrd1, NULL, (void *) logit, NULL);
	if (ret) {
	    perror("pthread_create: logit");
	    endwin();
	    exit(EXIT_FAILURE);
	}

	/* Create the second thread */
	ret =
	    pthread_create(&thrd2, NULL, (void *) background_process,
			   NULL);
	if (ret) {
	    perror("pthread_create: backgound_process");
	    endwin();
	    exit(EXIT_FAILURE);
	}

	pthread_join(thrd2, NULL);
	pthread_join(thrd1, NULL);
	endwin();
	exit(EXIT_SUCCESS);

    } else {
	printf("Terminal does not support color\n");
	printf("\nTry TERM=linux  or use a text console !!\n");
	refreshp();
	sleep(2);
    }
    cleanup_telnet();

    if (trxmode == CWMODE && keyerport == NET_KEYER)
	netkeyer_close();
    else
	close(cfd);		/* close keyer */

    endwin();

    return (0);
}
Exemplo n.º 26
0
Arquivo: ui.c Projeto: hahahafr/ziege
void
maj_affichage(jeu_s jeu, aff_s aff)
{

    int x, y;
    
    int winmaxx, winmaxy;
    getmaxyx(aff->etat, winmaxy, winmaxx);
    
    mvwprintw(aff->etat, winmaxy - 2, 2, "Score TIGRE:");
    wattron(aff->etat, A_BOLD);
    wprintw(aff->etat, " %d", jeu->participant[TIGRE].score);
    wattroff(aff->etat, A_BOLD);
    wclrtoeol(aff->etat);

    mvwprintw(aff->etat, winmaxy - 3, 2, "Score CHEVRE:");
    wattron(aff->etat, A_BOLD);
    wprintw(aff->etat, " %d", jeu->participant[CHEVRE].score);
    wattroff(aff->etat, A_BOLD);
    wclrtoeol(aff->etat);
    
    if (get_phase(jeu) == PHASE_PLACEMENT)
    {
        mvwprintw(aff->etat, winmaxy - 4, 2, "PHASE: ");
        wattron(aff->etat, A_BOLD);
        wprintw(aff->etat, "PLACEMENT", get_phase(jeu));
        wattroff(aff->etat, A_BOLD);
        wclrtoeol(aff->etat);
    }
    if (get_phase(jeu) == PHASE_DEPLACEMENT)
    {
        mvwprintw(aff->etat, winmaxy - 4, 2, "PHASE: ");
        wattron(aff->etat, A_BOLD);
        wprintw(aff->etat, "DEPLACEMENT", get_phase(jeu));
        wattroff(aff->etat, A_BOLD);
        wclrtoeol(aff->etat);
    }

    if (get_joueur(jeu) == CHEVRE)
    {
        mvwprintw(aff->etat, winmaxy - 5, 2, "JOUEUR: ");
        wattron(aff->etat, A_BOLD | COLOR_PAIR(20));
        wprintw(aff->etat, "CHEVRE", get_joueur(jeu));
        wattroff(aff->etat, A_BOLD | COLOR_PAIR(20));
        wclrtoeol(aff->etat);
    }
    if (get_joueur(jeu) == TIGRE)
    {
        mvwprintw(aff->etat, winmaxy - 5, 2, "JOUEUR: ");
        wattron(aff->etat, A_BOLD | COLOR_PAIR(21));
        wprintw(aff->etat, "TIGRE", get_joueur(jeu));
        wattroff(aff->etat, A_BOLD | COLOR_PAIR(21));
        wclrtoeol(aff->etat);
    }

    mvwprintw(aff->etat, winmaxy - 6, 2, "CHEVRES A PLACER:");
    wattron(aff->etat, A_BOLD);
    wprintw(aff->etat, " %d", NB_MAX_CHEVRE-jeu->g->nb_chevre);
    wattroff(aff->etat, A_BOLD);
    wclrtoeol(aff->etat);
    wrefresh(aff->etat);


    // i = ORD = x
    // j = ABS = y
    for (int i = 0; i < PLATEAU_LARGEUR; i++)
    {
        for (int j = 0; j < PLATEAU_HAUTEUR; j++)
        {
            if (get_pion(jeu->p,j,i) == CHEVRE)
            {
                coord_jeu_vers_aff(aff, i, j, &y, &x);
                retracer_case(aff, y, x, CHEVRE);
                wrefresh(aff->plateau);
            }
            else if (get_pion(jeu->p,j,i) == TIGRE)
            {
                coord_jeu_vers_aff(aff, i, j, &y, &x);
                retracer_case(aff, y, x, TIGRE);
                wrefresh(aff->plateau);
            }
            else
            {
                coord_jeu_vers_aff(aff, i, j, &y, &x);
                retracer_case(aff, y, x, VIDE);
                wrefresh(aff->plateau);
            }
        }
    }

    mvwprintw(aff->cimetiere, 0, 2, "Pressez sur une touche:");
    mvwprintw(aff->cimetiere, 1, 2, "[s] pour sauvegarder save.txt");
    mvwprintw(aff->cimetiere, 2, 2, "[c] pour charger save.txt");
    mvwprintw(aff->cimetiere, 3, 2, "[u] pour undo l'action précedente");
    wrefresh(aff->cimetiere);
}
Exemplo n.º 27
0
/* render sort dialog */
void
load_sort_win (WINDOW * main_win, GModule module, GSort * sort)
{
  GMenu *menu;
  int c, quit = 1;
  int i = 0, k, n = 0;
  int opts[SORT_MAX_OPTS];
  int y, x, h = SORT_WIN_H, w = SORT_WIN_W;
  int w2 = w - 2;
  WINDOW *win;

  getmaxyx (stdscr, y, x);

  /* determine amount of sort choices */
  for (i = 0, k = 0; NULL != sort_choices[module][i]; i++) {
    const char *name = sort_choices[module][i];
    if (strcmp ("Time Served", name) == 0 && !conf.serve_usecs &&
        !conf.serve_secs)
      continue;
    else if (strcmp ("Bandwidth", name) == 0 && !conf.bandwidth)
      continue;
    else if (strcmp ("Protocol", name) == 0 && !conf.append_protocol)
      continue;
    else if (strcmp ("Method", name) == 0 && !conf.append_method)
      continue;
    opts[k++] = i;
    n++;
  }

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, SORT_MENU_H, SORT_MENU_W, SORT_MENU_Y, SORT_MENU_X);
  menu->size = n;
  menu->selectable = 1;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));

  /* set checked option and set index */
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (sort_choices[module][opts[i]]);
    if (sort->field == SORT_BY_HITS &&
        strcmp ("Hits", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_DATA &&
               strcmp ("Data", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_BW &&
               strcmp ("Bandwidth", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_USEC &&
               strcmp ("Time Served", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_PROT &&
               strcmp ("Protocol", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_MTHD &&
               strcmp ("Method", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    }
  }
  post_gmenu (menu);

  draw_header (win, "Sort active module by", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[ENTER] to select field - [TAB] sort");
  if (sort->sort == SORT_ASC)
    draw_header (win, "[x] ASC [ ] DESC", " %s", SORT_WIN_H - 2, 1,
                 SORT_WIN_W - 2, 2);
  else
    draw_header (win, "[ ] ASC [x] DESC", " %s", SORT_WIN_H - 2, 1,
                 SORT_WIN_W - 2, 2);

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, SORT_MENU_W, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, SORT_MENU_W, 0);
       break;
     case 9:   /* TAB */
       /* ascending */
       if (sort->sort == SORT_ASC) {
         sort->sort = SORT_DESC;
         draw_header (win, "[ ] ASC [x] DESC", " %s", SORT_WIN_H - 2, 1,
                      SORT_WIN_W - 2, 2);
       }
       /* descending */
       else {
         sort->sort = SORT_ASC;
         draw_header (win, "[x] ASC [ ] DESC", " %s", SORT_WIN_H - 2, 1,
                      SORT_WIN_W - 2, 2);
       }
       break;
     case 32:
     case 0x0a:
     case 0x0d:
     case KEY_ENTER:
       gmenu_driver (menu, REQ_SEL);
       for (i = 0; i < n; ++i) {
         if (menu->items[i].checked != 1)
           continue;
         if (strcmp ("Hits", menu->items[i].name) == 0)
           sort->field = SORT_BY_HITS;
         else if (strcmp ("Data", menu->items[i].name) == 0)
           sort->field = SORT_BY_DATA;
         else if (strcmp ("Bandwidth", menu->items[i].name) == 0)
           sort->field = SORT_BY_BW;
         else if (strcmp ("Time Served", menu->items[i].name) == 0)
           sort->field = SORT_BY_USEC;
         else if (strcmp ("Protocol", menu->items[i].name) == 0)
           sort->field = SORT_BY_PROT;
         else if (strcmp ("Method", menu->items[i].name) == 0)
           sort->field = SORT_BY_MTHD;
         quit = 0;
         break;
       }
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }

  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Exemplo n.º 28
0
Arquivo: ui.c Projeto: hahahafr/ziege
void
init_affichage(jeu_s jeu, aff_s *aff)
{
    initscr();
    start_color();

    init_pair(20+CHEVRE, COLOR_WHITE, COLOR_GREEN);
    init_pair(20+TIGRE, COLOR_WHITE, COLOR_RED);
    init_pair(23, COLOR_WHITE, COLOR_YELLOW);

    noecho();
    cbreak();
    curs_set(0);

    int screeny, screenx;
    int plateau_orig_y, plateau_orig_x;

    getmaxyx(stdscr, screeny, screenx);

    plateau_orig_y = (screeny-TAILLE_PLATEAU_H)/2;
    plateau_orig_x = (screenx-TAILLE_PLATEAU_L-TAILLE_ETAT_L)/2;

    WINDOW *plateau = newwin(
      TAILLE_PLATEAU_H,
      TAILLE_PLATEAU_L,
      plateau_orig_y,
      plateau_orig_x);

    WINDOW *etat = newwin(
      screeny/2,
      TAILLE_ETAT_L,
      0,
      screenx-TAILLE_ETAT_L+2);

    WINDOW *cimetiere = newwin(
      screeny/2,
      TAILLE_CIM_L,
      screeny/2,
      screenx-TAILLE_CIM_L+2);

    WINDOW *message = newwin(
      3,
      screenx-TAILLE_ETAT_L-2,
      1,
      2);

    wattron(message, A_BOLD | COLOR_PAIR(23));
    
    wborder(etat, ACS_VLINE, ' ', ' ', ACS_HLINE, ACS_VLINE, ' ', ACS_LTEE, ACS_HLINE); 
    wborder(cimetiere, ACS_VLINE, ' ', ' ', ' ', ACS_VLINE, ' ', ACS_VLINE, ' ');
    box(plateau, ACS_VLINE, ACS_HLINE);
    
    refresh();
    wrefresh(etat);
    wrefresh(cimetiere);
    wrefresh(plateau);

    (* aff) = (aff_s)malloc(sizeof(t_affichage_s));

    (* aff)->plateau_orig_y=plateau_orig_y;
    (* aff)->plateau_orig_x=plateau_orig_x;
    (* aff)->etat=etat;
    (* aff)->plateau=plateau;
    (* aff)->cimetiere=cimetiere;
    (* aff)->message=message;


    tracer_plateau((* aff));

    wrefresh(etat);
    wrefresh(cimetiere);
    wrefresh(plateau);


    for(int i = 0; i < 5; i++)
    {
        for(int j = 0; j < 5; j++)
        {
            // i = y
            // j = x
            (* aff)->tabindcoord[i][j]=malloc(2*sizeof(int));
            (* aff)->tabindcoord[i][j][ORD]=2+plateau_orig_y+(6*i);
            (* aff)->tabindcoord[i][j][ABS]=4+plateau_orig_x+(10*j);
        }
    }
}
Exemplo n.º 29
0
/* implement basic frame work to build a field input */
char *
input_string (WINDOW * win, int pos_y, int pos_x, size_t max_width,
              const char *str, int enable_case, int *toggle_case)
{
  char *s = xmalloc (max_width + 1), *tmp;
  size_t pos = 0, x = 0, quit = 1, c;

  /* window dimensions */
  size_t size_x = 0, size_y = 0, i;
  getmaxyx (win, size_y, size_x);
  size_x -= 4;

  /* are we setting a default string */
  if (str) {
    size_t len = MIN (max_width, strlen (str));
    memcpy (s, str, len);
    s[len] = '\0';

    x = pos = 0;
    /* is the default str length greater than input field? */
    if (strlen (s) > size_x) {
      tmp = xstrdup (&s[0]);
      tmp[size_x] = '\0';
      mvwprintw (win, pos_y, pos_x, "%s", tmp);
      free (tmp);
    } else
      mvwprintw (win, pos_y, pos_x, "%s", s);
  } else
    s[0] = '\0';

  if (enable_case)
    draw_header (win, "[x] case sensitive", " %s", size_y - 2, 1, size_x - 2,
                 2);

  wmove (win, pos_y, pos_x + x);
  wrefresh (win);

  curs_set (1);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case 1:   /* ^a   */
     case 262: /* HOME */
       pos = x = 0;
       break;
     case 5:
     case 360: /* END of line */
       if (strlen (s) > size_x) {
         x = size_x;
         pos = strlen (s) - size_x;
       } else {
         pos = 0;
         x = strlen (s);
       }
       break;
     case 7:   /* ^g  */
     case 27:  /* ESC */
       pos = x = 0;
       if (str && *str == '\0')
         s[0] = '\0';
       quit = 0;
       break;
     case 9:   /* TAB   */
       if (!enable_case)
         break;
       *toggle_case = *toggle_case == 0 ? 1 : 0;
       if (*toggle_case)
         draw_header (win, "[ ] case sensitive", " %s", size_y - 2, 1,
                      size_x - 2, 2);
       else if (!*toggle_case)
         draw_header (win, "[x] case sensitive", " %s", size_y - 2, 1,
                      size_x - 2, 2);
       break;
     case 21:  /* ^u */
       s[0] = '\0';
       pos = x = 0;
       break;
     case 8:   /* xterm-256color */
     case 127:
     case KEY_BACKSPACE:
       if (pos + x > 0) {
         memmove (&s[(pos + x) - 1], &s[pos + x], (max_width - (pos + x)) + 1);
         if (pos <= 0)
           x--;
         else
           pos--;
       }
       break;
     case KEY_LEFT:
       if (x > 0)
         x--;
       else if (pos > 0)
         pos--;
       break;
     case KEY_RIGHT:
       if ((x + pos) < strlen (s)) {
         if (x < size_x)
           x++;
         else
           pos++;
       }
       break;
     case 0x0a:
     case 0x0d:
     case KEY_ENTER:
       quit = 0;
       break;
     default:
       if (strlen (s) == max_width)
         break;
       if (!isprint (c))
         break;

       if (strlen (s) == pos) {
         s[pos + x] = c;
         s[pos + x + 1] = '\0';
         waddch (win, c);
       } else {
         memmove (&s[pos + x + 1], &s[pos + x], strlen (&s[pos + x]) + 1);
         s[pos + x] = c;
       }
       if ((x + pos) < max_width) {
         if (x < size_x)
           x++;
         else
           pos++;
       }
    }
    tmp = xstrdup (&s[pos > 0 ? pos : 0]);
    tmp[MIN (strlen (tmp), size_x)] = '\0';
    for (i = strlen (tmp); i < size_x; i++)
      mvwprintw (win, pos_y, pos_x + i, "%s", " ");
    mvwprintw (win, pos_y, pos_x, "%s", tmp);
    free (tmp);

    wmove (win, pos_y, pos_x + x);
    wrefresh (win);
  }
  curs_set (0);
  return s;
}
Exemplo n.º 30
0
void NcursesResize(Connection *conn, const char *file)
{
	if (has_colors() == TRUE) {
		start_color();

		init_pair(1, COLOR_WHITE, COLOR_BLUE);
		init_pair(2, COLOR_BLACK, COLOR_CYAN);
		init_pair(3, COLOR_WHITE, COLOR_MAGENTA);
		init_color(COLOR_WHITE, 500, 500, 500);
		init_pair(4, COLOR_BLACK, COLOR_WHITE);
		init_pair(5, COLOR_BLACK, COLOR_GREEN);
		init_pair(6, COLOR_CYAN, COLOR_CYAN);

		bkgd(COLOR_PAIR(2));
		attron(A_REVERSE);
	}

	curs_set(0);
	noecho();

	getmaxyx(stdscr, maxy, maxx);
	halfx = maxx >> 1;
	halfy = maxy >> 1;

	mvaddstr(maxy - 2, maxx - 17, "Press ? for help");

	/* debug
	   mvprintw(maxy - 4, maxx - 17, "maxy = %d", maxy);
	   mvprintw(maxy - 3, maxx - 17, "maxx = %d", maxx);
	 */

	refresh();

	// title window
	title = newwin(3 ,maxx - 2, 1, 1);
	if (title == NULL) {
		addstr("Unable to allocate memory for title window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(title, COLOR_PAIR(1));
	box(title, '|', '=');
	NcursesCenter(title, 1, banner);
	wrefresh(title);

	// body window (y size has to be tweaked by screen size)
	//border_body = newwin(((2 * maxy) / 3) - 5, maxx - 2, 5, 1);
	border_body = newwin(((2 * maxy) / 3) - 2, maxx - 2, 5, 1);
	if (border_body == NULL) {
		addstr("Unable to allocate memory for border body window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(border_body, COLOR_PAIR(1));
	box(border_body, '|', '=');
	wrefresh(border_body);

	body = newpad(maxy * 4, maxx - 2);
	if (body == NULL) {
		addstr("Unable to allocate memory for body window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(body, COLOR_PAIR(1));

	// usage window
	//border_usage = newwin((maxy / 2) - 5, maxx / 2, 
	/*border_usage = newwin((maxy / 2) + 1, maxx / 2 + 13, 
	  (maxy / 4) - 4, (maxx / 4) - 6);
	 */
	border_usage = newwin((maxy / 2) - 1, maxx / 2 + 13, 
			(maxy / 4) - 4, (maxx / 4) - 6);
	if (border_usage == NULL) {
		addstr("Unable to allocate memory for border usage window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}		

	wbkgd(border_usage, COLOR_PAIR(3));
	box(border_usage, '|', '=');

	/*usage = newwin((maxy / 2) - 1, (maxx / 2) + 11, 
	  (maxy / 4) - 3, (maxx / 4) - 5);
	 */
	usage = newwin((maxy / 2) - 3, (maxx / 2) + 11, 
			(maxy / 4) - 3, (maxx / 4) - 5);
	if (usage == NULL) {
		addstr("Unable to allocate memory for usage window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(usage, COLOR_PAIR(3));
	getmaxyx(usage, usage_maxy, usage_maxx);

	while (*help_ptr) {
		getyx(usage, usage_y, usage_x);
		if (*help_ptr == ' ')
			if (usage_maxx - usage_x < 12) waddch(usage, '\n');
		waddch(usage, *help_ptr);
		help_ptr++;
	}

	// console window
	border_console = newwin(5, maxx / 3, maxy - 8, maxx / 3);
	if (border_console == NULL) {
		addstr("Unable to allocate memory for border console window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(border_console, COLOR_PAIR(5));

	console = newwin(3, (maxx / 3) - 2, (maxy - 8 + 1), (maxx / 3) + 1);
	if (console == NULL) {
		addstr("Unable to allocate memory for console window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}	

	wbkgd(console, COLOR_PAIR(4));
	box(console, '*', '*');

	// add window
	add = SUBWINDOWS;
	if (add == NULL) {
		addstr("Unable to allocate memory for add window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}

	wbkgd(add, COLOR_PAIR(1));
	box(add, '|', '=');
	NcursesCenter(add, 0, "Add Record");

	// resize window
	resize = SUBWINDOWS;
	if (resize == NULL) {
		addstr("Unable to allocate memory for resize window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}

	wbkgd(resize, COLOR_PAIR(1));
	box(resize, '|', '=');
	NcursesCenter(resize, 0, "Resize to");

	// find window
	find = SUBWINDOWS;
	if (find == NULL) {
		addstr("Unable to allocate memory for find window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}

	wbkgd(find, COLOR_PAIR(1));
	box(find, '|', '=');
	NcursesCenter(find, 0, "Find");

	// create window
	create = SUBWINDOWS;
	if (create == NULL) {
		addstr("Unable to allocate memory for find window");
		DatabaseClose(conn);
		endwin();
		exit(1);
	}

	wbkgd(create, COLOR_PAIR(1));
	box(create, '|', '=');
	NcursesCenter(create, 0, "Add New Database");

	DatabaseList(conn, body);
	PREFRESH;
	refresh();
}