Ejemplo n.º 1
0
Archivo: irc.c Proyecto: klange/ponyos
void WRITE(const char *fmt, ...) {

	static int line_feed_pending = 0;

	int last_color = 0xFFFFFFFF;
	int bold_on = 0;
	int italic_on = 0;

	va_list args;
	va_start(args, fmt);
	char * tmp;
	vasprintf(&tmp, fmt, args);
	va_end(args);

	spin_lock(&c_lock);
	char * c = tmp;
	while (*c) {
		if (*c == '\n') {
			if (line_feed_pending) {
				wprintw(body_win, "\n");
			}
			line_feed_pending = 1;
			c++;
			continue;
		} else {
			if (line_feed_pending) {
				line_feed_pending = 0;
				wprintw(body_win, "\n");
			}
		}
		if (*c == 0x03) {
			c++;
			int i = -1;
			int j = -1;
			if (*c >= '0' && *c <= '9') {
				i = (*c - '0');
				c++;
			}
			if (*c >= '0' && *c <= '9') {
				i *= 10;
				i += (*c - '0');
				c++;
			}
			if (*c == ',') {
				c++;
				if (*c >= '0' && *c <= '9') {
					j = (*c - '0');
					c++;
				}
				if (*c >= '0' && *c <= '9') {
					j *= 10;
					j += (*c - '0');
					c++;
				}
			}
			int t = irc_color_to_pair(i,j);
			if (t != last_color && last_color != 0xFFFFFFFF) {
				wattroff(body_win, COLOR_PAIR(last_color));
			}
			if (i != -1) {
				wattron(body_win, COLOR_PAIR(t));
				last_color = t;
			}
			continue;
		}
		if (*c == 0x02) {
			if (bold_on) {
				wattroff(body_win, A_BOLD);
				bold_on = 0;
			} else {
				wattron(body_win, A_BOLD);
				bold_on = 1;
			}
			c++;
			continue;
		}
		if (*c == 0x16) {
			if (italic_on) {
				wattroff(body_win, A_ITALIC);
				italic_on = 0;
			} else {
				wattron(body_win, A_ITALIC);
				italic_on = 1;
			}
			c++;
			continue;
		}
		if (*c == 0x0f) {
			if (last_color != 0xFFFFFFFF) {
				wattroff(body_win, COLOR_PAIR(last_color));
				last_color = 0xFFFFFFFF;
			}
			bold_on = 0;
			wattroff(body_win, A_BOLD);
			c++;
			continue;
		}

		wprintw(body_win, "%c", *c);
		c++;
	}
	wattroff(body_win, COLOR_PAIR(last_color));
	wattroff(body_win, A_BOLD);
	wattroff(body_win, A_ITALIC);
	free(tmp);
	wrefresh(body_win);
	spin_unlock(&c_lock);
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
	int cap1, cap2;
	if (argc == 1)
	{
		cap1 = 3;
		cap2 = 5;
	}
	else
	{
		if (argc != 3)
			return 3;
		cap1 = atoi(argv[1]);
		cap2 = atoi(argv[2]);
		if (cap1 <= 0 || cap2 <= 0)
			return 5;
	}
	int ch = 0;
	int i;
	const int roof = std::max(cap1, cap2) + 2 + 2;
	Bucket b1(cap1), b2(cap2);

	initscr();
	start_color();
	cbreak();
	keypad(stdscr, true);
	noecho();
	init_pair(1, COLOR_WHITE, COLOR_BLUE);
	refresh();

	WINDOW *win1, *win2;

	win1 = newwin(cap1+2, 3, roof-(cap1+2), 2);
	win2 = newwin(cap2+2, 3, roof-(cap2+2), 6);

	box(win1, 0, 0);
	box(win2, 0, 0);

	wrefresh(win1);
	wrefresh(win2);
	move(0, 0);

	while (ch != 'q')
	{
		ch = getch();

		switch(ch)
		{
			case 'h':
				b1 << b2;
				break;
			case 'l':
				b1 >> b2;
				break;
			case 'u':
				b1.fill();
				break;
			case 'i':
				b2.fill();
				break;
			case 'j':
				b1.empty();
				break;
			case 'k':
				b2.empty();
				break;
			default:
				break;
		}
		wattron(win1, COLOR_PAIR(1));
		for (i=0; i<b1.level(); ++i)
			mvwaddch(win1, b1.max()-i, 1, ' ');
		wattroff(win1, COLOR_PAIR(1));
		for (; i<b1.max(); ++i)
			mvwaddch(win1, b1.max()-i, 1, ' ');
		wrefresh(win1);

		wattron(win2, COLOR_PAIR(1));
		for (i=0; i<b2.level(); ++i)
			mvwaddch(win2, b2.max()-i, 1, ' ');
		wattroff(win2, COLOR_PAIR(1));
		for (; i<b2.max(); ++i)
			mvwaddch(win2, b2.max()-i, 1, ' ');
		wrefresh(win2);
		move(0, 0);
	}

	endwin();
	return 0;
}
Ejemplo n.º 3
0
static void _print_text_command(allocated_block_t *allocated_block)
{
	char *tmp_char = NULL;

	wattron(text_win,
		COLOR_PAIR(allocated_block->color));

	mvwprintw(text_win, main_ycord,
		  main_xcord, "%c", allocated_block->letter);
	main_xcord += 4;

	tmp_char = conn_type_string_full(allocated_block->request->conn_type);
	mvwprintw(text_win, main_ycord, main_xcord, tmp_char);
	xfree(tmp_char);
	main_xcord += 8;

	if (allocated_block->request->rotate)
		mvwprintw(text_win, main_ycord,
			  main_xcord, "Y");
	else
		mvwprintw(text_win, main_ycord,
			  main_xcord, "N");
	main_xcord += 7;

	if (allocated_block->request->elongate)
		mvwprintw(text_win, main_ycord,
			  main_xcord, "Y");
	else
		mvwprintw(text_win, main_ycord,
			  main_xcord, "N");
	main_xcord += 7;

	mvwprintw(text_win, main_ycord,
		  main_xcord, "%d", allocated_block->request->size);
	main_xcord += 10;

	if (allocated_block->request->conn_type[0] >= SELECT_SMALL) {
#ifdef HAVE_BGP
		mvwprintw(text_win, main_ycord,
			  main_xcord, "%d",
			  allocated_block->request->small16);
		main_xcord += 5;
#endif

		mvwprintw(text_win, main_ycord,
			  main_xcord, "%d",
			  allocated_block->request->small32);
		main_xcord += 5;

#ifndef HAVE_BGL
		mvwprintw(text_win, main_ycord,
			  main_xcord, "%d",
			  allocated_block->request->small64);
		main_xcord += 5;
#endif

		mvwprintw(text_win, main_ycord,
			  main_xcord, "%d",
			  allocated_block->request->small128);
		main_xcord += 6;

#ifndef HAVE_BGL
		mvwprintw(text_win, main_ycord,
			  main_xcord, "%d",
			  allocated_block->request->small256);
		main_xcord += 6;
#endif
	} else {
#ifdef HAVE_BGL
		main_xcord += 11;
#elif defined HAVE_BGP
		main_xcord += 27;
#else
		main_xcord += 22;
#endif
	}
	mvwprintw(text_win, main_ycord,
		  main_xcord, "%s",
		  allocated_block->request->save_name);
	main_xcord = 1;
	main_ycord++;
	wattroff(text_win,
		 COLOR_PAIR(allocated_block->color));
	return;
}
Ejemplo n.º 4
0
int attron(int attrs)
{
    return wattron(mainwin, attrs);
};
Ejemplo n.º 5
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);
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
    struct vrmr_ctx vctx;

    int retval = 0, optch = 0;

    static char optstring[] = "c:d:hVW";
    struct option long_options[] = {
            {"configfile", required_argument, NULL, 'c'},
            {"debug", required_argument, NULL, 'd'},
            {"help", no_argument, NULL, 'h'},
            {"version", no_argument, NULL, 'V'},
            {"wizard", no_argument, NULL, 'W'},
            {0, 0, 0, 0},
    };
    int longopt_index = 0;

    int debug_level = NONE;
    PANEL *main_panels[5];
    char *s = NULL;

    /* some defaults */
    vuurmuur_semid = -1;
    vuurmuur_shmid = -1;
    vuurmuurlog_semid = -1;
    vuurmuurlog_shmid = -1;

    /* create the version string */
    snprintf(version_string, sizeof(version_string),
            "%s (using libvuurmuur %s)", VUURMUURCONF_VERSION,
            libvuurmuur_get_version());

    /* some initilization */
    if (vrmr_init(&vctx, "vuurmuur_conf") < 0)
        exit(EXIT_FAILURE);

    /* settings file */
    memset(vccnf.configfile_location, 0, sizeof(vccnf.configfile_location));
    if (vctx.conf.etcdir[0] == '\0')
        (void)strlcpy(vccnf.configfile_location, VUURMUURCONF_CONFIGFILE,
                sizeof(vccnf.configfile_location));
    else
        (void)snprintf(vccnf.configfile_location,
                sizeof(vccnf.configfile_location),
                "%s/vuurmuur/vuurmuur_conf.conf", vctx.conf.etcdir);

#ifdef ENABLE_NLS
    setlocale(LC_ALL, "");
    setlocale(LC_TIME, "");
    setlocale(LC_MESSAGES, "");
    setlocale(LC_COLLATE, "");
    setlocale(LC_CTYPE, "");
    setlocale(LC_MONETARY, "");
    setlocale(LC_NUMERIC, "");
#endif

    /* check if we are in utf-8 mode */
    utf8_mode = 0;

    if ((s = getenv("LC_ALL")) || (s = getenv("LC_CTYPE")) ||
            (s = getenv("LANG"))) {
        if (strstr(s, "UTF-8"))
            utf8_mode = 1;
    }

#ifdef ENABLE_NLS
    bindtextdomain("vuurmuur", xstr(VRMR_LOCALEDIR));
    textdomain("vuurmuur");
#endif

    /* process commandline options */
    while ((optch = getopt_long(argc, argv, optstring, long_options,
                    &longopt_index)) != -1) {
        switch (optch) {
            case 'h':
                print_commandline_args();
                break;

            /* configfile */
            case 'c':

                if (strlcpy(vctx.conf.configfile, optarg,
                            sizeof(vctx.conf.configfile)) >=
                        sizeof(vctx.conf.configfile)) {
                    vrmr_error(EXIT_FAILURE, VR_ERR,
                            gettext("commandline argument too long for option "
                                    "-c."));
                    exit(EXIT_FAILURE);
                }
                break;

            case 'd':

                /* convert the debug string and check the result */
                debug_level = atoi(optarg);
                if (debug_level < 0 || debug_level > HIGH) {
                    vrmr_error(EXIT_FAILURE, VR_ERR,
                            gettext("commandline debuglevel out of range."));
                    exit(EXIT_FAILURE);
                }
                vrmr_debug_level = debug_level;

                fprintf(stdout, "vuurmuur_conf: debugging enabled.\n");
                fprintf(stdout, "vuurmuur_conf: debug level: %d\n",
                        debug_level);
                break;

            case 'V':
                /* print version */
                fprintf(stdout, "Vuurmuur_conf %s\n", version_string);
                fprintf(stdout, "%s\n", VUURMUUR_COPYRIGHT);

                exit(EXIT_SUCCESS);

            case 'W': {
                char wizard_path[512] = "";
                snprintf(wizard_path, sizeof(wizard_path),
                        "%s/scripts/vuurmuur-wizard.sh", vctx.conf.datadir);
                printf("Running %s...\n", wizard_path);
                exec_wizard(wizard_path);
                exit(EXIT_SUCCESS);
            }
            default:

                vrmr_error(EXIT_FAILURE, VR_ERR,
                        gettext("unknown commandline option."));
                exit(EXIT_FAILURE);
        }
    }

    /*  close the STDERR_FILENO because it gives us annoying "Broken
        Pipe" errors on some systems with bash3. Let's see if this
        has negative side-effects. */
    close(STDERR_FILENO);

    /* init vuurmuur_conf config already to get background */
    (void)init_vcconfig(&vctx.conf, vccnf.configfile_location, &vccnf);

    /* Initialize curses */
    (void)initscr();
    (void)start_color();
    (void)cbreak();
    (void)noecho();
    (void)keypad(stdscr, (bool)TRUE);

    setup_colors();

    /* create the three main windows */
    if (!(status_frame_win = create_newwin(
                  3, COLS, LINES - 3, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(status_win = create_newwin(
                  1, COLS - 4, LINES - 2, 2, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(top_win = create_newwin(3, COLS, 0, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(main_win = create_newwin(
                  LINES - 6, COLS, 3, 0, NULL, vccnf.color_bgd)))
        exit(EXIT_FAILURE);
    if (!(mainlog_win = newwin(LINES - 8, COLS - 2, 4, 1)))
        exit(EXIT_FAILURE);

    (void)wbkgd(mainlog_win, vccnf.color_bgd);

    wattron(status_frame_win, vccnf.color_bgd);
    mvwprintw(status_frame_win, 0, 2, " %s ", gettext("Status"));
    mvwprintw(status_frame_win, 2,
            (int)(COLS - 4 - StrLen(vctx.user_data.realusername) - 6),
            " user: %s ", vctx.user_data.realusername);
    wattroff(status_frame_win, vccnf.color_bgd);

    /* Attach a panel to each window */
    main_panels[0] = new_panel(top_win);
    main_panels[1] = new_panel(main_win);
    main_panels[2] = new_panel(status_win);
    main_panels[3] = new_panel(mainlog_win);
    main_panels[4] = new_panel(status_frame_win);

    (void)update_panels();
    (void)doupdate();

    /* init the vrprint functions for the Gui */
    vrprint.error = vuumuurconf_print_error;
    vrprint.warning = vuumuurconf_print_warning;
    vrprint.info = vuumuurconf_print_info;

    if (status_print(status_win, gettext("This is Vuurmuur_conf %s, %s"),
                version_string, VUURMUUR_COPYRIGHT) < 0)
        exit(EXIT_FAILURE);

    /* setup the global busywin */
    VrBusyWinCreate();
    VrBusyWinHide();

    // form_test();

    /* startup_screen inits the config, loads the zones, rules, etc */
    if (startup_screen(&vctx, &vctx.rules, &vctx.zones, &vctx.services,
                &vctx.interfaces, &vctx.blocklist, &vctx.reg) < 0) {
        /* failure! Lets quit. */

        /* delete panels and windows */
        (void)del_panel(main_panels[0]);
        (void)del_panel(main_panels[1]);
        (void)del_panel(main_panels[2]);
        (void)del_panel(main_panels[3]);
        (void)del_panel(main_panels[4]);
        (void)destroy_win(top_win);
        (void)destroy_win(main_win);
        (void)destroy_win(status_win);
        (void)destroy_win(status_frame_win);
        /* clear screen */
        (void)refresh();
        /* end ncurses mode */
        (void)endwin();

        exit(EXIT_FAILURE);
    }

    /* setup statuslist */
    (void)setup_statuslist();

    status_print(status_win, STR_READY);

    mm_status_checkall(&vctx, NULL, &vctx.rules, &vctx.zones, &vctx.interfaces,
            &vctx.services);
    /* main menu loop */
    while (main_menu(&vctx, &vctx.rules, &vctx.zones, &vctx.interfaces,
                   &vctx.services, &vctx.blocklist, &vctx.reg) == 1)
        ;
    /* clean up the status list */
    vrmr_list_cleanup(&vuurmuur_status.StatusList);

    /* detach from shared memory, if we were attached */
    if (vuurmuur_shmp != NULL && vuurmuur_shmp != (char *)(-1) &&
            vuurmuur_shmtable != 0) {
        if (vrmr_lock(vuurmuur_semid)) {
            vuurmuur_shmtable->configtool.connected = 3;
            vrmr_unlock(vuurmuur_semid);
        }
        (void)shmdt(vuurmuur_shmp);
    }
    if (vuurmuurlog_shmp != NULL && vuurmuurlog_shmp != (char *)(-1) &&
            vuurmuurlog_shmtable != 0) {
        if (vrmr_lock(vuurmuurlog_semid)) {
            vuurmuurlog_shmtable->configtool.connected = 3;
            vrmr_unlock(vuurmuurlog_semid);
        }
        (void)shmdt(vuurmuurlog_shmp);
    }

    /* destroy the global busywin */
    VrBusyWinDelete();

    /* delete panels and windows */
    (void)del_panel(main_panels[0]);
    (void)del_panel(main_panels[1]);
    (void)del_panel(main_panels[2]);
    (void)del_panel(main_panels[3]);
    (void)del_panel(main_panels[4]);

    (void)destroy_win(mainlog_win);
    (void)destroy_win(top_win);
    (void)destroy_win(main_win);
    (void)destroy_win(status_win);
    (void)destroy_win(status_frame_win);
    /* clear screen */
    (void)refresh();

    /* end ncurses mode */
    (void)endwin();

    /* set error functions to the stdout versions */
    vrprint.error = vrmr_stdoutprint_error;
    vrprint.warning = vrmr_stdoutprint_warning;
    vrprint.info = vrmr_stdoutprint_info;
    vrprint.debug = vrmr_stdoutprint_debug;
    vrprint.audit = vrmr_stdoutprint_audit;

    /* unload the backends */
    if (vrmr_backends_unload(&vctx.conf, &vctx) < 0) {
        vrmr_error(-1, VR_ERR, gettext("unloading the backends failed"));
        retval = -1;
    }

    /* cleanup the datastructures */
    (void)vrmr_list_cleanup(&vctx.blocklist.list);
    (void)vrmr_destroy_serviceslist(&vctx.services);
    (void)vrmr_destroy_zonedatalist(&vctx.zones);
    (void)vrmr_rules_cleanup_list(&vctx.rules);
    (void)vrmr_destroy_interfaceslist(&vctx.interfaces);
    vrmr_deinit(&vctx);
    return (retval);
}
int main(void)
{
        WINDOW *win1;
        int x, y, i, j, k, tmp;	// j, k not used yet.
	int ridx;
	float ymufin=0.0, ftemp = 0.0, ftmp2 = 0.0, deltamu = 0.0, deltavar = 0.0, yvarmax = 0.0;
	float ymu[3500] = {}, yvar[3500] = {};
	int xrnd[3500] = {}, yhts[100] = {};
	int scnarr[35][100] = {};
	int slowness = 1000;

        initscr();
        cbreak();               // Line buffering disabled
        keypad(stdscr, TRUE);   // allow softkeys
        noecho();               // don't display input when (w)getch();
	curs_set(0);		// don't display the cursor.
        getmaxyx(stdscr,y,x);

	srand((unsigned)(int)time(NULL));

	win1 = newwin(y,x,0,0);

	for (i=0; i<3500; i++) {				// xrnd[index]=rand(0:99)
		xrnd[i] = rand()%100;
	}
	for (i=0; i<3500; i++) {				// i == xrnd[] index
		ridx = i-1;
		tmp = xrnd[i];
		if (scnarr[0][xrnd[i]])
			break;
		for (j=0; j<35; j++) {
			if (j == 34) {
				scnarr[j][tmp] = 1;

				yhts[tmp] = 1;
				yvar[i] = 0;
				for (k=0; k<100; k++) {
					ymu[i] = ymu[i]+(float)yhts[k]/100;	//ymu[i]
				}
				ymufin = ymu[i];
				for (k=0; k<100; k++) {
					ftemp = ((float)yhts[k] - ymufin);	//(xi-mu)
					ftemp = ftemp * ftemp;		//(xi-mu)^2
					yvar[i] =yvar[i]+ftemp;		//sum of squares
				}
				yvar[i] = yvar[i]/100;			//variance (indexed)
				if (yvar[i] > yvarmax)
					yvarmax = yvar[i];

 				for (k=0; k<35; k++) {
					if (k>0)	mvwprintw(win1,k-1,tmp," ");
					mvwaddch(win1,k,tmp,ACS_CKBOARD);
					wrefresh(win1);
  // Enable This Line when running from localhost (not over ssh):
//   					waitmics(slowness);
				}
			}else if (
					((tmp>0)&&(scnarr[j][tmp-1]==1)) ||
					(scnarr[j+1][tmp]==1) ||
					((tmp<99)&&(scnarr[j][tmp+1]==1))
				) {
				scnarr[j][tmp] = 1;

				yhts[tmp] = 35-j;
				yvar[i] = 0;
				for (k=0; k<100; k++) {
					ymu[i] = ymu[i]+(float)yhts[k]/100;
				}
				ymufin = ymu[i];
				for (k = 0; k<100; k++) {
					ftemp = ((float)yhts[k] - ymufin);	//(xi-mu)
					ftemp = ftemp*ftemp;		//(xi-mu)^2
					yvar[i] = yvar[i] + ftemp;	//sum of squares
				}
				yvar[i] = yvar[i]/100;			//variance (indexed)
				if (yvar[i] > yvarmax)
					yvarmax = yvar[i];

 				for (k=0; k<=j; k++) {
					if (k>0)	mvwprintw(win1,k-1,tmp," ");
					mvwaddch(win1,k,tmp,ACS_CKBOARD);
					wrefresh(win1);
  // Enable This Line when running from localhost (not over ssh):
  //					waitmics(slowness);
				}
				break;
			}
		}
	}
	wrefresh(win1);

	wgetch(win1);
	wclear(win1);
	/*
***********************************************************************************************
	*/
	wrefresh(win1);
	while (1) {
		k = wgetch(win1);
		if (k == 27) {				//clear BS input, keep good stuff
			k = wgetch(win1); //k == 91
			k = wgetch(win1); //k==50s+getch: pgup/pgdn; k==60s up/dn/l/r
			if (k/10 == 5) wgetch(win1); //ignore extra getch sent
		}

//if KEY_LEFT, print generatied ballistic deposition map
		if (k == 68) {
			wclear(win1);
/* deposition	*/	for (i=0; i<100; i++) {
/* map:		*/		for (j=34; j>=0; j--) {
					if (scnarr[j][i] == 1)	mvwaddch(win1,j,i,ACS_CKBOARD);

				}
			}
/* top value	*/	for (i=0; i<100; i++) {
				mvwaddch(win1,35-yhts[i],i,ACS_HLINE);
			}
/* average	*/	if (ymufin-((int)ymufin) < .5) {
/* indicator:	*/		for (i=0; i<100; i++) {
					if (scnarr[35-(int)ymufin][i]==0)
						mvwaddch(win1,36-ymufin,i,ACS_HLINE);
					if (scnarr[35-(int)ymufin][i]==1)
						mvwaddch(win1,36-ymufin,i,ACS_CKBOARD);
				}
				mvwprintw(win1,1,2,"y_mu: %.2f", ymufin);
				mvwprintw(win1,2,2,"y_mu_remainder < .5");
				mvwprintw(win1,35-(int)ymufin,0,"[%d]", (int)ymufin);
			} else {
				for (i=0; i<100; i++) {
					if (scnarr[34-(int)ymufin][i]==0)
						mvwaddch(win1,35-ymufin,i,ACS_HLINE);
					if (scnarr[34-(int)ymufin][i]==1)
						mvwaddch(win1,35-ymufin,i,ACS_CKBOARD);
				}
				mvwprintw(win1,1,2,"y_mu: %f", ymufin);
				mvwprintw(win1,2,2,"y_mu_remainder >= .5");
				mvwprintw(win1,34-(int)ymufin,0,"[%d]", (int)ymufin+1);
			}
			wrefresh(win1);

//if KEY_RIGHT, print statistics and graphs:
 		} else if (k == 67) {
			wclear(win1);
    /*  headers */	mvwprintw(win1, 0, 0," N=%d \twidth=100\tmu_final=%.3f"
				"\t\tvar_final=%.3f",ridx,ymu[ridx],yvar[ridx]);
			mvwprintw(win1, 1, 0,"\t\t\t\tdelta_mu=%.5f\tdelta_var=%.5f"
				,(ridx,ymu[ridx]/ridx),(yvar[ridx]/ridx));
			mvwprintw(win1, 3, 0," ymu[0:%d] (by 10%% bins):",ridx);
			mvwprintw(win1, 4, 0," yvar[0:%d] (by 10%% bins):",ridx);

			for (i=0; i<=10; i++) {
				ftemp = 35*(int)ymu[(int)(i*ridx/10)]/ymu[ridx];
				ftmp2 = 35*(int)yvar[(int)(i*ridx/10)]/yvarmax;
    /*  graph ymu[t]    */	mvwprintw(win1,33-ftemp,i*9+2,"%.2f",ymu[(int)(i*ridx/10)]);
				wattron(win1,A_STANDOUT);
    /*  graph yvar[y]   */	mvwprintw(win1,34-ftmp2,i*9+2,"%.2f",yvar[(int)(i*ridx/10)]);
				wattroff(win1,A_STANDOUT);
    /*  plot x axis(%)  */ 	mvwprintw(win1,34,i*9+3,"%02d%%",i*10);
			}
			wrefresh(win1);

//if KEY_UP, debug:
		} else if (k==65) {
			wclear(win1);
			mvwprintw(win1,0,0,"i:");
			mvwprintw(win1,7,0,"yhts[i]:\t(final)");
			mvwprintw(win1,14,0,"ymu[1:%d]:\t(ymu, %%-wise)",ridx);
			mvwprintw(win1,21,0,"yvar[0:%d]:\t(yvar, %%-wise)",ridx);
			for (i=0; i<100; i++){
				mvwprintw(win1,1+i/20,(i%20)*5," %2d",i);
				mvwprintw(win1,8+i/20,(i%20)*5," %2d",yhts[i]);
				mvwprintw(win1,15+i/20,(i%20)*5,"%4.1f",
					ymu[((i+1)*ridx)/100]);
				mvwprintw(win1,22+i/20,(i%20)*5,"%4.1f",
					yvar[((i+1)*ridx)/100]);
			}
			wrefresh(win1);


//if ENTER, end:
		} else if (k == 10) {
		        delwin(win1);
			endwin();
			system("clear");
			break;
		}
	}
	return k;
	/*
***********************************************************************************************
	*/
	delwin(win1);
	endwin();
	system("clear");
        return 0;
}
Ejemplo n.º 8
0
void Messages::dialog::show()
{
    werase( w );
    draw_border( w, border_color );

    scrollbar()
    .offset_x( 0 )
    .offset_y( border_width )
    .content_size( folded_filtered.size() )
    .viewport_pos( offset )
    .viewport_size( max_lines )
    .apply( w );

    // Range of window lines to print
    size_t line_from = 0, line_to;
    if( offset < folded_filtered.size() ) {
        line_to = std::min( max_lines, folded_filtered.size() - offset );
    } else {
        line_to = 0;
    }

    if( !log_from_top ) {
        // Always print from new to old
        std::swap( line_from, line_to );
    }
    std::string prev_time_str;
    bool printing_range = false;
    for( size_t line = line_from; line != line_to; ) {
        // Decrement here if printing from bottom to get the correct line number
        if( !log_from_top ) {
            --line;
        }

        const size_t folded_ind = offset + line;
        const size_t msg_ind = folded_all[folded_filtered[folded_ind]].first;
        const game_message &msg = player_messages.history( msg_ind );

        nc_color col = msgtype_to_color( msg.type, false );

        // Print current line
        print_colored_text( w, border_width + line, border_width + time_width + padding_width,
                            col, col, folded_all[folded_filtered[folded_ind]].second );

        // Generate aligned time string
        const time_point msg_time = msg.timestamp_in_turns;
        const std::string time_str = to_string_clipped( calendar::turn - msg_time, clipped_align::right );

        if( time_str != prev_time_str ) {
            // Time changed, print time string
            prev_time_str = time_str;
            right_print( w, border_width + line, border_width + msg_width + padding_width,
                         time_color, time_str );
            printing_range = false;
        } else {
            // Print line brackets to mark ranges of time
            if( printing_range ) {
                const size_t last_line = log_from_top ? line - 1 : line + 1;
                wattron( w, bracket_color );
                mvwaddch( w, border_width + last_line, border_width + time_width - 1, LINE_XOXO );
                wattroff( w, bracket_color );
            }
            wattron( w, bracket_color );
            mvwaddch( w, border_width + line, border_width + time_width - 1,
                      log_from_top ? LINE_XXOO : LINE_OXXO );
            wattroff( w, bracket_color );
            printing_range = true;
        }

        // Decrement for !log_from_top is done at the beginning
        if( log_from_top ) {
            ++line;
        }
    }

    if( filtering ) {
        wrefresh( w );
        // Print the help text
        werase( w_filter_help );
        draw_border( w_filter_help, border_color );
        for( size_t line = 0; line < help_text.size(); ++line ) {
            nc_color col = filter_help_color;
            print_colored_text( w_filter_help, border_width + line, border_width, col, col,
                                help_text[line] );
        }
        mvwprintz( w_filter_help, w_fh_height - 1, border_width, border_color, "< " );
        mvwprintz( w_filter_help, w_fh_height - 1, w_fh_width - border_width - 2, border_color, " >" );
        wrefresh( w_filter_help );

        // This line is preventing this method from being const
        filter.query( false, true ); // Draw only
    } else {
        if( filter_str.empty() ) {
            mvwprintz( w, w_height - 1, border_width, border_color, _( "< Press %s to filter, %s to reset >" ),
                       ctxt.get_desc( "FILTER" ), ctxt.get_desc( "RESET_FILTER" ) );
        } else {
            mvwprintz( w, w_height - 1, border_width, border_color, "< %s >", filter_str );
            mvwprintz( w, w_height - 1, border_width + 2, filter_color, "%s", filter_str );
        }
        wrefresh( w );
    }
}
Ejemplo n.º 9
0
static void groupchat_onDraw(ToxWindow *self, Tox *m)
{
    int x2, y2;
    getmaxyx(self->window, y2, x2);

    ChatContext *ctx = self->chatwin;

    line_info_print(self);
    wclear(ctx->linewin);

    curs_set(1);

    if (ctx->len > 0)
        mvwprintw(ctx->linewin, 1, 0, "%ls", &ctx->line[ctx->start]);

    wclear(ctx->sidebar);
    mvwhline(self->window, y2 - CHATBOX_HEIGHT, 0, ACS_HLINE, x2);

    if (self->show_peerlist) {
        mvwvline(ctx->sidebar, 0, 0, ACS_VLINE, y2 - CHATBOX_HEIGHT);
        mvwaddch(ctx->sidebar, y2 - CHATBOX_HEIGHT, 0, ACS_BTEE);

        int num_peers = groupchats[self->num].num_peers;

        wmove(ctx->sidebar, 0, 1);
        wattron(ctx->sidebar, A_BOLD);
        wprintw(ctx->sidebar, "Peers: %d\n", num_peers);
        wattroff(ctx->sidebar, A_BOLD);

        mvwaddch(ctx->sidebar, 1, 0, ACS_LTEE);
        mvwhline(ctx->sidebar, 1, 1, ACS_HLINE, SIDEBAR_WIDTH - 1);

        int N = TOX_MAX_NAME_LENGTH;
        int maxlines = y2 - SDBAR_OFST - CHATBOX_HEIGHT;
        int i;

        for (i = 0; i < num_peers && i < maxlines; ++i) {
            wmove(ctx->sidebar, i + 2, 1);
            int peer = i + groupchats[self->num].side_pos;

            /* truncate nick to fit in side panel without modifying list */
            char tmpnck[TOX_MAX_NAME_LENGTH];
            int maxlen = SIDEBAR_WIDTH - 2;
            memcpy(tmpnck, &groupchats[self->num].peer_names[peer * N], maxlen);
            tmpnck[maxlen] = '\0';

            wprintw(ctx->sidebar, "%s\n", tmpnck);
        }
    }

    int y, x;
    getyx(self->window, y, x);
    (void) x;
    int new_x = ctx->start ? x2 - 1 : wcswidth(ctx->line, ctx->pos);
    wmove(self->window, y + 1, new_x);

    wrefresh(self->window);

    if (self->help->active)
        help_onDraw(self);
}
Ejemplo n.º 10
0
Archivo: nchgdc.c Proyecto: Eeketh/hgd
int
hgd_show_dialog(struct ui *u, const char *title, const char *msg, int secs)
{
	WINDOW			*bwin, *win;
	int			 x, y, h, w;
	char			*msg_centre;
	int			 ch = 0, again = 0;

	/* we will need to redisplay the dialog if we get a resize */
	do {
		again = 0;

		hgd_calc_dialog_win_dims(&y, &x, &h, &w);
		hgd_centre_dialog_text(&msg_centre, msg);

		DPRINTF(HGD_D_INFO, "Show dialog: '%s'", title);

		if ((bwin = newwin(h + 2, w + 2, y - 1, x - 1)) == NULL) {
			DPRINTF(HGD_D_ERROR, "Could not initialise progress window");
			return (HGD_FAIL);
		}

		if ((win = newwin(h, w, y, x)) == NULL) {
			DPRINTF(HGD_D_ERROR, "Could not initialise progress window");
			return (HGD_FAIL);
		}

		wattron(win, COLOR_PAIR(HGD_CPAIR_DIALOG));
		wattron(bwin, COLOR_PAIR(HGD_CPAIR_DIALOG));

		wclear(win);
		wclear(bwin);

		wbkgd(win, COLOR_PAIR(HGD_CPAIR_DIALOG));
		box(bwin, '|', '-');

		mvwprintw(bwin, 0, w / 2 - (strlen(title) / 2), title);
		mvwprintw(win, 1, 0, msg_centre);

		redrawwin(bwin);
		redrawwin(win);
		wrefresh(bwin);
		wrefresh(win);

		if (secs)
			sleep(secs);
		else
			ch = wgetch(win);

		if (ch == KEY_RESIZE) {
			DPRINTF(HGD_D_INFO, "redraw dialog");
			hgd_resize_app(u);
			again = 1;
		}

		delwin(win);
		delwin(bwin);

		free(msg_centre);

	} while(again);

	hgd_refresh_ui(u);

	return (HGD_OK);
}
Ejemplo n.º 11
0
Archivo: nchgdc.c Proyecto: Eeketh/hgd
int
hgd_ui_queue_track(struct ui *u, char *filename)
{
	char			*full_path = NULL;
	char			*title = "[ File Upload ]";
	int			 ret = HGD_FAIL;
	WINDOW			*bwin = NULL, *win = NULL, *bar = NULL;
	int			 x, y, h, w;
	char			*msg_centre;

	DPRINTF(HGD_D_INFO, "Upload track: %s", filename);

	xasprintf(&full_path, "%s/%s", u->cwd, filename);

	hgd_calc_dialog_win_dims(&y, &x, &h, &w);
	hgd_centre_dialog_text(&msg_centre, filename);

	if ((bwin = newwin(h + 2, w + 2, y - 1, x - 1)) == NULL) {
		DPRINTF(HGD_D_ERROR, "Could not initialise progress window");
		goto clean;
	}

	if ((win = newwin(h, w, y, x)) == NULL) {
		DPRINTF(HGD_D_ERROR, "Could not initialise progress window");
		goto clean;
	}

	wattron(win, COLOR_PAIR(HGD_CPAIR_DIALOG));
	wattron(bwin, COLOR_PAIR(HGD_CPAIR_DIALOG));

	wclear(win);
	wclear(bwin);

	wbkgd(win, COLOR_PAIR(HGD_CPAIR_DIALOG));
	wbkgd(bar, COLOR_PAIR(HGD_CPAIR_PBAR_BG));
	box(bwin, '|', '-');

	mvwprintw(bwin, 0, w / 2 - (strlen(title) / 2), title);
	mvwprintw(win, 1, 0, msg_centre);

	redrawwin(bwin);
	redrawwin(win);
	wrefresh(bwin);
	wrefresh(win);

	ret = hgd_cli_queue_track(full_path, u, hgd_ui_q_callback);

	/* XXX */
	//hgd_resize_app(u);
clean:
	if (full_path)
		free(full_path);

	if (ret == HGD_OK) 
		hgd_set_statusbar_text(u, "Upload of '%s' succesful", filename);
	else
		hgd_set_statusbar_text(u, "Upload of '%s' failed", filename);

	delwin(win);
	delwin(bwin);

	free(msg_centre);

	hgd_refresh_ui(u);

	return (ret);
}
Ejemplo n.º 12
0
void NcursesAction::renderAction(WINDOW *w, std::shared_ptr<ActionType> a, int i) {
  wattron(w, NC_COLOR_PAIR_NAME_SET);
  mvwprintw(w, i, 1 + NC_ACTION_NAME, a->name.c_str() );
  wattroff(w, NC_COLOR_PAIR_NAME_SET);
}
Ejemplo n.º 13
0
static void owl_mainwin_redraw(owl_window *w, WINDOW *recwin, void *user_data)
{
  owl_message *m;
  int i, lines, isfull, viewsize;
  int x, y, savey, recwinlines, start;
  int topmsg, curmsg, markedmsgid, fgcolor, bgcolor;
  const owl_view *v;
  GList *fl;
  const owl_filter *f;
  owl_mainwin *mw = user_data;

  topmsg = owl_global_get_topmsg(&g);
  curmsg = owl_global_get_curmsg(&g);
  markedmsgid = owl_global_get_markedmsgid(&g);
  v = owl_global_get_current_view(&g);

  if (v==NULL) {
    owl_function_debugmsg("Hit a null window in owl_mainwin_redisplay.");
    return;
  }

  werase(recwin);

  recwinlines=owl_global_get_recwin_lines(&g);
  viewsize=owl_view_get_size(v);

  /* if there are no messages or if topmsg is past the end of the messages,
   * just draw a blank screen */
  if (viewsize==0 || topmsg>=viewsize) {
    if (viewsize==0) {
      owl_global_set_topmsg(&g, 0);
    }
    mw->curtruncated=0;
    mw->lastdisplayed=-1;
    return;
  }

  /* write the messages out */
  isfull=0;
  mw->curtruncated=0;
  mw->lasttruncated=0;

  for (i=topmsg; i<viewsize; i++) {
    if (isfull) break;
    m=owl_view_get_element(v, i);

    /* hold on to y in case this is the current message or deleted */
    getyx(recwin, y, x);
    savey=y;

    /* if it's the current message, account for a vert_offset */
    if (i==owl_global_get_curmsg(&g)) {
      start=owl_global_get_curmsg_vert_offset(&g);
      lines=owl_message_get_numlines(m)-start;
    } else {
      start=0;
      lines=owl_message_get_numlines(m);
    }

    /* if we match filters set the color */
    fgcolor=OWL_COLOR_DEFAULT;
    bgcolor=OWL_COLOR_DEFAULT;
    for (fl = g.filterlist; fl; fl = g_list_next(fl)) {
      f = fl->data;
      if ((owl_filter_get_fgcolor(f)!=OWL_COLOR_DEFAULT) ||
          (owl_filter_get_bgcolor(f)!=OWL_COLOR_DEFAULT)) {
        if (owl_filter_message_match(f, m)) {
          if (owl_filter_get_fgcolor(f)!=OWL_COLOR_DEFAULT) fgcolor=owl_filter_get_fgcolor(f);
          if (owl_filter_get_bgcolor(f)!=OWL_COLOR_DEFAULT) bgcolor=owl_filter_get_bgcolor(f);
	}
      }
    }

    /* if we'll fill the screen print a partial message */
    if ((y+lines > recwinlines) && (i==owl_global_get_curmsg(&g))) mw->curtruncated=1;
    if (y+lines > recwinlines) mw->lasttruncated=1;
    if (y+lines > recwinlines-1) {
      isfull=1;
      owl_message_curs_waddstr(m, recwin,
			       start,
			       start+recwinlines-y,
			       owl_global_get_rightshift(&g),
			       owl_global_get_cols(&g)+owl_global_get_rightshift(&g)-1,
			       fgcolor, bgcolor);
    } else {
      /* otherwise print the whole thing */
      owl_message_curs_waddstr(m, recwin,
			       start,
			       start+lines,
			       owl_global_get_rightshift(&g),
			       owl_global_get_cols(&g)+owl_global_get_rightshift(&g)-1,
			       fgcolor, bgcolor);
    }


    /* is it the current message and/or deleted? */
    getyx(recwin, y, x);
    wattrset(recwin, A_NORMAL);
    if (owl_global_get_rightshift(&g)==0) {   /* this lame and should be fixed */
      if (m==owl_view_get_element(v, curmsg)) {
	wmove(recwin, savey, 0);
	wattron(recwin, A_BOLD);	
	if (owl_global_get_curmsg_vert_offset(&g)>0) {
	  waddstr(recwin, "+");
	} else {
	  waddstr(recwin, "-");
	}
	if (owl_message_is_delete(m)) {
	  waddstr(recwin, "D");
	} else if (markedmsgid == owl_message_get_id(m)) {
	  waddstr(recwin, "*");
	} else {
	  waddstr(recwin, ">");
	}
	wmove(recwin, y, x);
	wattroff(recwin, A_BOLD);
      } else if (owl_message_is_delete(m)) {
	wmove(recwin, savey, 0);
	waddstr(recwin, " D");
	wmove(recwin, y, x);
      } else if (markedmsgid == owl_message_get_id(m)) {
	wmove(recwin, savey, 0);
	waddstr(recwin, " *");
	wmove(recwin, y, x);
      }
    }
    wattroff(recwin, A_BOLD);
  }
  mw->lastdisplayed=i-1;
}
Ejemplo n.º 14
0
int
gui_bar_window_print_string (struct t_gui_bar_window *bar_window,
                             enum t_gui_bar_filling filling,
                             int *x, int *y,
                             const char *string,
                             int reset_color_before_display,
                             int hide_chars_if_scrolling,
                             int *index_item, int *index_subitem, int *index_line)
{
    int x_with_hidden, size_on_screen, low_char, hidden;
    char utf_char[16], *next_char, *output;

    if (!string || !string[0])
        return 1;

    wmove (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar, *y, *x);

    if (reset_color_before_display)
    {
        gui_window_set_custom_color_fg_bg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                           CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_FG]),
                                           CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_BG]));
    }

    x_with_hidden = *x;

    hidden = 0;

    while (string && string[0])
    {
        switch (string[0])
        {
            case GUI_COLOR_COLOR_CHAR:
                string++;
                switch (string[0])
                {
                    case GUI_COLOR_FG_CHAR: /* fg color */
                        string++;
                        gui_window_string_apply_color_fg ((unsigned char **)&string,
                                                          GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                        break;
                    case GUI_COLOR_BG_CHAR: /* bg color */
                        string++;
                        gui_window_string_apply_color_bg ((unsigned char **)&string,
                                                          GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                        break;
                    case GUI_COLOR_FG_BG_CHAR: /* fg + bg color */
                        string++;
                        gui_window_string_apply_color_fg_bg ((unsigned char **)&string,
                                                             GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                        break;
                    case GUI_COLOR_EXTENDED_CHAR: /* pair number */
                        string++;
                        gui_window_string_apply_color_pair ((unsigned char **)&string,
                                                            GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                        break;
                    case GUI_COLOR_EMPHASIS_CHAR: /* emphasis */
                        string++;
                        gui_window_toggle_emphasis ();
                        break;
                    case GUI_COLOR_BAR_CHAR: /* bar color */
                        switch (string[1])
                        {
                            case GUI_COLOR_BAR_FG_CHAR:
                                /* bar foreground */
                                string += 2;
                                gui_window_set_custom_color_fg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                                CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_FG]));
                                break;
                            case GUI_COLOR_BAR_DELIM_CHAR:
                                /* bar delimiter */
                                string += 2;
                                gui_window_set_custom_color_fg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                                CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_DELIM]));
                                break;
                            case GUI_COLOR_BAR_BG_CHAR:
                                /* bar background */
                                string += 2;
                                gui_window_set_custom_color_bg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                                CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_BG]));
                                break;
                            case GUI_COLOR_BAR_START_INPUT_CHAR:
                                string += 2;
                                hidden = 0;
                                break;
                            case GUI_COLOR_BAR_START_INPUT_HIDDEN_CHAR:
                                string += 2;
                                hidden = 1;
                                break;
                            case GUI_COLOR_BAR_MOVE_CURSOR_CHAR:
                                /* move cursor to current position on screen */
                                string += 2;
                                getyx (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                       bar_window->cursor_y,
                                       bar_window->cursor_x);
                                bar_window->cursor_x += bar_window->x;
                                bar_window->cursor_y += bar_window->y;
                                break;
                            case GUI_COLOR_BAR_START_ITEM:
                                string += 2;
                                if (*index_item < 0)
                                {
                                    *index_item = 0;
                                    *index_subitem = 0;
                                }
                                else
                                {
                                    (*index_subitem)++;
                                    if (*index_subitem >= bar_window->items_subcount[*index_item])
                                    {
                                        (*index_item)++;
                                        *index_subitem = 0;
                                    }
                                }
                                *index_line = 0;
                                gui_bar_window_coords_add (bar_window,
                                                           (*index_item >= bar_window->items_count) ? -1 : *index_item,
                                                           (*index_item >= bar_window->items_count) ? -1 : *index_subitem,
                                                           *index_line,
                                                           *x + bar_window->x,
                                                           *y + bar_window->y);
                                break;
                            case GUI_COLOR_BAR_START_LINE_ITEM:
                                string += 2;
                                (*index_line)++;
                                gui_bar_window_coords_add (bar_window,
                                                           *index_item,
                                                           *index_subitem,
                                                           *index_line,
                                                           *x + bar_window->x,
                                                           *y + bar_window->y);
                                break;
                            default:
                                string++;
                                break;
                        }
                        break;
                    case GUI_COLOR_RESET_CHAR: /* reset color (keep attributes) */
                        string++;
                        gui_window_set_custom_color_fg_bg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                           CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_FG]),
                                                           CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_BG]));
                        break;
                    default:
                        gui_window_string_apply_color_weechat ((unsigned char **)&string,
                                                               GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                        break;
                }
                break;
            case GUI_COLOR_SET_ATTR_CHAR:
                string++;
                gui_window_string_apply_color_set_attr ((unsigned char **)&string,
                                                        GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                break;
            case GUI_COLOR_REMOVE_ATTR_CHAR:
                string++;
                gui_window_string_apply_color_remove_attr ((unsigned char **)&string,
                                                           GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar);
                break;
            case GUI_COLOR_RESET_CHAR:
                string++;
                gui_window_remove_color_style (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                               A_ALL_ATTR);
                gui_window_set_custom_color_fg_bg (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                   CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_FG]),
                                                   CONFIG_COLOR(bar_window->bar->options[GUI_BAR_OPTION_COLOR_BG]));
                break;
            default:
                next_char = utf8_next_char (string);
                if (!next_char)
                    break;

                memcpy (utf_char, string, next_char - string);
                utf_char[next_char - string] = '\0';

                if ((((unsigned char)utf_char[0]) < 32) && (!utf_char[1]))
                {
                    low_char = 1;
                    snprintf (utf_char, sizeof (utf_char), "%c",
                              'A' + ((unsigned char)utf_char[0]) - 1);
                }
                else
                {
                    low_char = 0;
                    if (!gui_chat_utf_char_valid (utf_char))
                        snprintf (utf_char, sizeof (utf_char), " ");
                }

                size_on_screen = utf8_char_size_screen (utf_char);
                if (size_on_screen >= 0)
                {
                    if (hide_chars_if_scrolling
                        && (x_with_hidden < bar_window->scroll_x))
                    {
                        /* hidden char (before scroll_x value) */
                        x_with_hidden++;
                    }
                    else if (!hidden)
                    {
                        if (*x + size_on_screen > bar_window->width)
                        {
                            if (filling == GUI_BAR_FILLING_VERTICAL)
                                return 1;
                            if (*y >= bar_window->height - 1)
                                return 0;
                            *x = 0;
                            (*y)++;
                            wmove (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar, *y, *x);
                        }

                        output = string_iconv_from_internal (NULL, utf_char);
                        if (low_char)
                            wattron (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar, A_REVERSE);
                        waddstr (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                 (output) ? output : utf_char);
                        if (low_char)
                            wattroff (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar, A_REVERSE);
                        if (output)
                            free (output);

                        if (gui_window_current_emphasis)
                        {
                            gui_window_emphasize (GUI_BAR_WINDOW_OBJECTS(bar_window)->win_bar,
                                                  *x, *y, size_on_screen);
                        }

                        *x += size_on_screen;
                    }
                }
                string = next_char;
                break;
        }
    }
    return 1;
}
Ejemplo n.º 15
0
// Muestra contenido de todas las celdas
void show_content(WINDOW * win, int mxrow, int mxcol) {

    register struct ent ** p;
    int row, col;
    int q_row_hidden = 0;

    for (row = offscr_sc_rows; row < mxrow; row++) {
        if (row_hidden[row]) {
            q_row_hidden++;
            continue;
        }

        register int c = rescol;
        int nextcol;
        int fieldlen;
        col = offscr_sc_cols;

        for (p = ATBL(tbl, row, offscr_sc_cols); col <= mxcol;
        p += nextcol - col, col = nextcol, c += fieldlen) {

            nextcol = col + 1;
            fieldlen = fwidth[col];
            if (col_hidden[col]) {
                c -= fieldlen;
                continue;
            }

            if ( (*p) == NULL) *p = lookat(row, col);

            // Clean format
            #ifdef USECOLORS
            if ((*p)->expr) {
                set_ucolor(win, &ucolors[EXPRESSION]);
            } else if ((*p)->label) {             // string
                set_ucolor(win, &ucolors[STRG]);
            } else if ((*p)->flags & is_valid && ! (*p)->format) {  // numeric value
                set_ucolor(win, &ucolors[NUMB]);
            } else if ((*p)->cellerror) {         // cellerror
                set_ucolor(win, &ucolors[CELL_ERROR]);
            } else if ((*p)->format && (*p)->format[0] == 'd') {  // date format
                set_ucolor(win, &ucolors[DATEF]);
            } else {
                set_ucolor(win, &ucolors[NORMAL]);
            }
            #endif

            // Cell color!
            if ((*p)->ucolor != NULL) {
                set_ucolor(win, (*p)->ucolor);
            }

            // Color selected cell
            if ((currow == row) && (curcol == col)) {
                #ifdef USECOLORS
                    if (has_colors()) set_ucolor(win, &ucolors[CELL_SELECTION_SC]);
                #else
                    wattron(win, A_REVERSE);
                #endif
            }

            // Color selected range
            int in_range = 0; // this is for coloring empty cells within a range
            srange * s = get_selected_range();
            if (s != NULL && row >= s->tlrow && row <= s->brrow && col >= s->tlcol && col <= s->brcol ) {
                #ifdef USECOLORS
                    set_ucolor(win, &ucolors[CELL_SELECTION_SC]);
                #else
                    wattron(win, A_REVERSE);
                #endif
                in_range = 1; // local variable. this is for coloring empty cells within a range
            }

            /* Color empty cells inside a range */
            if ( in_range && row >= ranges->tlrow && row <= ranges->brrow &&
                 col >= ranges->tlcol && col <= ranges->brcol
               ) {
                #ifdef USECOLORS
                    set_ucolor(win, &ucolors[CELL_SELECTION_SC]);
                #else
                    wattron(win, A_REVERSE);
                #endif
            }

            if ((*p)->cellerror == CELLERROR) {
               (void) mvprintw(row + RESROW + 1 - offscr_sc_rows, c, "%*.*s", fwidth[col], fwidth[col], "ERROR");
               continue;
            }

            // si hay valor numerico
            if ( (*p)->flags & is_valid) {
                show_numeric_content_of_cell(win, p, col, row + 1 - offscr_sc_rows - q_row_hidden, c);

            // si hay solo valor de texto
            } else if ((*p) -> label) { 
                show_text_content_of_cell(win, p, row, col, row + 1 - offscr_sc_rows - q_row_hidden, c);

            // repaint a blank cell, because of in range, or because we have a coloured empty cell!
            } else if (! ((*p)->flags & is_valid) && !(*p)->label ) {
                if ( (currow == row && curcol == col) ||
                ( in_range && row >= ranges->tlrow && row <= ranges->brrow &&
                col >= ranges->tlcol && col <= ranges->brcol ) ) {
                    #ifdef USECOLORS
                    if (has_colors()) set_ucolor(win, &ucolors[CELL_SELECTION_SC]);
                    #else
                    wattron(win, A_REVERSE);
                    #endif
                } else if ((*p)->ucolor == NULL) {
                    #ifdef USECOLORS
                    set_ucolor(win, &ucolors[STRG]); // When a long string does not fit in column.
                    #endif
                }
                char caracter;
                chtype cht[fieldlen];
                int i;
                mvwinchnstr(win, row + 1 - offscr_sc_rows - q_row_hidden, c, cht, fieldlen);
                for (i = 0; i < fieldlen; i++) {
                    caracter = cht[i] & A_CHARTEXT;
                    #ifdef NETBSD
                    if (! caracter) {
                        caracter = ' '; // this is for NetBSD compatibility
                    }
                    #endif
                    mvwprintw(win, row + 1 - offscr_sc_rows - q_row_hidden, c + i, "%c", caracter);
                }
            }

            // clean format
            #ifndef USECOLORS
                wattroff(win, A_REVERSE);
            #endif
        }
    }
}
Ejemplo n.º 16
0
void wputch(WINDOW* w, nc_color FG, long ch)
{
 wattron(w, FG);
 waddch(w, ch);
 wattroff(w, FG);
}
Ejemplo n.º 17
0
void show_text_content_of_cell(WINDOW * win, struct ent ** p, int row, int col, int r, int c) {
    char value[FBUFLEN];      // the value to be printed without padding
    char field[FBUFLEN] = ""; // the value with padding and alignment
    int col_width = fwidth[col];
    int flen;                 // current length of field
    int left;

    int str_len  = strlen((*p)->label);
    //int str_len  = scstrlen((*p)->label);
    strcpy(value, (*p)->label);

    // in case there is a format
    char s[FBUFLEN] = "";
    int res = get_formated_value(p, col, s);

    // si no entra en pantalla
    if (str_len > col_width) {
        sprintf(field, "%0*d", col_width, 0);
        subst(field, '0', '*');

        // Color selected cell
        if ((currow == row) && (curcol == col)) {
            #ifdef USECOLORS
                if (has_colors()) set_ucolor(win, &ucolors[CELL_SELECTION_SC]);
            #else
                wattron(win, A_REVERSE);
            #endif
        }
        strncpy(field, value, col_width);
        field[col_width]='\0';
        mvwprintw(win, r, c, "%s", field);

        char ex[str_len+1];
        strcpy(ex, value);
        del_range_chars(ex, 0, col_width-1);
            #ifdef USECOLORS
                if (has_colors()) set_ucolor(win, &ucolors[STRG]);
            #else
                wattroff(win, A_REVERSE);
            #endif
        mvwprintw(win, r, c + col_width, "%s", ex);
        wclrtoeol(win);
        return;

    // izquierda
    } else if ( (*p)->label && (*p)->flags & is_leftflush ) {
        strcpy(field, value);
        left = col_width - str_len;
        left = left < 0 ? 0 : left;
        flen = str_len;
        //scdebug("%d %d", left, flen);
        while (left-- && flen++) add_char(field, ' ', flen-1);

        //sprintf(field + strlen(field), "%0*d", left, 0);
        //subst(field, '0', '-');

    // centrado
    } else if ( (*p)->label && (*p)->flags & is_label) {
        left = (col_width - str_len )/2;
        left = left < 0 ? 0 : left;
        flen = 0;
        while (left-- && ++flen) add_char(field, ' ', flen-1);
        strcat(field, value);
        flen += str_len;
        left = (col_width - flen);
        left = left < 0 ? 0 : left;
        while (left-- && ++flen) add_char(field, ' ', flen-1);

    // derecha
    } else if ( (*p)->label || res == 0) {
        left = col_width - str_len;
        left = left < 0 ? 0 : left;
        flen = 0;
        while (left-- && ++flen) add_char(field, ' ', flen-1);
        strcat(field, value);
//
    }

    //scdebug("%d %d-%s-", r, c, field);
    mvwprintw(win, r, c, "%s", field);
    wclrtoeol(win);

    return;
}
Ejemplo n.º 18
0
void mvwputch(WINDOW *w, int y, int x, nc_color FG, long ch)
{
 wattron(w, FG);
 mvwaddch(w, y, x, ch);
 wattroff(w, FG);
}
Ejemplo n.º 19
0
void hl_wprintw(WINDOW *win, const char *line, int width, int offset)
{
    int length;               /* Length of the line passed in */
    enum hl_group_kind color; /* Color used to print current char */
    int i;                    /* Loops through the line char by char */
    int j;                    /* General iterator */
    int p;                    /* Count of chars printed to screen */
    int pad;                  /* Used to pad partial tabs */
    int attr;                 /* A temp variable used for attributes */
    int highlight_tabstop = cgdbrc_get (CGDBRC_TABSTOP)->variant.int_val;

    /* Jump ahead to the character at offset (process color commands too) */
    length = strlen(line);
    color = HLG_TEXT;

    for (i = 0, j = 0; i < length && j < offset; i++) {
        if (line[i] == HL_CHAR && i+1 < length) {
            /* Even though we're not printing anything in this loop,
             * the color attribute needs to be maintained for when we
             * start printing in the loop below.  This way the text
             * printed will be done in the correct color. */
            color = (int)line[++i];
        }
        else if (line[i] == '\t') {
            /* Tab character, expand to size set by user */
            j += highlight_tabstop - (j % highlight_tabstop);
        }
        else {
            /* Normal character, just increment counter by one */
            j++;
        }
    }
    pad = j - offset;

    /* Pad tab spaces if offset is less than the size of a tab */
    for (j = 0, p = 0; j < pad && p < width; j++, p++)
        wprintw(win, " ");

    /* Set the color appropriately */
    if (hl_groups_get_attr (hl_groups_instance, color, &attr) == -1)
    {
        logger_write_pos ( logger, __FILE__, __LINE__, "hl_groups_get_attr error");
        return;
    }

    wattron(win, attr);

    /* Print string 1 char at a time */
    for (; i < length && p < width; i++)
    {
        if (line[i] == HL_CHAR)
        {
            if (++i < length)
            {
                wattroff(win, attr);
                color = (int)line[i];

                if (hl_groups_get_attr (hl_groups_instance, color, &attr) == -1)
                {
                    logger_write_pos ( logger, __FILE__, __LINE__, "hl_groups_get_attr error");
                    return;
                }

                wattron(win, attr);
            }
        } else {
            switch (line[i])
            {
            case '\t':
                do {
                    wprintw(win, " ");
                    p++;
                } while ((p+offset) % highlight_tabstop > 0 && p < width);
                break;
            default:
                wprintw(win, "%c", line[i]);
                p++;
            }
        }
    }

    /* Shut off color attribute */
    wattroff(win, attr);

    for (; p < width; p++)
        wprintw(win, " ");
}
Ejemplo n.º 20
0
void		Plazza::parsing(std::string &line)
{
  std::map<std::string, Pizza *(*)(Pizza::TaillePizza, int)> _mapPizza;
  std::vector<std::string> cmd;
  std::list<Pizza *> list;
  std::istringstream iss(line);
  std::string err = "";
  std::string pizza = "";
  std::string size = "";
  std::string str;
  static int order = 0;
  int nb = 0;

  _mapPizza["regina"] = &Plazza::createPizza<Regina>;
  _mapPizza["margarita"] = &Plazza::createPizza<Margarita>;
  _mapPizza["americaine"] = &Plazza::createPizza<Americaine>;
  _mapPizza["fantasia"] = &Plazza::createPizza<Fantasia>;

  std::transform(line.begin(), line.end(), line.begin(), ::tolower);

  wattron(_body, COLOR_PAIR(2));
  while (iss && iss.rdbuf()->in_avail() != -1)
    {
      iss >> pizza;
      iss >> size;
      iss.ignore(255, 'x');
      iss >> nb;
      iss.ignore(255, ';');
      if (nb < 0)
	nb = 0;

      if (_mapPizza.find(pizza) != _mapPizza.end())
	{
	  if (size == "s" || size == "m" || size == "l"
	      || size == "xl" || size == "xxl")
	    {
	      Pizza::TaillePizza _size = findPizzaSize(size);

	      // create pizza and push back into list
	      for (int i = 0; i < nb; ++i)
		list.push_back((_mapPizza[pizza])(_size, order));

	      // Insert order into list
	      Order	tmp(order, nb, list);

	      //affOrderIntoLog(tmp)

	      _order.push_back(tmp);
	      _total += nb;
	    }
	  else
	    {
	      err = "There no such size for a pizza : " + size;
	      wclrtoeol(_body);
	      mvwprintw(_body, 4, (_parentX / 2 - 45), err.c_str());
	    }
	}
      else
	{
	  err = "There is no pizza called : " + pizza;
	  wclrtoeol(_body);
	  mvwprintw(_body, 3, (_parentX / 2 - 45), err.c_str());
	}
    }
  wattroff(_body, COLOR_PAIR(2));
  if (nb > 0)
    order++;
  affOrderIntoLog(order, nb, std::string("preparation"));
}
Ejemplo n.º 21
0
extern void get_reservation(void)
{
	int error_code = -1, active, i, recs;
	reserve_info_t resv;
	time_t now = time(NULL);
	static int printed_resv = 0;
	static int count = 0;
	static reserve_info_msg_t *resv_info_ptr = NULL, *new_resv_ptr = NULL;
	bitstr_t *nodes_req = NULL;

	if (resv_info_ptr) {
		error_code = slurm_load_reservations(resv_info_ptr->last_update,
						     &new_resv_ptr);
		if (error_code == SLURM_SUCCESS)
			 slurm_free_reservation_info_msg(resv_info_ptr);
		else if (slurm_get_errno() == SLURM_NO_CHANGE_IN_DATA) {
			error_code = SLURM_SUCCESS;
			new_resv_ptr = resv_info_ptr;
		}
	} else
		error_code = slurm_load_reservations((time_t) NULL,
						     &new_resv_ptr);

	if (error_code) {
		if (quiet_flag != 1) {
			if (!params.commandline) {
				mvwprintw(text_win,
					  main_ycord, 1,
					  "slurm_load_reservations: %s",
					  slurm_strerror(slurm_get_errno()));
				main_ycord++;
			} else {
				printf("slurm_load_reservations: %s\n",
				       slurm_strerror(slurm_get_errno()));
			}
		}
	}

	if (!params.no_header)
		_print_header_resv();

	if (new_resv_ptr)
		recs = new_resv_ptr->record_count;
	else
		recs = 0;

	if (!params.commandline) {
		if ((text_line_cnt + printed_resv) > count)
			text_line_cnt--;
	}
	printed_resv = 0;
	count = 0;
	if (params.hl)
		nodes_req = get_requested_node_bitmap();
	for (i = 0; i < recs; i++) {
		resv = new_resv_ptr->reservation_array[i];
		if (nodes_req) {
			int overlap = 0;
			bitstr_t *loc_bitmap = bit_alloc(bit_size(nodes_req));
			inx2bitstr(loc_bitmap, resv.node_inx);
			overlap = bit_overlap(loc_bitmap, nodes_req);
			FREE_NULL_BITMAP(loc_bitmap);
			if (!overlap)
				continue;
		}

		if ((resv.start_time <= now) && (resv.end_time >= now))
			active = 1;
		else
			active = 0;

		if (active && (resv.node_inx[0] != -1)) {
			int j = 0;
			resv.node_cnt = 0;
			while (resv.node_inx[j] >= 0) {
				resv.node_cnt +=
					(resv.node_inx[j + 1] + 1) -
					 resv.node_inx[j];
				set_grid_inx(resv.node_inx[j],
					     resv.node_inx[j + 1],
					     count);
				j += 2;
			}
		}

		if (resv.node_inx[0] != -1) {
			if (!params.commandline) {
				if ((count >= text_line_cnt) &&
				    (printed_resv  < (text_win->_maxy-3))) {
					resv.flags = (int)letters[count%62];
					wattron(text_win,
						COLOR_PAIR(colors[count%6]));
					_print_text_resv(&resv);
					wattroff(text_win,
						 COLOR_PAIR(colors[count%6]));
					printed_resv++;
				}
			} else {
				/* put the letter code into "flags" field */
				resv.flags = (int)letters[count%62];
				_print_text_resv(&resv);
			}
			count++;
		}
		if (count == 128)
			count = 0;
	}

	if (params.commandline && params.iterate)
		printf("\n");

	if (!params.commandline)
		main_ycord++;

	resv_info_ptr = new_resv_ptr;
	return;
}
Ejemplo n.º 22
0
void
update_history_win(WINDOW *win)
{
	int i;
	int col = COLS-2;
	int sig, rat;

	if (col > MAX_HISTORY)
		col = 4 + MAX_HISTORY;

	werase(win);
	wattron(win, WHITE);
	box(win, 0 , 0);
	print_centered(win, 0, COLS, " Signal/Rate History ");
	mvwhline(win, SIGN_POS, 1, ACS_HLINE, col);
	mvwhline(win, SIGN_POS+2, 1, ACS_HLINE, col);
	mvwvline(win, 1, 4, ACS_VLINE, LINES-3);

	wattron(win, GREEN);
	mvwprintw(win, 2, 1, "dBm");
	mvwprintw(win, normalize_db(30, SIGN_POS - 1) + 1, 1, "-30");
	mvwprintw(win, normalize_db(40, SIGN_POS - 1) + 1, 1, "-40");
	mvwprintw(win, normalize_db(50, SIGN_POS - 1) + 1, 1, "-50");
	mvwprintw(win, normalize_db(60, SIGN_POS - 1) + 1, 1, "-60");
	mvwprintw(win, normalize_db(70, SIGN_POS - 1) + 1, 1, "-70");
	mvwprintw(win, normalize_db(80, SIGN_POS - 1) + 1, 1, "-80");
	mvwprintw(win, normalize_db(90, SIGN_POS - 1) + 1, 1, "-90");
	mvwprintw(win, SIGN_POS-1, 1, "-99");

	mvwprintw(win, 1, col-6, "Signal");

	wattron(win, CYAN);
	mvwprintw(win, TYPE_POS, 1, "TYP");
	mvwprintw(win, 2, col-11, "Packet Type");

	wattron(win, A_BOLD);
	wattron(win, BLUE);
	mvwprintw(win, 3, col-4, "Rate");
	mvwprintw(win, RATE_POS-12, 1, "300");
	mvwprintw(win, RATE_POS-11, 1, "275");
	mvwprintw(win, RATE_POS-10, 1, "250");
	mvwprintw(win, RATE_POS-9, 1, "225");
	mvwprintw(win, RATE_POS-8, 1, "200");
	mvwprintw(win, RATE_POS-7, 1, "175");
	mvwprintw(win, RATE_POS-6, 1, "150");
	mvwprintw(win, RATE_POS-5, 1, "125");
	mvwprintw(win, RATE_POS-4, 1, "100");
	mvwprintw(win, RATE_POS-3, 1, " 75");
	mvwprintw(win, RATE_POS-2, 1, " 50");
	mvwprintw(win, RATE_POS-1, 1, " 25");
	wattroff(win, A_BOLD);

	i = hist.index - 1;

	while (col > 4 && hist.signal[i] != 0)
	{
		sig = normalize_db(-hist.signal[i], SIGN_POS - 1);

		wattron(win, ALLGREEN);
		mvwvline(win, sig + 1, col, ACS_BLOCK, SIGN_POS - sig - 1);

		wattron(win, get_packet_type_color(hist.type[i]));
		mvwprintw(win, TYPE_POS, col, "%c", \
			get_packet_type_char(hist.type[i]));

		if (hist.retry[i])
			mvwprintw(win, TYPE_POS+1, col, "r");

		rat = hist.rate[i]/250;

		wattron(win, A_BOLD);
		wattron(win, BLUE);
		mvwvline(win, RATE_POS - rat, col, 'x', rat);
		wattroff(win, A_BOLD);

		i--;
		col--;
		if (i < 0)
			i = MAX_HISTORY-1;
	}
	wnoutrefresh(win);
}
Ejemplo n.º 23
0
Archivo: tasks.c Proyecto: 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;
}
Ejemplo n.º 24
0
/* Month draw */
void month_draw(void)
{
	const char *name  = month_to_string(SEL.month);
	const int   start = start_of_month(SEL.year, SEL.month);
	const int   days  = days_in_month(SEL.year, SEL.month);
	const int   weeks = weeks_in_month(SEL.year, SEL.month);
	const int   hdr   = COMPACT ? 3 : 4;
	const float midpt = (float)COLS/2.0 - (strlen(name) + 1 + 4)/2.0;
	const float hstep = (float)(COLS-1)/7.0;
	const float vstep = (float)(LINES-2-hdr+COMPACT)/weeks;

	/* Load cal data */
	cal_load(SEL.year, SEL.month, 0, days);

	/* Print Header */
	if (COMPACT) wattron(win, A_REVERSE | A_BOLD);
	if (COMPACT) mvwhline(win, 0, 0, ' ' | A_REVERSE | A_BOLD, COLS);
	if (COMPACT) mvwhline(win, 1, 0, ' ' | A_REVERSE | A_BOLD, COLS);
	mvwprintw(win, 0, midpt, "%s %d", name, SEL.year);
	for (int d = 0; d < 7; d++) {
		const char *str = hstep >= 10 ? day_to_string(d+SUN) : day_to_str(d+SUN);
		mvwprintw(win, 1, ROUND(1+d*hstep), "%s", str);
	}
	if (COMPACT)  wattroff(win, A_REVERSE | A_BOLD);
	if (!COMPACT) mvwhline(win, 2, 0, ACS_HLINE, COLS);

	/* Print days */
	for (int d = 0; d < days; d++) {
		int row = (start + d) / 7;
		int col = (start + d) % 7;
		if (d == SEL.day) wattron(win, A_BOLD);
		mvwprintw(win, ROUND(hdr+row*vstep), ROUND(1+col*hstep), "%d", d+1);
		if (d == SEL.day) wattroff(win, A_BOLD);
	}

	/* Print events */
	event_t *event = EVENTS;
	for (int d = 0; d < days; d++) {
		int y = ROUND(hdr+(((start + d) / 7)  )*vstep);
		int e = ROUND(hdr+(((start + d) / 7)+1)*vstep)-2;
		int x = ROUND(1  +(((start + d) % 7)  )*hstep)+3;
		int w = ROUND(1  +(((start + d) % 7)+1)*hstep)-x-1;
		while (event && before(&event->start, SEL.year, SEL.month, d, 24, 0)) {
			if (!before(&event->start, SEL.year, SEL.month, d, 0, 0)){
				if (y == e) mvwhline(win, y, x-3, ACS_DARROW, 2);
				if (y <= e) event_line(win, event, y, x, w, 0);
				y++;
			}
			event = event->next;
		}
	}

	/* Print lines */
	for (int w = 1; w < weeks; w++)
		mvwhline(win, ROUND(hdr-1+w*vstep), 1, ACS_HLINE, COLS-2);
	for (int d = 1; d < 7; d++) {
		int top = d >=  start             ? 0     : 1;
		int bot = d <= (start+days-1)%7+1 ? weeks : weeks-1;
		mvwvline(win, ROUND(hdr+top*vstep), ROUND(d*hstep),
				ACS_VLINE, (bot-top)*vstep);
		for (int w = 1; w < weeks; w++) {
			int chr = w == top ? ACS_TTEE :
				  w == bot ? ACS_BTEE : ACS_PLUS;
			mvwaddch(win, ROUND(hdr-1+w*vstep), ROUND(d*hstep), chr);
		}
	}

	/* Draw today */
	int col = day_of_week(SEL.year, SEL.month, SEL.day);
	int row = (start+SEL.day) / 7;
	int l = ROUND((col+0)*hstep);
	int r = ROUND((col+1)*hstep);
	int t = ROUND((row+0)*vstep+hdr-1);
	int b = ROUND((row+1)*vstep+hdr-1);
	mvwvline_set(win, t, l, WACS_T_VLINE, b-t);
	mvwvline_set(win, t, r, WACS_T_VLINE, b-t);
	mvwhline_set(win, t, l, WACS_T_HLINE, r-l);
	mvwhline_set(win, b, l, WACS_T_HLINE, r-l);
	mvwadd_wch(win, t, l, WACS_T_ULCORNER);
	mvwadd_wch(win, t, r, WACS_T_URCORNER);
	mvwadd_wch(win, b, l, WACS_T_LLCORNER);
	mvwadd_wch(win, b, r, WACS_T_LRCORNER);
}
Ejemplo n.º 25
0
static void
_win_print(ProfWin *window, const char show_char, int pad_indent, GDateTime *time,
    int flags, theme_item_t theme_item, const char *const from, const char *const message, DeliveryReceipt *receipt)
{
    // flags : 1st bit =  0/1 - me/not me
    //         2nd bit =  0/1 - date/no date
    //         3rd bit =  0/1 - eol/no eol
    //         4th bit =  0/1 - color from/no color from
    //         5th bit =  0/1 - color date/no date
    gboolean me_message = FALSE;
    int offset = 0;
    int colour = theme_attrs(THEME_ME);
    size_t indent = 0;

    char *time_pref = NULL;
    switch (window->type) {
        case WIN_CHAT:
            time_pref = prefs_get_string(PREF_TIME_CHAT);
            break;
        case WIN_MUC:
            time_pref = prefs_get_string(PREF_TIME_MUC);
            break;
        case WIN_MUC_CONFIG:
            time_pref = prefs_get_string(PREF_TIME_MUCCONFIG);
            break;
        case WIN_PRIVATE:
            time_pref = prefs_get_string(PREF_TIME_PRIVATE);
            break;
        case WIN_XML:
            time_pref = prefs_get_string(PREF_TIME_XMLCONSOLE);
            break;
        default:
            time_pref = prefs_get_string(PREF_TIME_CONSOLE);
            break;
    }

    gchar *date_fmt = NULL;
    if (g_strcmp0(time_pref, "off") == 0) {
        date_fmt = g_strdup("");
    } else {
        date_fmt = g_date_time_format(time, time_pref);
    }
    prefs_free_string(time_pref);
    assert(date_fmt != NULL);

    if(strlen(date_fmt) != 0){
        indent = 3 + strlen(date_fmt);
    }

    if ((flags & NO_DATE) == 0) {
        if (date_fmt && strlen(date_fmt)) {
            if ((flags & NO_COLOUR_DATE) == 0) {
                wattron(window->layout->win, theme_attrs(THEME_TIME));
            }
            wprintw(window->layout->win, "%s %c ", date_fmt, show_char);
            if ((flags & NO_COLOUR_DATE) == 0) {
                wattroff(window->layout->win, theme_attrs(THEME_TIME));
            }
        }
    }

    if (strlen(from) > 0) {
        if (flags & NO_ME) {
            colour = theme_attrs(THEME_THEM);
        }

        if (flags & NO_COLOUR_FROM) {
            colour = 0;
        }

        if (receipt && !receipt->received) {
            colour = theme_attrs(THEME_RECEIPT_SENT);
        }

        wattron(window->layout->win, colour);
        if (strncmp(message, "/me ", 4) == 0) {
            wprintw(window->layout->win, "*%s ", from);
            offset = 4;
            me_message = TRUE;
        } else {
            wprintw(window->layout->win, "%s: ", from);
            wattroff(window->layout->win, colour);
        }
    }

    if (!me_message) {
        if (receipt && !receipt->received) {
            wattron(window->layout->win, theme_attrs(THEME_RECEIPT_SENT));
        } else {
            wattron(window->layout->win, theme_attrs(theme_item));
        }
    }

    if (prefs_get_boolean(PREF_WRAP)) {
        _win_print_wrapped(window->layout->win, message+offset, indent, pad_indent);
    } else {
        wprintw(window->layout->win, "%s", message+offset);
    }

    if ((flags & NO_EOL) == 0) {
        int curx = getcurx(window->layout->win);
        if (curx != 0) {
            wprintw(window->layout->win, "\n");
        }
    }

    if (me_message) {
        wattroff(window->layout->win, colour);
    } else {
        if (receipt && !receipt->received) {
            wattroff(window->layout->win, theme_attrs(THEME_RECEIPT_SENT));
        } else {
            wattroff(window->layout->win, theme_attrs(theme_item));
        }
    }

    g_free(date_fmt);
}
Ejemplo n.º 26
0
void
save_create(ui_t *ui)
{
    save_info_t *info;
    char savepath[128];

    // Pause the capture while saving
    capture_set_paused(1);

    // Cerate a new indow for the panel and form
    ui_panel_create(ui, 15, 68);

    // Initialize save panel specific data
    info = sng_malloc(sizeof(save_info_t));

    // Store it into panel userptr
    set_panel_userptr(ui->panel, (void*) info);

    // Initialize the fields    int total, displayed;

    info->fields[FLD_SAVE_PATH] = new_field(1, 52, 3, 13, 0, 0);
    info->fields[FLD_SAVE_FILE] = new_field(1, 47, 4, 13, 0, 0);
    info->fields[FLD_SAVE_ALL] = new_field(1, 1, 7, 4, 0, 0);
    info->fields[FLD_SAVE_SELECTED] = new_field(1, 1, 8, 4, 0, 0);
    info->fields[FLD_SAVE_DISPLAYED] = new_field(1, 1, 9, 4, 0, 0);
    info->fields[FLD_SAVE_MESSAGE] = new_field(1, 1, 10, 4, 0, 0);
    info->fields[FLD_SAVE_PCAP] = new_field(1, 1, 7, 36, 0, 0);
    info->fields[FLD_SAVE_PCAP_RTP] = new_field(1, 1, 8, 36, 0, 0);
    info->fields[FLD_SAVE_TXT] = new_field(1, 1, 9, 36, 0, 0);
    info->fields[FLD_SAVE_SAVE] = new_field(1, 10, ui->height - 2, 20, 0, 0);
    info->fields[FLD_SAVE_CANCEL] = new_field(1, 10, ui->height - 2, 40, 0, 0);
    info->fields[FLD_SAVE_COUNT] = NULL;

    // Set fields options
    field_opts_off(info->fields[FLD_SAVE_PATH], O_AUTOSKIP);
    field_opts_off(info->fields[FLD_SAVE_FILE], O_AUTOSKIP);
    field_opts_off(info->fields[FLD_SAVE_ALL], O_AUTOSKIP);
    field_opts_off(info->fields[FLD_SAVE_SELECTED], O_AUTOSKIP);
    field_opts_off(info->fields[FLD_SAVE_DISPLAYED], O_AUTOSKIP);
    field_opts_off(info->fields[FLD_SAVE_MESSAGE], O_VISIBLE);

    // Change background of input fields
    set_field_back(info->fields[FLD_SAVE_PATH], A_UNDERLINE);
    set_field_back(info->fields[FLD_SAVE_FILE], A_UNDERLINE);

    // Disable Save RTP if RTP packets are not being captured
    if (!setting_enabled(SETTING_CAPTURE_RTP))
        field_opts_off(info->fields[FLD_SAVE_PCAP_RTP], O_ACTIVE);

    // Create the form and post it
    info->form = new_form(info->fields);
    set_form_sub(info->form, ui->win);
    post_form(info->form);
    form_opts_off(info->form, O_BS_OVERLOAD);

    // Set Default field values
    sprintf(savepath, "%s", setting_get_value(SETTING_SAVEPATH));

    set_field_buffer(info->fields[FLD_SAVE_PATH], 0, savepath);
    set_field_buffer(info->fields[FLD_SAVE_SAVE], 0, "[  Save  ]");
    set_field_buffer(info->fields[FLD_SAVE_CANCEL], 0, "[ Cancel ]");

    // Set window boxes
    wattron(ui->win, COLOR_PAIR(CP_BLUE_ON_DEF));
    // Window border
    title_foot_box(ui->panel);

    // Header and footer lines
    mvwhline(ui->win, ui->height - 3, 1, ACS_HLINE, ui->width - 1);
    mvwaddch(ui->win, ui->height - 3, 0, ACS_LTEE);
    mvwaddch(ui->win, ui->height - 3, ui->width - 1, ACS_RTEE);

    // Save mode box
    mvwaddch(ui->win, 6, 2, ACS_ULCORNER);
    mvwhline(ui->win, 6, 3, ACS_HLINE, 30);
    mvwaddch(ui->win, 6, 32, ACS_URCORNER);
    mvwvline(ui->win, 7, 2, ACS_VLINE, 4);
    mvwvline(ui->win, 7, 32, ACS_VLINE, 4);
    mvwaddch(ui->win, 11, 2, ACS_LLCORNER);
    mvwhline(ui->win, 11, 3, ACS_HLINE, 30);
    mvwaddch(ui->win, 11, 32, ACS_LRCORNER);

    // Save mode box
    mvwaddch(ui->win, 6, 34, ACS_ULCORNER);
    mvwhline(ui->win, 6, 35, ACS_HLINE, 30);
    mvwaddch(ui->win, 6, 64, ACS_URCORNER);
    mvwvline(ui->win, 7, 34, ACS_VLINE, 3);
    mvwvline(ui->win, 7, 64, ACS_VLINE, 3);
    mvwaddch(ui->win, 10, 34, ACS_LLCORNER);
    mvwhline(ui->win, 10, 35, ACS_HLINE, 30);
    mvwaddch(ui->win, 10, 64, ACS_LRCORNER);

    wattroff(ui->win, COLOR_PAIR(CP_BLUE_ON_DEF));

    // Set screen labels
    mvwprintw(ui->win, 1, 27, "Save capture");
    mvwprintw(ui->win, 3, 3, "Path:");
    mvwprintw(ui->win, 4, 3, "Filename:");
    wattron(ui->win, COLOR_PAIR(CP_BLUE_ON_DEF));
    mvwprintw(ui->win, 6, 4, " Dialogs ");
    mvwprintw(ui->win, 6, 36, " Format ");
    wattroff(ui->win, COLOR_PAIR(CP_BLUE_ON_DEF));

    // Set default cursor position
    set_current_field(info->form, info->fields[FLD_SAVE_FILE]);
    form_driver(info->form, REQ_END_LINE);
    curs_set(1);

    // Get filter stats
    sip_stats_t stats = sip_calls_stats();

    // Set default save modes
    info->savemode = (stats.displayed == stats.total) ? SAVE_ALL : SAVE_DISPLAYED;
    info->saveformat = (setting_enabled(SETTING_CAPTURE_RTP))? SAVE_PCAP_RTP : SAVE_PCAP;

}
Ejemplo n.º 27
0
bool trade(game *g, npc *p, int cost, std::string deal)
{
    WINDOW* w_head = newwin( 4, 80,  0,  0);
    WINDOW* w_them = newwin(21, 40,  4,  0);
    WINDOW* w_you  = newwin(21, 40,  4, 40);
    WINDOW* w_tmp;
    mvwprintz(w_head, 0, 0, c_white, _("\
Trading with %s\n\
Tab key to switch lists, letters to pick items, Enter to finalize, Esc to quit\n\
? to get information on an item"), p->name.c_str());

// Set up line drawings
    for (int i = 0; i < 80; i++)
        mvwputch(w_head,  3, i, c_white, LINE_OXOX);
    wrefresh(w_head);


// End of line drawings

// Populate the list of what the NPC is willing to buy, and the prices they pay
// Note that the NPC's barter skill is factored into these prices.
    std::vector<int> theirs, their_price, yours, your_price;
    p->init_selling(theirs, their_price);
    p->init_buying(g->u.inv, yours, your_price);
    bool getting_theirs[theirs.size()], getting_yours[yours.size()];

// Adjust the prices based on your barter skill.
    for (int i = 0; i < their_price.size(); i++) {
        their_price[i] *= (price_adjustment(g->u.sklevel[sk_barter]) +
                           (p->int_cur - g->u.int_cur) / 15);
        getting_theirs[i] = false;
    }
    for (int i = 0; i < your_price.size(); i++) {
        your_price[i] /= (price_adjustment(g->u.sklevel[sk_barter]) +
                          (p->int_cur - g->u.int_cur) / 15);
        getting_yours[i] = false;
    }

    int cash = cost;// How much cash you get in the deal (negative = losing money)
    bool focus_them = true;	// Is the focus on them?
    bool update = true;		// Re-draw the screen?
    int them_off = 0, you_off = 0;	// Offset from the start of the list
    char ch, help;

    do {
        if (update) {	// Time to re-draw
            update = false;
// Draw borders, one of which is highlighted
            werase(w_them);
            werase(w_you);
            for (int i = 1; i < 80; i++)
                mvwputch(w_head, 3, i, c_white, LINE_OXOX);
            mvwprintz(w_head, 3, 30, ((cash <  0 && g->u.cash >= cash * -1) ||
                                      (cash >= 0 && p->cash  >= cash) ?
                                      c_green : c_red),
                      "%s $%d", (cash >= 0 ? _("Profit") : _("Cost")), abs(cash));
            if (deal != "")
                mvwprintz(w_head, 3, 45, (cost < 0 ? c_ltred : c_ltgreen), deal.c_str());
            if (focus_them)
                wattron(w_them, c_yellow);
            else
                wattron(w_you,  c_yellow);
            wborder(w_them, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
                    LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );
            wborder(w_you,  LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
                    LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );
            wattroff(w_them, c_yellow);
            wattroff(w_you,  c_yellow);
            mvwprintz(w_them, 0, 1, (cash < 0 || p->cash >= cash ? c_green : c_red),
                      "%s: $%d", p->name.c_str(), p->cash);
            mvwprintz(w_you,  0, 2, (cash > 0 || g->u.cash>=cash*-1 ? c_green:c_red),
                      "You: $%d", g->u.cash);
// Draw their list of items, starting from them_off
            for (int i = them_off; i < theirs.size() && i < 17; i++)
                mvwprintz(w_them, i - them_off + 1, 1,
                          (getting_theirs[i] ? c_white : c_ltgray), "%c %c %s - $%d",
                          char(i + 'a'), (getting_theirs[i] ? '+' : '-'),
                          p->inv[theirs[i + them_off]].tname().substr( 0,25).c_str(),
                          their_price[i + them_off]);
            if (them_off > 0)
                mvwprintw(w_them, 19, 1, _("< Back"));
            if (them_off + 17 < theirs.size())
                mvwprintw(w_them, 19, 9, _("More >"));
// Draw your list of items, starting from you_off
            for (int i = you_off; i < yours.size() && i < 17; i++)
                mvwprintz(w_you, i - you_off + 1, 1,
                          (getting_yours[i] ? c_white : c_ltgray), "%c %c %s - $%d",
                          char(i + 'a'), (getting_yours[i] ? '+' : '-'),
                          g->u.inv[yours[i + you_off]].tname().substr( 0,25).c_str(),
                          your_price[i + you_off]);
            if (you_off > 0)
                mvwprintw(w_you, 19, 1, _("< Back"));
            if (you_off + 17 < yours.size())
                mvwprintw(w_you, 19, 9, _("More >"));
            wrefresh(w_head);
            wrefresh(w_them);
            wrefresh(w_you);
        }	// Done updating the screen
        ch = getch();
        switch (ch) {
        case '\t':
            focus_them = !focus_them;
            update = true;
            break;
        case '<':
            if (focus_them) {
                if (them_off > 0) {
                    them_off -= 17;
                    update = true;
                }
            } else {
                if (you_off > 0) {
                    you_off -= 17;
                    update = true;
                }
            }
            break;
        case '>':
            if (focus_them) {
                if (them_off + 17 < theirs.size()) {
                    them_off += 17;
                    update = true;
                }
            } else {
                if (you_off + 17 < yours.size()) {
                    you_off += 17;
                    update = true;
                }
            }
            break;
        case '?':
            update = true;
            w_tmp = newwin(3, 21, 1, 30);
            mvwprintz(w_tmp, 1, 1, c_red, _("Examine which item?"));
            wborder(w_tmp, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
                    LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );
            wrefresh(w_tmp);
            help = getch();
            help -= 'a';
            werase(w_tmp);
            delwin(w_tmp);
            wrefresh(w_head);
            if (focus_them) {
                if (help >= 0 && help < theirs.size())
                    popup(p->inv[theirs[help]].info().c_str());
            } else {
                if (help >= 0 && help < yours.size())
                    popup(g->u.inv[theirs[help]].info().c_str());
            }
            break;
        case '\n':	// Check if we have enough cash...
            if (cash < 0 && g->u.cash < cash * -1) {
                popup(_("Not enough cash!  You have $%d, price is $%d."), g->u.cash, cash);
                update = true;
                ch = ' ';
            } else if (cash > 0 && p->cash < cash)
                p->op_of_u.owed += cash;
            break;
        default:	// Letters & such
            if (ch >= 'a' && ch <= 'z') {
                ch -= 'a';
                if (focus_them) {
                    if (ch < theirs.size()) {
                        getting_theirs[ch] = !getting_theirs[ch];
                        if (getting_theirs[ch])
                            cash -= their_price[ch];
                        else
                            cash += their_price[ch];
                        update = true;
                    }
                } else {	// Focus is on the player's inventory
                    if (ch < yours.size()) {
                        getting_yours[ch] = !getting_yours[ch];
                        if (getting_yours[ch])
                            cash += your_price[ch];
                        else
                            cash -= your_price[ch];
                        update = true;
                    }
                }
                ch = 0;
            }
        }
    } while (ch != KEY_ESCAPE && ch != '\n');

    if (ch == '\n') {
        inventory newinv;
        int practice = 0;
        std::vector<char> removing;
        for (int i = 0; i < yours.size(); i++) {
            if (getting_yours[i]) {
                newinv.push_back(g->u.inv[yours[i]]);
                practice++;
                removing.push_back(g->u.inv[yours[i]].invlet);
            }
        }
// Do it in two passes, so removing items doesn't corrupt yours[]
        for (int i = 0; i < removing.size(); i++)
            g->u.i_rem(removing[i]);

        for (int i = 0; i < theirs.size(); i++) {
            item tmp = p->inv[theirs[i]];
            if (getting_theirs[i]) {
                practice += 2;
                tmp.invlet = 'a';
                while (g->u.has_item(tmp.invlet)) {
                    if (tmp.invlet == 'z')
                        tmp.invlet = 'A';
                    else if (tmp.invlet == 'Z')
                        return false;	// TODO: Do something else with these.
                    else
                        tmp.invlet++;
                }
                g->u.inv.push_back(tmp);
            } else
                newinv.push_back(tmp);
        }
        g->u.practice(sk_barter, practice / 2);
        p->inv = newinv;
        g->u.cash += cash;
        p->cash   -= cash;
    }
    werase(w_head);
    werase(w_you);
    werase(w_them);
    wrefresh(w_head);
    wrefresh(w_you);
    wrefresh(w_them);
    delwin(w_head);
    delwin(w_you);
    delwin(w_them);
    if (ch == '\n')
        return true;
    return false;
}
Ejemplo n.º 28
0
void Plantinfo::update()
{

  werase(mWindow);
  box( mWindow, 0, 0 );
  wattron( mWindow, COLOR_PAIR( DEFAULT_COLOR ) );


  if( getAttr(plant) )
  {

    int i = 3;
    if( !getAttr( autoEnd ) )
    {
      mvwprintw( mWindow, 1, 2, "Plant Info" );


      INFO_PRINT( Health, health );
      INFO_PRINT( Root Level, rootLevel );
      INFO_PRINT( Leaf Level, leafLevel );
      INFO_PRINT( Flower Level, flowerLevel );
      INFO_PRINT( Root LvlUp, rootLevelUp );
      INFO_PRINT( Leaf LvlUp, leafLevelUp );
      INFO_PRINT( Flower LvlUp, flowerLevelUp );
    } else {

      std::system( "curl -s 131.151.189.189/api/top > topSeeds " );
      std::ifstream in( "topSeeds", ios::in );
      std::string seed, seeds[3];

      in >> seed;

      int k = 0;
      int start = 0;
      for( int i = 0; i < seed.length(); i++ )
      {
        if( seed[i] == ',' || i == seed.length()-1 )
        {
          seeds[k++] = seed.substr( start, i-start );
          start = i+1;
          if( k == 3 )
            break;
        }
      }

      seeds[2] += seed[seed.length()-1];

      mvwprintw( mWindow, 1, 2, "Top Seeds (pun lol)" );
      mvwprintw( mWindow, i++, 2, "1) %s", seeds[0].c_str() );
      mvwprintw( mWindow, i++, 2, "2) %s", seeds[1].c_str() );
      mvwprintw( mWindow, i++, 2, "3) %s", seeds[2].c_str() );


    }
    // Check if plant is talking
    GameState state = *getAttr( state );
    ++i;
    for( std::vector<Animation *>::iterator j = state.animations.begin(); j != state.animations.end(); j++ )
    {
      if( (*j)->type == TALK )
      {
        if( getAttr( plant )->objectID == ((Talk *)(*j))->plantID )
        {

          char *msg = ((Talk *)(*j))->message;
          bool nLine = false;


          for( int l = 0; l < 28; l++ )
          {
            if( msg[l] == '\n' )
            {
              nLine = true;
            }
          }

          while( strlen( msg ) > 28 || nLine )
          {
            nLine = false;
            char str[29];
            strncpy( str, msg, 28 );
            int n = 28;

            for( int l = 0; l < 28 && l < strlen(msg); l++ )
            {
              if( str[l] == '\n' )
              {

                str[l] = '\0';
                n = l;
                break;
              }

            }
            str[28] = '\0';
            mvwprintw( mWindow, i++, 2, "%s", str );
            msg += n+1;

            for( int l = 0; l < 28; l++ )
            {
              if( msg[l] == '\n' )
              {
                nLine = true;
                break;
              }
            }

          }
          mvwprintw( mWindow, i++, 2, "%s", msg );
        }
      }
    }


  } else {
    if( !getAttr( autoEnd ) )
Ejemplo n.º 29
0
int Window::attron(int attrs)
{
  return wattron(p->win, attrs);
}
Ejemplo n.º 30
0
inline void              NcursesDisplay::_dispAnime( void )//Champion Gnebie's awesome art
{
    wattron(stdscr, COLOR_PAIR(CATS_COLOR));
    _anime++;
    if (_anime >= 80)
    _anime = 0;
    if (_anime < 20) {
        if (_window_width - 20 > ANIME_WIDTH) {
            mvprintw(LINES - 4, ANIME_WIDTH, "  /\\**/\\");
            mvprintw(LINES - 3, ANIME_WIDTH, "  ( o_o  )_)");
            mvprintw(LINES - 2, ANIME_WIDTH, "  ,(u  u  ,),");
            mvprintw(LINES - 1, ANIME_WIDTH, " {}{}{}{}{}{}   ");
            if (_window_width - 60 > ANIME_WIDTH) {
                mvprintw(LINES - 7, ANIME_WIDTH + 20, "    |\\_._/|    ");
                mvprintw(LINES - 6, ANIME_WIDTH + 20, "    | o o |    ");
                mvprintw(LINES - 5, ANIME_WIDTH + 20, "    (  T  )    ");
                mvprintw(LINES - 4, ANIME_WIDTH + 20, "   .^`-^-'^.   ");
                mvprintw(LINES - 3, ANIME_WIDTH + 20, "   `.  ;  .'   ");
                mvprintw(LINES - 2, ANIME_WIDTH + 20, "   | | | | |   ");
                mvprintw(LINES - 1, ANIME_WIDTH + 20, "  ((_((|))_))  ");
            }
        }
    } else if (_anime < 40) {
        if (_window_width - 20 > ANIME_WIDTH) {
            mvprintw(LINES - 4, ANIME_WIDTH, "   /\\**/\\");
            mvprintw(LINES - 3, ANIME_WIDTH, "   ( o_o  )_)");
            mvprintw(LINES - 2, ANIME_WIDTH, "   ,(u  u  ,),");
            mvprintw(LINES - 1, ANIME_WIDTH, "  {}{}{}{}{}{}  ");
            if (_window_width - 60 > ANIME_WIDTH) {
                mvprintw(LINES - 7, ANIME_WIDTH + 20, "    |,\\__/|    ");
                mvprintw(LINES - 6, ANIME_WIDTH + 20, "    |  o o|    ");
                mvprintw(LINES - 5, ANIME_WIDTH + 20, "    (   T )    ");
                mvprintw(LINES - 4, ANIME_WIDTH + 20, "   .^`--^'^.   ");
                mvprintw(LINES - 3, ANIME_WIDTH + 20, "   `.  ;  .'   ");
                mvprintw(LINES - 2, ANIME_WIDTH + 20, "   | | | | |   ");
                mvprintw(LINES - 1, ANIME_WIDTH + 20, "  ((_((|))_))  ");
            }
        }
    } else if (_anime < 60) {
        if (_window_width - 20 > ANIME_WIDTH) {
            mvprintw(LINES - 4, ANIME_WIDTH, "    /\\**/\\");
            mvprintw(LINES - 3, ANIME_WIDTH, "    ( o_o  )_)");
            mvprintw(LINES - 2, ANIME_WIDTH, "    ,(u  u  ,),");
            mvprintw(LINES - 1, ANIME_WIDTH, "  {}{}{}{}{}{}  ");

            if (_window_width - 60 > ANIME_WIDTH) {
                mvprintw(LINES - 7, ANIME_WIDTH + 20, "    |\\__/,|    ");
                mvprintw(LINES - 6, ANIME_WIDTH + 20, "    |o o  |    ");
                mvprintw(LINES - 5, ANIME_WIDTH + 20, "    ( T   )    ");
                mvprintw(LINES - 4, ANIME_WIDTH + 20, "   .^`^--'^.   ");
                mvprintw(LINES - 3, ANIME_WIDTH + 20, "   `.  ;  .'   ");
                mvprintw(LINES - 2, ANIME_WIDTH + 20, "   | | | | |   ");
                mvprintw(LINES - 1, ANIME_WIDTH + 20, "  ((_((|))_))  ");
            }
        }
    } else {
        if (_window_width - 20 > ANIME_WIDTH) {
            mvprintw(LINES - 4, ANIME_WIDTH, "  /\\**/\\");
            mvprintw(LINES - 3, ANIME_WIDTH, "  ( o_o  )_)");
            mvprintw(LINES - 2, ANIME_WIDTH, "  ,(u  u  ,),");
            mvprintw(LINES - 1, ANIME_WIDTH, "  {}{}{}{}{}{}  ");


            if (_window_width - 60 > ANIME_WIDTH) {
                mvprintw(LINES - 7, ANIME_WIDTH + 20, "    |\\_._/|    ");
                mvprintw(LINES - 6, ANIME_WIDTH + 20, "    | 0 0 |    ");
                mvprintw(LINES - 5, ANIME_WIDTH + 20, "    (  T  )    ");
                mvprintw(LINES - 4, ANIME_WIDTH + 20, "   .^`-^-'^.   ");
                mvprintw(LINES - 3, ANIME_WIDTH + 20, "   `.  ;  .'   ");
                mvprintw(LINES - 2, ANIME_WIDTH + 20, "   | | | | |   ");
                mvprintw(LINES - 1, ANIME_WIDTH + 20, "  ((_((|))_))  ");
            }
        }
    }
    wattroff(stdscr, COLOR_PAIR(CATS_COLOR));
}