Ejemplo n.º 1
0
int worldfactory::show_worldgen_tab_confirm(WINDOW *win, WORLDPTR world)
{
    const int iTooltipHeight = 1;
    const int iContentHeight = FULL_SCREEN_HEIGHT - 3 - iTooltipHeight;

    const int iOffsetX = (TERMX > FULL_SCREEN_WIDTH) ? (TERMX - FULL_SCREEN_WIDTH) / 2 : 0;
    const int iOffsetY = (TERMY > FULL_SCREEN_HEIGHT) ? (TERMY - FULL_SCREEN_HEIGHT) / 2 : 0;

    WINDOW *w_confirmation = newwin(iContentHeight, FULL_SCREEN_WIDTH - 2, iTooltipHeight + 2 + iOffsetY, 1 + iOffsetX);

    unsigned namebar_pos = 3 + utf8_width(_("World Name:"));

    int line = 1;
    bool noname = false;
    long ch;

    std::string worldname = world->world_name;
    do {
        mvwprintz(w_confirmation, 2, 2, c_ltgray, _("World Name:"));
        mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "______________________________");

        fold_and_print(w_confirmation, 10, 2, 76, c_ltgray,
                       _("When you are satisfied with the world as it is and are ready to continue, press >"));
        fold_and_print(w_confirmation, 12, 2, 76, c_ltgray, _("To go back and review your world, press <"));
        fold_and_print(w_confirmation, 14, 2, 76, c_green, _("To pick a random name for your world, press ?."));

        if (!noname) {
            mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "%s", worldname.c_str());
            if (line == 1) {
                wprintz(w_confirmation, h_ltgray, "_");
            }
        }

        wrefresh(win);
        wrefresh(w_confirmation);
        refresh();
        ch = input();
        if (noname) {
            mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "______________________________");
            noname = false;
        }


        if (ch == '>') {
            if (worldname.size() == 0) {
                mvwprintz(w_confirmation, 2, namebar_pos, h_ltgray, _("______NO NAME ENTERED!!!!_____"));
                noname = true;
                wrefresh(w_confirmation);
                if (!query_yn(_("Are you SURE you're finished? World name will be randomly generated."))) {
                    continue;
                    continue;
                } else {
                    world->world_name = pick_random_name();
                    if (!valid_worldname(world->world_name)) {
                        continue;
                    }
                    return 1;
                }
            } else if (query_yn(_("Are you SURE you're finished?")) && valid_worldname(worldname)) {
                world->world_name = worldname;
                werase(w_confirmation);
                delwin(w_confirmation);

                return 1;
            } else {
                continue;
            }
        } else if (ch == '<') {
            world->world_name = worldname;
            werase(w_confirmation);
            delwin(w_confirmation);
            return -1;
        } else if (ch == '?') {
            mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "______________________________");
            world->world_name = worldname = pick_random_name();
        } else if (ch == KEY_ESCAPE){
            world->world_name = worldname; // cache the current worldname just in case they say No to the exit query
            return -999;
        } else {
            switch (line) {
                case 1:
                    if (ch == KEY_BACKSPACE || ch == 127) {
                        if (worldname.size() > 0) {
                            //erase utf8 character TODO: make a function
                            while(worldname.size() > 0 && ((unsigned char)worldname[worldname.size() - 1]) >= 128 &&
                                    ((unsigned char)worldname[(int)worldname.size() - 1]) <= 191) {
                                worldname.erase(worldname.size() - 1);
                            }
                            worldname.erase(worldname.size() - 1);
                            mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "______________________________ ");
                            mvwprintz(w_confirmation, 2, namebar_pos, c_ltgray, "%s", worldname.c_str());
                            wprintz(w_confirmation, h_ltgray, "_");
                        }
                    } else if (is_char_allowed(ch) && utf8_width(worldname.c_str()) < 30) {
                        worldname.push_back(ch);
                    } else if(ch == KEY_F(2)) {
                        std::string tmp = get_input_string_from_file();
                        int tmplen = utf8_width(tmp.c_str());
                        if(tmplen > 0 && tmplen + utf8_width(worldname.c_str()) < 30) {
                            worldname.append(tmp);
                        }
                    }
                    //experimental unicode input
                    else if(ch > 127) {
                        std::string tmp = utf32_to_utf8(ch);
                        int tmplen = utf8_width(tmp.c_str());
                        if(tmplen > 0 && tmplen + utf8_width(worldname.c_str()) < 30) {
                            worldname.append(tmp);
                        }
                    }
                    break;
            }
        }
    } while (true);

    return 0;
}
Ejemplo n.º 2
0
static void friendlist_onDraw(ToxWindow *self, Tox *m)
{
    curs_set(0);
    werase(self->window);
    int x2, y2;
    getmaxyx(self->window, y2, x2);

    uint64_t cur_time = get_unix_time();
    struct tm cur_loc_tm = *localtime(&cur_time);

    bool fix_statuses = x2 != self->x;    /* true if window x axis has changed */

    wattron(self->window, COLOR_PAIR(CYAN));
    wprintw(self->window, " Open a chat window with the");
    wattron(self->window, A_BOLD);
    wprintw(self->window, " Enter ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "key. Delete a friend with the");
    wattron(self->window, A_BOLD);
    wprintw(self->window, " Delete ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "key.\n\n");
    wattroff(self->window, COLOR_PAIR(CYAN));

    pthread_mutex_lock(&Winthread.lock);
    int nf = tox_get_num_online_friends(m);
    pthread_mutex_unlock(&Winthread.lock);

    wattron(self->window, A_BOLD);
    wprintw(self->window, " Online: ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "%d/%d \n\n", nf, num_friends);

    if ((y2 - FLIST_OFST) <= 0)    /* don't allow division by zero */
        return;

    int selected_num = 0;

    /* Determine which portion of friendlist to draw based on current position */
    int page = num_selected / (y2 - FLIST_OFST);
    int start = (y2 - FLIST_OFST) * page;
    int end = y2 - FLIST_OFST + start;

    int i;

    for (i = start; i < num_friends && i < end; ++i) {
        int f = friendlist_index[i];
        bool f_selected = false;

        if (friends[f].active) {
            if (i == num_selected) {
                wattron(self->window, A_BOLD);
                wprintw(self->window, " > ");
                wattroff(self->window, A_BOLD);
                selected_num = f;
                f_selected = true;
            } else {
                wprintw(self->window, "   ");
            }

            if (friends[f].online) {
                uint8_t status = friends[f].status;
                int colour = WHITE;

                switch (status) {
                    case TOX_USERSTATUS_NONE:
                        colour = GREEN;
                        break;

                    case TOX_USERSTATUS_AWAY:
                        colour = YELLOW;
                        break;

                    case TOX_USERSTATUS_BUSY:
                        colour = RED;
                        break;

                    case TOX_USERSTATUS_INVALID:
                        colour = MAGENTA;
                        break;
                }

                wattron(self->window, COLOR_PAIR(colour) | A_BOLD);
                wprintw(self->window, "O ");
                wattroff(self->window, COLOR_PAIR(colour) | A_BOLD);

                if (f_selected)
                    wattron(self->window, COLOR_PAIR(BLUE));

                wattron(self->window, A_BOLD);
                wprintw(self->window, "%s", friends[f].name);
                wattroff(self->window, A_BOLD);

                if (f_selected)
                    wattroff(self->window, COLOR_PAIR(BLUE));

                /* Reset friends[f].statusmsg on window resize */
                if (fix_statuses) {
                    uint8_t statusmsg[TOX_MAX_STATUSMESSAGE_LENGTH] = {'\0'};

                    pthread_mutex_lock(&Winthread.lock);
                    uint16_t s_len = tox_get_status_message(m, friends[f].num, statusmsg,
                                                            TOX_MAX_STATUSMESSAGE_LENGTH);
                    pthread_mutex_unlock(&Winthread.lock);

                    friends[f].statusmsg_len = s_len;
                    friends[f].statusmsg[s_len] = '\0';
                    snprintf(friends[f].statusmsg, sizeof(friends[f].statusmsg), "%s", statusmsg);
                }

                /* Truncate note if it doesn't fit on one line */
                uint16_t maxlen = x2 - getcurx(self->window) - 2;

                if (friends[f].statusmsg_len > maxlen) {
                    friends[f].statusmsg[maxlen - 3] = '\0';
                    strcat(friends[f].statusmsg, "...");
                    friends[f].statusmsg[maxlen] = '\0';
                    friends[f].statusmsg_len = maxlen;
                }

                if (friends[f].statusmsg[0])
                    wprintw(self->window, " %s", friends[f].statusmsg);

                wprintw(self->window, "\n");
            } else {
                wprintw(self->window, "o ");

                if (f_selected)
                    wattron(self->window, COLOR_PAIR(BLUE));

                wattron(self->window, A_BOLD);
                wprintw(self->window, "%s", friends[f].name);
                wattroff(self->window, A_BOLD);

                if (f_selected)
                    wattroff(self->window, COLOR_PAIR(BLUE));

                uint64_t last_seen = friends[f].last_online.last_on;

                if (last_seen != 0) {
                    int day_dist = (cur_loc_tm.tm_yday - friends[f].last_online.tm.tm_yday) % 365;
                    const uint8_t *hourmin = friends[f].last_online.hour_min_str;

                    switch (day_dist) {
                        case 0:
                            wprintw(self->window, " Last seen: Today %s\n", hourmin);
                            break;

                        case 1:
                            wprintw(self->window, " Last seen: Yesterday %s\n", hourmin);
                            break;

                        default:
                            wprintw(self->window, " Last seen: %d days ago\n", day_dist);
                            break;
                    }
                } else {
                    wprintw(self->window, " Last seen: Never\n");
                }
            }
        }
    }

    self->x = x2;
    wrefresh(self->window);
    draw_popup(self, m);

    if (num_friends) {
        wmove(self->window, y2 - 1, 1);

        wattron(self->window, A_BOLD);
        wprintw(self->window, "ID: ");
        wattroff(self->window, A_BOLD);

        int i;

        for (i = 0; i < TOX_CLIENT_ID_SIZE; ++i)
            wprintw(self->window, "%02X", friends[selected_num].pub_key[i] & 0xff);
    }
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
    int option;
    unsigned int flags = WATCH_ENABLE;

    /*@ -observertrans @*/
    switch (gpsd_units()) {
    case imperial:
	altfactor = METERS_TO_FEET;
	altunits = "ft";
	speedfactor = MPS_TO_MPH;
	speedunits = "mph";
	break;
    case nautical:
	altfactor = METERS_TO_FEET;
	altunits = "ft";
	speedfactor = MPS_TO_KNOTS;
	speedunits = "knots";
	break;
    case metric:
	altfactor = 1;
	altunits = "m";
	speedfactor = MPS_TO_KPH;
	speedunits = "kph";
	break;
    default:
	/* leave the default alone */
	break;
    }
    /*@ +observertrans @*/

    /* Process the options.  Print help if requested. */
    while ((option = getopt(argc, argv, "hVl:smu:D:")) != -1) {
	switch (option) {
#ifdef CLIENTDEBUG_ENABLE
	case 'D':
	    debug = atoi(optarg);
	    gps_enable_debug(debug, stderr);
	    break;
#endif /* CLIENTDEBUG_ENABLE */
	case 'm':
	    magnetic_flag = true;
	    break;
	case 's':
	    silent_flag = true;
	    break;
	case 'u':
	    /*@ -observertrans @*/
	    switch (optarg[0]) {
	    case 'i':
		altfactor = METERS_TO_FEET;
		altunits = "ft";
		speedfactor = MPS_TO_MPH;
		speedunits = "mph";
		continue;
	    case 'n':
		altfactor = METERS_TO_FEET;
		altunits = "ft";
		speedfactor = MPS_TO_KNOTS;
		speedunits = "knots";
		continue;
	    case 'm':
		altfactor = 1;
		altunits = "m";
		speedfactor = MPS_TO_KPH;
		speedunits = "kph";
		continue;
	    default:
		(void)fprintf(stderr, "Unknown -u argument: %s\n", optarg);
	    }
	    break;
	    /*@ +observertrans @*/
	case 'V':
	    (void)fprintf(stderr, "cgps: %s (revision %s)\n",
			  VERSION, REVISION);
	    exit(EXIT_SUCCESS);
	case 'l':
	    switch (optarg[0]) {
	    case 'd':
		deg_type = deg_dd;
		continue;
	    case 'm':
		deg_type = deg_ddmm;
		continue;
	    case 's':
		deg_type = deg_ddmmss;
		continue;
	    default:
		(void)fprintf(stderr, "Unknown -l argument: %s\n", optarg);
		/*@ -casebreak @*/
	    }
	    break;
	case 'h':
	default:
	    usage(argv[0]);
	    break;
	}
    }

    /* Grok the server, port, and device. */
    if (optind < argc) {
	gpsd_source_spec(argv[optind], &source);
    } else
	gpsd_source_spec(NULL, &source);

    /* Open the stream to gpsd. */
    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf(stderr,
		      "cgps: no gpsd running or network error: %d, %s\n",
		      errno, gps_errstr(errno));
	exit(EXIT_FAILURE);
    }

    /* note: we're assuming BSD-style reliable signals here */
    (void)signal(SIGINT, die);
    (void)signal(SIGHUP, die);
    (void)signal(SIGWINCH, resize);

    windowsetup();

    status_timer = time(NULL);

    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    /* heart of the client */
    for (;;) {
	int c;

	if (!gps_waiting(&gpsdata, 5000000)) {
	    die(GPS_TIMEOUT);
	} else {
	    errno = 0;
	    if (gps_read(&gpsdata) == -1) {
		fprintf(stderr, "cgps: socket error 4\n");
		die(errno == 0 ? GPS_GONE : GPS_ERROR);
	    } else {
		/* Here's where updates go now that things are established. */
#ifdef TRUENORTH
		if (compass_flag)
		    update_compass_panel(&gpsdata);
		else
#endif /* TRUENORTH */
		    update_gps_panel(&gpsdata);
	    }
	}

	/* Check for user input. */
	c = wgetch(datawin);

	switch (c) {
	    /* Quit */
	case 'q':
	    die(CGPS_QUIT);
	    break;

	    /* Toggle spewage of raw gpsd data. */
	case 's':
	    silent_flag = !silent_flag;
	    break;

	    /* Clear the spewage area. */
	case 'c':
	    (void)werase(messages);
	    break;

	default:
	    break;
	}
    }
}
Ejemplo n.º 4
0
int showmenu(const char* title, vector<char*>& options) {
    int ch;
    int line = 0;
    int offset = 0;
    int typed = 0;
    WINDOW* menu = newwin(LINES-1, COLS, 0, 0);
    PANEL* pmenu = new_panel(menu);
    status(" ");

    do {
        werase(menu);
        wprintw(menu, title);

        int start = offset;
        int end = offset + (LINES-4);
        if (end > (int)options.size()) end = options.size();
        for (int x = start; x < end; x++) {
            mvwprintw(menu, x-start+3, 0, "%d: %s\n", x+1, options[x]);
            if (x == line) mvwchgat(menu, x-start+3, 0, -1, A_REVERSE, 0, NULL);
        }
        update_panels();
        doupdate();

        ch = getch();
        switch (ch) {
        case KEY_UP:
            line--;
            if (line < 0) line = 0;
            if (line-1 <= start) {
                offset--;
                if (offset < 0) offset = 0;
            }
            if (typed) status(" ");
            typed = 0;
            break;
        case KEY_DOWN:
            line++;
            if (line >= end) line = end-1;
            if (line-start+5 >= LINES) {
                offset++;
            }
            if (typed) status(" ");
            typed = 0;
            break;
        case KEY_PPAGE:
            line -= LINES-4;
            if (line < 0) line = 0;
            offset = line-1;
            if (offset < 0) offset = 0;
            break;
        case KEY_NPAGE:
            line += LINES-4;
            if (line >= (int)options.size())
                line = options.size()-1;
            offset = line-LINES+6;
            if (offset < 0) offset = 0;
            break;
        case KEY_HOME:
            line = 0;
            offset = 0;
            break;
        case KEY_END:
            line = options.size()-1;
            offset = line-LINES+6;
            if (offset < 0) offset = 0;
            break;
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            typed *= 10;
            typed += ch - '0';
            line = typed-1;
            if (line >= (int)options.size()) line = options.size()-1;
            status("%d", typed);
            break;
        }
    } while (ch != '\n');

    del_panel(pmenu);
    delwin(menu);
    refresh();
    return line;
}
Ejemplo n.º 5
0
void uimenu::show() {
    if (!started) {
        bool w_auto = (w_width == -1 || w_width == -2 );
        bool w_autofold = ( w_width == -2);
        int realtextwidth = 0;

        if ( w_auto ) {
            w_width = 4;
        }

        bool h_auto = (w_height == -1);
        if ( h_auto ) {
            w_height = 4;
        }

        std::vector<int> autoassign;
        autoassign.clear();
        int pad = pad_left + pad_right + 2;
        for ( int i = 0; i < entries.size(); i++ ) {
			int txtwidth = utf8_width(entries[ i ].txt.c_str());
            if(entries[ i ].enabled) {
                if( entries[ i ].hotkey > 0 ) {
                    keymap[ entries[ i ].hotkey ] = i;
                } else if ( entries[ i ].hotkey == -1 ) {
                    autoassign.push_back(i);
                }
                if ( entries[ i ].retval == -1 ) {
                    entries[ i ].retval = i;
                }
                if ( w_auto && w_width < txtwidth + pad + 4 ) {
                    w_width = txtwidth + pad + 4;
                }
            } else {
                if ( w_auto && w_width < txtwidth + pad + 4 ) {
                    w_width = txtwidth + pad + 4;    // todo: or +5 if header
                }
            }
        }
        if ( autoassign.size() > 0 ) {
            for ( int a = 0; a < autoassign.size(); a++ ) {
                int palloc = autoassign[ a ];
                if ( palloc < 9 ) {
                    entries[ palloc ].hotkey = palloc + 49; // 1-9;
                } else if ( palloc == 9 ) {
                    entries[ palloc ].hotkey = palloc + 39; // 0;
                } else if ( palloc < 36 ) {
                    entries[ palloc ].hotkey = palloc + 87; // a-z
                } else if ( palloc < 61 ) {
                    entries[ palloc ].hotkey = palloc + 29; // A-Z
                }
                if ( palloc < 61 ) {
                    keymap[ entries[ palloc ].hotkey ] = palloc;
                }
            }
        }

        if (w_auto && w_width > TERMX) {
            w_width = TERMX;
        }

        if(text.size() > 0 ) {
			int twidth = utf8_width(text.c_str());
            if ( textwidth == -1 ) {
                if ( w_autofold || !w_auto ) {
                   realtextwidth = w_width - 4;
                } else {
                   realtextwidth = twidth;
                   if ( twidth + 4 > w_width ) {
                       if ( realtextwidth + 4 > TERMX ) {
                           realtextwidth = TERMX - 4;
                       }
                       w_width = realtextwidth + 4;
                   }
                }
            } else if ( textwidth != -1 ) {
                realtextwidth = textwidth;
            }
            textformatted = foldstring(text, realtextwidth);
        }

        if (h_auto) {
            w_height = 2 + textformatted.size() + entries.size();
        }

        vmax = entries.size();
        if ( w_height > TERMY ) {
            w_height = TERMY;
        }
        if ( vmax + 2 + textformatted.size() > w_height ) {
            vmax = w_height - 2 - textformatted.size();
            if ( vmax < 1 ) {
                popup("Can't display menu options, %d %d available screen rows are occupied by\n'%s\n(snip)\n%s'\nThis is probably a bug.\n",
                   textformatted.size(),TERMY,textformatted[0].c_str(),textformatted[textformatted.size()-1].c_str()
                );
            }
        }

        if (w_x == -1) {
            w_x = int((TERMX - w_width) / 2);
        }
        if (w_y == -1) {
            w_y = int((TERMY - w_height) / 2);
        }

        window = newwin(w_height, w_width, w_y, w_x);
        werase(window);
        wattron(window, border_color);
        wborder(window, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
                LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );
        wattroff(window, border_color);
        if( title.size() > 0 ) {
            mvwprintz(window, 0, 1, border_color, "< ");
            wprintz(window, title_color, "%s", title.c_str() );
            wprintz(window, border_color, " >");
        }
        started = true;
    }
    std::string padspaces = std::string(w_width - 2 - pad_left - pad_right, ' ');
    for ( int i = 0; i < textformatted.size(); i++ ) {
        mvwprintz(window, 1+i, 2, text_color, "%s", textformatted[i].c_str());
    }
    int estart = textformatted.size() + 1; // todo fold text + get offset

    if ( selected < vshift ) {
        vshift=selected;
    } else if ( selected >= vshift + vmax ) {
        vshift=1+selected-vmax;
    }
    for ( int ei = vshift, si=0; si < vmax; ei++,si++ ) {
        if ( ei < entries.size() ) {
            nc_color co = ( ei == selected ? hilight_color : ( entries[ ei ].enabled ? text_color : disabled_color ) );
            if ( hilight_full ) {
               mvwprintz(window, estart + si, pad_left + 1, co , "%s", padspaces.c_str());
            }
            if(entries[ ei ].enabled && entries[ ei ].hotkey > 33 && entries[ ei ].hotkey < 126 ) {
               mvwprintz(window, estart + si, pad_left + 2, ( ei == selected ? hilight_color : hotkey_color ) , "%c", entries[ ei ].hotkey);
            }
            mvwprintz(window, estart + si, pad_left + 4, co, "%s", entries[ ei ].txt.c_str() );
        } else {
            mvwprintz(window, estart + si, pad_left + 1, c_ltgray , "%s", padspaces.c_str());
        }
    }
    wrefresh(window);
}
Ejemplo n.º 6
0
static void friendlist_onDraw(ToxWindow *self, Tox *m)
{
    curs_set(0);
    werase(self->window);
    int x2, y2;
    getmaxyx(self->window, y2, x2);

    bool fix_statuses = x2 != self->x;    /* true if window max x value has changed */

    wattron(self->window, COLOR_PAIR(CYAN));
    wprintw(self->window, " Press the");
    wattron(self->window, A_BOLD);
    wprintw(self->window, " h ");
    wattroff(self->window, A_BOLD);
    wprintw(self->window, "key for help\n\n");
    wattroff(self->window, COLOR_PAIR(CYAN));

    if (blocklist_view == 1) {
        blocklist_onDraw(self, m, y2, x2);
        return;
    }

    time_t cur_time = get_unix_time();
    struct tm cur_loc_tm = *localtime((const time_t *) &cur_time);

    wattron(self->window, A_BOLD);
    wprintw(self->window, " Online: ");
    wattroff(self->window, A_BOLD);

    wprintw(self->window, "%d/%d \n\n", Friends.num_online, Friends.num_friends);

    if ((y2 - FLIST_OFST) <= 0) {
        return;
    }

    uint32_t selected_num = 0;

    /* Determine which portion of friendlist to draw based on current position */
    pthread_mutex_lock(&Winthread.lock);
    int page = Friends.num_selected / (y2 - FLIST_OFST);
    pthread_mutex_unlock(&Winthread.lock);

    int start = (y2 - FLIST_OFST) * page;
    int end = y2 - FLIST_OFST + start;

    pthread_mutex_lock(&Winthread.lock);
    size_t num_friends = Friends.num_friends;
    pthread_mutex_unlock(&Winthread.lock);

    int i;

    for (i = start; i < num_friends && i < end; ++i) {
        pthread_mutex_lock(&Winthread.lock);
        uint32_t f = Friends.index[i];
        bool is_active = Friends.list[f].active;
        int num_selected = Friends.num_selected;
        pthread_mutex_unlock(&Winthread.lock);

        bool f_selected = false;

        if (is_active) {
            if (i == num_selected) {
                wattron(self->window, A_BOLD);
                wprintw(self->window, " > ");
                wattroff(self->window, A_BOLD);
                selected_num = f;
                f_selected = true;
            } else {
                wprintw(self->window, "   ");
            }

            pthread_mutex_lock(&Winthread.lock);
            Tox_Connection connection_status = Friends.list[f].connection_status;
            Tox_User_Status status = Friends.list[f].status;
            pthread_mutex_unlock(&Winthread.lock);

            if (connection_status != TOX_CONNECTION_NONE) {
                int colour = MAGENTA;

                switch (status) {
                    case TOX_USER_STATUS_NONE:
                        colour = GREEN;
                        break;

                    case TOX_USER_STATUS_AWAY:
                        colour = YELLOW;
                        break;

                    case TOX_USER_STATUS_BUSY:
                        colour = RED;
                        break;
                }

                wattron(self->window, COLOR_PAIR(colour) | A_BOLD);
                wprintw(self->window, "%s ", ONLINE_CHAR);
                wattroff(self->window, COLOR_PAIR(colour) | A_BOLD);

                if (f_selected) {
                    wattron(self->window, COLOR_PAIR(BLUE));
                }

                wattron(self->window, A_BOLD);
                pthread_mutex_lock(&Winthread.lock);
                wprintw(self->window, "%s", Friends.list[f].name);
                pthread_mutex_unlock(&Winthread.lock);
                wattroff(self->window, A_BOLD);

                if (f_selected) {
                    wattroff(self->window, COLOR_PAIR(BLUE));
                }

                /* Reset Friends.list[f].statusmsg on window resize */
                if (fix_statuses) {
                    char statusmsg[TOX_MAX_STATUS_MESSAGE_LENGTH];

                    pthread_mutex_lock(&Winthread.lock);
                    tox_friend_get_status_message(m, Friends.list[f].num, (uint8_t *) statusmsg, NULL);
                    size_t s_len = tox_friend_get_status_message_size(m, Friends.list[f].num, NULL);
                    pthread_mutex_unlock(&Winthread.lock);

                    statusmsg[s_len] = '\0';

                    filter_str(statusmsg, s_len);

                    pthread_mutex_lock(&Winthread.lock);
                    snprintf(Friends.list[f].statusmsg, sizeof(Friends.list[f].statusmsg), "%s", statusmsg);
                    Friends.list[f].statusmsg_len = strlen(Friends.list[f].statusmsg);
                    pthread_mutex_unlock(&Winthread.lock);
                }

                /* Truncate note if it doesn't fit on one line */
                size_t maxlen = x2 - getcurx(self->window) - 2;

                pthread_mutex_lock(&Winthread.lock);

                if (Friends.list[f].statusmsg_len > maxlen) {
                    Friends.list[f].statusmsg[maxlen - 3] = '\0';
                    strcat(Friends.list[f].statusmsg, "...");
                    Friends.list[f].statusmsg[maxlen] = '\0';
                    Friends.list[f].statusmsg_len = maxlen;
                }

                if (Friends.list[f].statusmsg_len > 0) {
                    wprintw(self->window, " %s", Friends.list[f].statusmsg);
                }

                pthread_mutex_unlock(&Winthread.lock);

                wprintw(self->window, "\n");
            } else {
                wprintw(self->window, "%s ", OFFLINE_CHAR);

                if (f_selected) {
                    wattron(self->window, COLOR_PAIR(BLUE));
                }

                wattron(self->window, A_BOLD);
                pthread_mutex_lock(&Winthread.lock);
                wprintw(self->window, "%s", Friends.list[f].name);
                pthread_mutex_unlock(&Winthread.lock);
                wattroff(self->window, A_BOLD);

                if (f_selected) {
                    wattroff(self->window, COLOR_PAIR(BLUE));
                }

                pthread_mutex_lock(&Winthread.lock);
                time_t last_seen = Friends.list[f].last_online.last_on;
                pthread_mutex_unlock(&Winthread.lock);

                if (last_seen != 0) {
                    pthread_mutex_lock(&Winthread.lock);

                    int day_dist = (
                                       cur_loc_tm.tm_yday - Friends.list[f].last_online.tm.tm_yday
                                       + ((cur_loc_tm.tm_year - Friends.list[f].last_online.tm.tm_year) * 365)
                                   );
                    const char *hourmin = Friends.list[f].last_online.hour_min_str;

                    pthread_mutex_unlock(&Winthread.lock);

                    switch (day_dist) {
                        case 0:
                            wprintw(self->window, " Last seen: Today %s\n", hourmin);
                            break;

                        case 1:
                            wprintw(self->window, " Last seen: Yesterday %s\n", hourmin);
                            break;

                        default:
                            wprintw(self->window, " Last seen: %d days ago\n", day_dist);
                            break;
                    }
                } else {
                    wprintw(self->window, " Last seen: Never\n");
                }
            }
        }
    }

    self->x = x2;

    if (num_friends) {
        wmove(self->window, y2 - 1, 1);

        wattron(self->window, A_BOLD);
        wprintw(self->window, "Key: ");
        wattroff(self->window, A_BOLD);

        int i;

        for (i = 0; i < TOX_PUBLIC_KEY_SIZE; ++i) {
            wprintw(self->window, "%02X", Friends.list[selected_num].pub_key[i] & 0xff);
        }
    }

    wnoutrefresh(self->window);
    draw_del_popup();

    if (self->help->active) {
        help_onDraw(self);
    }
}
Ejemplo n.º 7
0
int removeuser(void)
{
	
	
	/* Declarations */
	
	WINDOW *rmudlg; /* Prompt Username Window */
	

	rmudlg = newwin(6,61,6,10); /* User name input dialog */
	box(rmudlg, ACS_VLINE, ACS_HLINE);
	wattron(rmudlg, A_UNDERLINE);
	mvwprintw(rmudlg, 1, 20, "Remove user from system");
	wattroff(rmudlg, A_UNDERLINE);
	
	
	
	echo();    /* Turns on Echo to see the text typed */
	/* Username Prompt */
	mvwprintw(rmudlg, 3, 1,  "Please type in username to remove:");
	mvwprintw(rmudlg, 3, 37, "[______________]");
	wrefresh(rmudlg);

	
	
	/* Show a highlighted Field */
	wattron(rmudlg, A_REVERSE);
	mvwprintw(rmudlg, 3, 37, "[______________]");
	wrefresh(rmudlg);
	mvwgetnstr(rmudlg, 3,38, loginname, 15);
	wattroff(rmudlg, A_REVERSE);
	noecho(); /* Removes Echo */
	

	werase(rmudlg);	
	
	while(1)
	{
		rmudlg = newwin(10,61,6,10);
		box(rmudlg, ACS_VLINE, ACS_HLINE);
		wattron(rmudlg, A_UNDERLINE);
		mvwprintw(rmudlg, 1, 20, "Are you sure");
		wattroff(rmudlg, A_UNDERLINE);
		mvwprintw(rmudlg, 3, 7,  "Are you sure you want to delete");
		mvwprintw(rmudlg, 4, 7, "user %s from the system", loginname);
		wattron(rmudlg,A_BOLD);
		mvwprintw(rmudlg, 6, 7, "Y=Yes	 N=No 	F10=Cancel");
		wattroff(rmudlg,A_BOLD);
		wrefresh(rmudlg);
		
		key = getch();
		switch(key)
		{
			case KEY_F(10):
			return 0;
			break;
			
			case 'n':
			return 0;
			break;
			
			case 'N':
			return 0;
			break;
			
			case 'y':
			delUser();
			return 0;
			break;
			
			case 'Y':
			delUser();
			return 0;
			break;
					
			
		}
	};
		
	
	return 0;
}
Ejemplo n.º 8
0
void construction_menu()
{
    static bool hide_unconstructable = false;
    // only display constructions the player can theoretically perform
    std::vector<std::string> available;
    std::map<std::string, std::vector<std::string>> cat_available;
    load_available_constructions( available, cat_available, hide_unconstructable );

    if( available.empty() ) {
        popup( _( "You can not construct anything here." ) );
        return;
    }

    int w_height = TERMY;
    if( ( int )available.size() + 2 < w_height ) {
        w_height = available.size() + 2;
    }
    if( w_height < FULL_SCREEN_HEIGHT ) {
        w_height = FULL_SCREEN_HEIGHT;
    }

    const int w_width = std::max( FULL_SCREEN_WIDTH, TERMX * 2 / 3);
    const int w_y0 = ( TERMY > w_height ) ? ( TERMY - w_height ) / 2 : 0;
    const int w_x0 = ( TERMX > w_width ) ? ( TERMX - w_width ) / 2 : 0;
    WINDOW_PTR w_con_ptr {newwin( w_height, w_width, w_y0, w_x0 )};
    WINDOW *const w_con = w_con_ptr.get();

    const int w_list_width = int( .375 * w_width );
    const int w_list_height = w_height - 4;
    const int w_list_x0 = 1;
    WINDOW_PTR w_list_ptr {newwin( w_list_height, w_list_width, w_y0 + 3, w_x0 + w_list_x0 )};
    WINDOW *const w_list = w_list_ptr.get();

    draw_grid( w_con, w_list_width + w_list_x0 );

    //tabcount needs to be increased to add more categories
    int tabcount = 10;
    std::string construct_cat[] = {_( "All" ), _( "Constructions" ), _( "Furniture" ),
                                   _( "Digging and Mining" ), _( "Repairing" ),
                                   _( "Reinforcing" ), _( "Decorative" ),
                                   _( "Farming and Woodcutting" ), _( "Others" ),
                                   _( "Filter" )
                                  };

    bool update_info = true;
    bool update_cat = true;
    bool isnew = true;
    int tabindex = 0;
    int select = 0;
    int offset = 0;
    bool exit = false;
    std::string category_name = "";
    std::vector<std::string> constructs;
    //storage for the color text so it can be scrolled
    std::vector< std::vector < std::string > > construct_buffers;
    std::vector<std::string> full_construct_buffer;
    std::vector<int> construct_buffer_breakpoints;
    int total_project_breakpoints = 0;
    int current_construct_breakpoint = 0;
    bool previous_hide_unconstructable = false;
    //track the cursor to determine when to refresh the list of construction recipes
    int previous_tabindex = -1;
    int previous_select = -1;

    const inventory &total_inv = g->u.crafting_inventory();

    input_context ctxt( "CONSTRUCTION" );
    ctxt.register_action( "UP", _( "Move cursor up" ) );
    ctxt.register_action( "DOWN", _( "Move cursor down" ) );
    ctxt.register_action( "RIGHT", _( "Move tab right" ) );
    ctxt.register_action( "LEFT", _( "Move tab left" ) );
    ctxt.register_action( "PAGE_UP" );
    ctxt.register_action( "PAGE_DOWN" );
    ctxt.register_action( "CONFIRM" );
    ctxt.register_action( "TOGGLE_UNAVAILABLE_CONSTRUCTIONS" );
    ctxt.register_action( "QUIT" );
    ctxt.register_action( "HELP_KEYBINDINGS" );
    ctxt.register_action( "FILTER" );

    std::string filter;
    int previous_index = 0;
    do {
        if( update_cat ) {
            update_cat = false;
            switch( tabindex ) {
                case 0:
                    category_name = "ALL";
                    break;
                case 1:
                    category_name = "CONSTRUCT";
                    break;
                case 2:
                    category_name = "FURN";
                    break;
                case 3:
                    category_name = "DIG";
                    break;
                case 4:
                    category_name = "REPAIR";
                    break;
                case 5:
                    category_name = "REINFORCE";
                    break;
                case 6:
                    category_name = "DECORATE";
                    break;
                case 7:
                    category_name = "FARM_WOOD";
                    break;
                case 8:
                    category_name = "OTHER";
                    break;
                case 9:
                    category_name = "FILTER";
                    break;
            }

            if( category_name == "ALL" ) {
                constructs = available;
                previous_index = tabindex;
            } else if( category_name == "FILTER" ) {
                constructs.clear();
                std::copy_if( available.begin(), available.end(),
                    std::back_inserter( constructs ),
                    [&](const std::string &a){
                        return lcmatch(a, filter);
                    } );
            } else {
                constructs = cat_available[category_name];
                previous_index = tabindex;
            }
            if( isnew ){
                if( !uistate.last_construction.empty() ){
                    select = std::distance(constructs.begin(),
                                            std::find( constructs.begin(),
                                                        constructs.end(),
                                                        uistate.last_construction ));
                }
                filter = uistate.construction_filter;
            }
        }
        // Erase existing tab selection & list of constructions
        mvwhline( w_con, 1, 1, ' ', w_list_width );
        werase( w_list );
        // Print new tab listing
        mvwprintz( w_con, 1, 1, c_yellow, "<< %s >>", construct_cat[tabindex].c_str() );
        // Determine where in the master list to start printing
        calcStartPos( offset, select, w_list_height, constructs.size() );
        // Print the constructions between offset and max (or how many will fit)
        for( size_t i = 0; ( int )i < w_list_height && ( i + offset ) < constructs.size(); i++ ) {
            int current = i + offset;
            std::string con_name = constructs[current];
            bool highlight = ( current == select );

            trim_and_print( w_list, i, 0, w_list_width,
                            construction_color( con_name, highlight ), "%s",
                            con_name.c_str() );
        }

        if( update_info ) {
            update_info = false;
            // Clear out lines for tools & materials
            const int pos_x = w_list_width + w_list_x0 + 2;
            const int available_window_width = w_width - pos_x - 1;
            for( int i = 1; i < w_height - 1; i++ ) {
                mvwhline( w_con, i, pos_x, ' ', available_window_width );
            }

            nc_color color_stage = c_white;
            std::vector<std::string> notes;
            notes.push_back( string_format( _( "Press %s or %s to tab." ),
                             ctxt.get_desc( "LEFT" ).c_str(), ctxt.get_desc( "RIGHT" ).c_str() ) );
            notes.push_back( string_format( _( "Press %s to search." ),
                             ctxt.get_desc( "FILTER" ).c_str() ) );
            notes.push_back( string_format( _( "Press %s to toggle unavailable constructions." ),
                            ctxt.get_desc( "TOGGLE_UNAVAILABLE_CONSTRUCTIONS" ).c_str() ) );
            notes.push_back( string_format( _( "Press %s to view and edit key-bindings." ),
                            ctxt.get_desc( "HELP_KEYBINDINGS" ).c_str() ) );

            //leave room for top and bottom UI text
            const int available_buffer_height = w_height - 3 - 3 - (int)notes.size();

            // print the hotkeys regardless of if there are constructions
            for( size_t i = 0; i < notes.size(); ++i ) {
                trim_and_print( w_con, w_height - 1 - (int)notes.size() + (int)i, pos_x,
                                available_window_width, c_white, "%s", notes[i].c_str() );
            }

            if( !constructs.empty() ) {
                if( select >= (int) constructs.size() ){
                    select = 0;
                }
                std::string current_desc = constructs[select];
                // Print construction name
                trim_and_print( w_con, 1, pos_x, available_window_width, c_white,
                                "%s", current_desc.c_str() );

                //only reconstruct the project list when moving away from the current item, or when changing the display mode
                if( previous_select != select || previous_tabindex != tabindex ||
                    previous_hide_unconstructable != hide_unconstructable ) {
                    previous_select = select;
                    previous_tabindex = tabindex;
                    previous_hide_unconstructable = hide_unconstructable;

                    //construct the project list buffer

                    // Print stages and their requirement.
                    std::vector<construction *> options = constructions_by_desc( current_desc );

                    construct_buffers.clear();
                    total_project_breakpoints = 0;
                    current_construct_breakpoint = 0;
                    construct_buffer_breakpoints.clear();
                    full_construct_buffer.clear();
                    int stage_counter = 0;
                    for( std::vector<construction *>::iterator it = options.begin();
                         it != options.end(); ++it ) {
                        stage_counter++;
                        construction *current_con = *it;
                        if( hide_unconstructable && !can_construct( *current_con ) ) {
                            continue;
                        }
                        // Update the cached availability of components and tools in the requirement object
                        current_con->requirements->can_make_with_inventory( total_inv );

                        std::vector<std::string> current_buffer;
                        std::ostringstream current_line;

                        // display result only if more than one step.
                        // Assume single stage constructions should be clear
                        // in their description what their result is.
                        if( current_con->post_terrain != "" && options.size() > 1 ) {
                            //also print out stage number when multiple stages are available
                            current_line << _( "Stage #" ) << stage_counter;
                            current_buffer.push_back( current_line.str() );
                            current_line.str( "" );

                            std::string result_string;
                            if( current_con->post_is_furniture ) {
                                result_string = furn_str_id( current_con->post_terrain ).obj().name;
                            } else {
                                result_string = ter_str_id( current_con->post_terrain ).obj().name;
                            }
                            current_line << "<color_" << string_from_color( color_stage ) << ">" << string_format(
                                             _( "Result: %s" ), result_string.c_str() ) << "</color>";
                            std::vector<std::string> folded_result_string = foldstring( current_line.str(),
                                    available_window_width );
                            current_buffer.insert( current_buffer.end(), folded_result_string.begin(),
                                                   folded_result_string.end() );
                        }

                        current_line.str( "" );
                        // display required skill and difficulty
                        int pskill = g->u.get_skill_level( current_con->skill );
                        int diff = ( current_con->difficulty > 0 ) ? current_con->difficulty : 0;

                        current_line << "<color_" << string_from_color( ( pskill >= diff ? c_white : c_red ) ) << ">" <<
                                     string_format( _( "Skill Req: %d (%s)" ), diff,
                                                    current_con->skill.obj().name().c_str() ) << "</color>";
                        current_buffer.push_back( current_line.str() );
                        // TODO: Textify pre_flags to provide a bit more information.
                        // Example: First step of dig pit could say something about
                        // requiring diggable ground.
                        current_line.str( "" );
                        if( current_con->pre_terrain != "" ) {
                            std::string require_string;
                            if( current_con->pre_is_furniture ) {
                                require_string = furn_str_id( current_con->pre_terrain ).obj().name;
                            } else {
                                require_string = ter_str_id( current_con->pre_terrain ).obj().name;
                            }
                            current_line << "<color_" << string_from_color( color_stage ) << ">" << string_format(
                                             _( "Requires: %s" ), require_string.c_str() ) << "</color>";
                            std::vector<std::string> folded_result_string = foldstring( current_line.str(),
                                    available_window_width );
                            current_buffer.insert( current_buffer.end(), folded_result_string.begin(),
                                                   folded_result_string.end() );
                        }
                        // get pre-folded versions of the rest of the construction project to be displayed later

                        // get time needed
                        std::vector<std::string> folded_time = current_con->get_folded_time_string(
                                available_window_width );
                        current_buffer.insert( current_buffer.end(), folded_time.begin(), folded_time.end() );

                        std::vector<std::string> folded_tools = current_con->requirements->get_folded_tools_list(
                                available_window_width, color_stage, total_inv );
                        current_buffer.insert( current_buffer.end(), folded_tools.begin(), folded_tools.end() );

                        std::vector<std::string> folded_components = current_con->requirements->get_folded_components_list(
                                    available_window_width, color_stage, total_inv );
                        current_buffer.insert( current_buffer.end(), folded_components.begin(), folded_components.end() );

                        construct_buffers.push_back( current_buffer );
                    }

                    //determine where the printing starts for each project, so it can be scrolled to those points
                    size_t current_buffer_location = 0;
                    for( size_t i = 0; i < construct_buffers.size(); i++ ) {
                        construct_buffer_breakpoints.push_back( static_cast<int>( current_buffer_location ) );
                        full_construct_buffer.insert( full_construct_buffer.end(), construct_buffers[i].begin(),
                                                      construct_buffers[i].end() );

                        //handle text too large for one screen
                        if( construct_buffers[i].size() > static_cast<size_t>( available_buffer_height ) ) {
                            construct_buffer_breakpoints.push_back( static_cast<int>( current_buffer_location +
                                                                    static_cast<size_t>( available_buffer_height ) ) );
                        }
                        current_buffer_location += construct_buffers[i].size();
                        if( i < construct_buffers.size() - 1 ) {
                            full_construct_buffer.push_back( std::string( "" ) );
                            current_buffer_location++;
                        }
                    }
                    total_project_breakpoints = static_cast<int>( construct_buffer_breakpoints.size() );
                }
                if( current_construct_breakpoint > 0 ) {
                    // Print previous stage indicator if breakpoint is past the beginning
                    trim_and_print( w_con, 2, pos_x, available_window_width, c_white,
                                    _( "Press %s to show previous stage(s)." ),
                                    ctxt.get_desc( "PAGE_UP" ).c_str() );
                }
                if( static_cast<size_t>( construct_buffer_breakpoints[current_construct_breakpoint] +
                                         available_buffer_height ) < full_construct_buffer.size() ) {
                    // Print next stage indicator if more breakpoints are remaining after screen height
                    trim_and_print( w_con, w_height - 2 - (int)notes.size(), pos_x, available_window_width,
                                    c_white, _( "Press %s to show next stage(s)." ),
                                    ctxt.get_desc( "PAGE_DOWN" ).c_str() );
                }
                // Leave room for above/below indicators
                int ypos = 3;
                nc_color stored_color = color_stage;
                for( size_t i = static_cast<size_t>( construct_buffer_breakpoints[current_construct_breakpoint] );
                     i < full_construct_buffer.size(); i++ ) {
                    //the value of 3 is from leaving room at the top of window
                    if( ypos > available_buffer_height + 3 ) {
                        break;
                    }
                    print_colored_text( w_con, ypos++, ( w_list_width + w_list_x0 + 2 ), stored_color, color_stage, full_construct_buffer[i] );
                }
            }
        } // Finished updating

        draw_scrollbar( w_con, select, w_list_height, constructs.size(), 3 );
        wrefresh( w_con );
        wrefresh( w_list );

        const std::string action = ctxt.handle_input();
        if( action == "FILTER" ){
            filter = string_input_popup( _( "Search" ), 50, filter, "", _( "Filter" ), 100, false );
            if( !filter.empty() ){
                update_info = true;
                update_cat = true;
                tabindex = 9;
                select = 0;
            }else if( previous_index !=9 ){
                tabindex = previous_index;
                update_info = true;
                update_cat = true;
                select = 0;
            }
            uistate.construction_filter = filter;
        } else if( action == "DOWN" ) {
            update_info = true;
            if( select < ( int )constructs.size() - 1 ) {
                select++;
            } else {
                select = 0;
            }
        } else if( action == "UP" ) {
            update_info = true;
            if( select > 0 ) {
                select--;
            } else {
                select = constructs.size() - 1;
            }
        } else if( action == "LEFT" ) {
            update_info = true;
            update_cat = true;
            select = 0;
            tabindex--;
            if( tabindex < 0 ) {
                tabindex = tabcount - 1;
            }
        } else if( action == "RIGHT" ) {
            update_info = true;
            update_cat = true;
            select = 0;
            tabindex = ( tabindex + 1 ) % tabcount;
        } else if( action == "PAGE_UP" ) {
            update_info = true;
            if( current_construct_breakpoint > 0 ) {
                current_construct_breakpoint--;
            }
            if( current_construct_breakpoint < 0 ) {
                current_construct_breakpoint = 0;
            }
        } else if( action == "PAGE_DOWN" ) {
            update_info = true;
            if( current_construct_breakpoint < total_project_breakpoints - 1 ) {
                current_construct_breakpoint++;
            }
            if( current_construct_breakpoint >= total_project_breakpoints ) {
                current_construct_breakpoint = total_project_breakpoints - 1;
            }
        } else if( action == "QUIT" ) {
            exit = true;
        } else if( action == "HELP_KEYBINDINGS" ) {
            draw_grid( w_con, w_list_width + w_list_x0 );
        } else if( action == "TOGGLE_UNAVAILABLE_CONSTRUCTIONS" ) {
            update_info = true;
            update_cat = true;
            hide_unconstructable = !hide_unconstructable;
            select = 0;
            offset = 0;
            load_available_constructions( available, cat_available, hide_unconstructable );
        } else if( action == "CONFIRM" ) {
            if( constructs.empty() || select >= (int) constructs.size() ){
                continue;// Nothing to be done here
            }
            if( player_can_build( g->u, total_inv, constructs[select] ) ) {
                place_construction( constructs[select] );
                uistate.last_construction = constructs[select];
                exit = true;
            } else {
                popup( _( "You can't build that!" ) );
                draw_grid( w_con, w_list_width + w_list_x0 );
                update_info = true;
            }
        }
    } while( !exit );

    w_list_ptr.reset();
    w_con_ptr.reset();
    g->refresh_all();
}
Ejemplo n.º 9
0
/* Launch a dialog that asks user for a string (e.g name) */
char *getstring(char *question)
{
   int c, width, apos=0;
   WINDOW *dialog;
   char *answer;

   /* Cancel alarm */
   alarm(0);
   game_pause(1);
   draw_grid();
   scrl_open=1;

   answer = malloc(21);

redraw:
   width = clamp(col*0.7, col*0.7, 60);
   dialog = newwin(8, width, row * 0.3, col*0.5 - width/2);

   /* Draw dialog */
   wbkgd(dialog, COLOR_PAIR(C_DIALOG));
   box(dialog, 0, 0);
   mvwaddstr(dialog, 2, width/2 - (strlen(question) / 2), question);

   /* Draw input box */
   mvwhline(dialog, 4, 3, ACS_HLINE, width-7);
   mvwhline(dialog, 6, 3, ACS_HLINE, width-7);
   mvwaddch(dialog, 4, 3, ACS_ULCORNER);
   mvwaddch(dialog, 6, 3, ACS_LLCORNER);
   mvwaddch(dialog, 5, 3, ACS_VLINE);
   mvwaddch(dialog, 5, width-4, ACS_VLINE);
   mvwaddch(dialog, 4, width-4, ACS_URCORNER);
   mvwaddch(dialog, 6, width-4, ACS_LRCORNER);

   if (apos > 0) mvwaddstr(dialog, 5, 4, answer);
   wmove(dialog, 5, 4+apos);


   /* Draw over top of everything */
   overwrite(dialog, stats);
   wrefresh(dialog);

   /* Handle input */
   while ((c = getkey())) {
      switch (c) {
         case KEY_RESIZE:
            getmaxyx(stdscr, row, col);
            draw_all();
            curs_set(1);
            goto redraw;
         /* Enter pressed */
         case 10:
            werase(dialog);
            delwin(dialog);
            game_pause(0);
            catch_alarm(0);
            fbar_time=0;
            scrl_open=0;
            return answer;
         case KEY_BACKSPACE:
         case 127: /* Katch the Konsole backspace */
         case 12:
            if (apos > 0) {
               mvwprintw(dialog, 5, 3+apos, " ");
               answer[--apos] = '\0';
               wmove(dialog, 5, 4+apos);
               wrefresh(dialog);
            }
            break;
         default:
            if ((c >= 'A' && c<= 'Z') 
                  || (c>='a' && c<= 'z')
                  || c==32 || c=='_' 
                  || (c>='1' && c<='9')) {
               if (apos>=20) break;
               answer[apos]=c;
               answer[++apos]='\0';
               mvwaddch(dialog, 5, 3+apos, c);
               wmove(dialog, 5, 4+apos);
               wrefresh(dialog);
            }
            break;
      }
   }
   scrl_open=0;
   return NULL;
}
Ejemplo n.º 10
0
/*
 * Display the list of processes that are tracked, in task bar.
 * This one is called when mode of operation is thread.
 */
static void
print_taskbar_thread(pid_t *pidlist, id_t *tidlist, int list_len,
    int list_index)
{
	const int ITEM_WIDTH = 12;

	int number_item;
	int i;
	int xpos = 0;
	const char *pname = NULL;
	pid_t last_pid = INVALID_PID;


	if (!display_initialized) {
		return;
	}

	number_item = (screen_width - 8) / ITEM_WIDTH;
	i = list_index - (list_index % number_item);

	(void) werase(taskbar);

	if (i != 0) {
		(void) mvwprintw(taskbar, 0, xpos, "<-");
	}

	xpos = 4;

	while (xpos + ITEM_WIDTH <= screen_width && i < list_len) {
		char str[ITEM_WIDTH+1];
		int slen, tlen;

		if (pidlist[i] != last_pid) {
			pname = lt_stat_proc_get_name(pidlist[i]);
			last_pid = pidlist[i];
		}

		/*
		 * Calculate length of thread's ID; use shorter process name
		 * in order to save space on the screen.
		 */
		tlen = snprintf(NULL, 0, "_%d", tidlist[i]);

		if (pname && pname[0]) {
			(void) snprintf(str, sizeof (str) - tlen - 1,
			    "%s", pname);
		} else {
			(void) snprintf(str, sizeof (str) - tlen - 1,
			    "<%d>", pidlist[i]);
		}

		slen = strlen(str);

		(void) snprintf(&str[slen], sizeof (str) - slen,
		    "_%d", tidlist[i]);

		slen += tlen;

		if (slen < ITEM_WIDTH) {
			(void) memset(&str[slen], ' ', ITEM_WIDTH - slen);
		}

		str[sizeof (str) - 1] = '\0';

		if (i == list_index) {
			(void) wattron(taskbar, A_REVERSE);
		}

		(void) mvwprintw(taskbar, 0, xpos, "%s", str);

		if (i == list_index) {
			(void) wattroff(taskbar, A_REVERSE);
		}

		xpos += ITEM_WIDTH;
		i++;
	}

	if (i != list_len) {
		(void) mvwprintw(taskbar, 0, screen_width - 2, "->");
	}

	(void) wrefresh(taskbar);
}
Ejemplo n.º 11
0
/*
 * The event loop for display. It displays data on screen and handles hotkey
 * presses.
 *
 * Parameter :
 *		duration - returns after 'duration'
 *
 * The function also returns if user presses 'q', 'Ctrl+C' or 'r'.
 *
 * Return value:
 *		0 - main() exits
 *		1 - main() calls it again
 */
int
lt_display_loop(int duration)
{
	uint64_t start;
	int remaining;
	struct timeval timeout;
	fd_set read_fd;
	int need_refresh = TRUE;
	pid_t *plist = NULL;
	id_t *tlist = NULL;
	int list_len = 0;
	int list_index = 0;
	int retval = 1;
	int next_snap;
	int gpipe;

	start = lt_millisecond();
	gpipe = lt_gpipe_readfd();

	if (!show_help) {
		print_hint(NULL);
		print_sysglobal();
	}

	get_plist(&plist, &tlist, &list_len, &list_index);

	for (;;) {
		if (need_refresh && !show_help) {
			if (list_len != 0) {
				if (!thread_mode) {
					print_taskbar_process(plist, list_len,
					    list_index);
					print_process(plist[list_index]);
				} else {
					print_taskbar_thread(plist, tlist,
					    list_len, list_index);
					print_thread(plist[list_index],
					    tlist[list_index]);
				}
			} else {
				print_empty_process_bar();
			}
		}

		need_refresh = TRUE;	/* Usually we need refresh. */
		remaining = duration - (int)(lt_millisecond() - start);

		if (remaining <= 0) {
			break;
		}

		/* Embedded dtrace snap action here. */
		next_snap = lt_dtrace_work(0);

		if (next_snap == 0) {
			/*
			 * Just did a snap, check time for the next one.
			 */
			next_snap = lt_dtrace_work(0);
		}

		if (next_snap > 0 && remaining > next_snap) {
			remaining = next_snap;
		}

		timeout.tv_sec = remaining / 1000;
		timeout.tv_usec = (remaining % 1000) * 1000;

		FD_ZERO(&read_fd);
		FD_SET(0, &read_fd);
		FD_SET(gpipe, &read_fd);

		/* Wait for keyboard input, or signal from gpipe */
		if (select(gpipe + 1, &read_fd, NULL, NULL, &timeout) > 0) {
			int k = 0;

			if (FD_ISSET(gpipe, &read_fd)) {
				/* Data from pipe has priority */
				char ch;
				(void) read(gpipe, &ch, 1);
				k = ch; /* Need this for big-endianness */
			} else {
				k = getch();
			}

			/*
			 * Check if we need to update the hint line whenever we
			 * get a chance.
			 * NOTE: current implementation depends on
			 * g_config.lt_cfg_snap_interval, but it's OK because it
			 * doesn't have to be precise.
			 */
			print_hint(NULL);
			/*
			 * If help is on display right now, and a key press
			 * happens, we need to clear the help and continue.
			 */
			if (show_help) {
				(void) werase(stdscr);
				(void) refresh();
				print_title();
				print_sysglobal();
				show_help = FALSE;
				/* Drop this key and continue */
				continue;
			}

			switch (k) {
			case 'Q':
			case 'q':
				retval = 0;
				goto quit;
			case 'R':
			case 'r':
				lt_display_deinit();
				lt_display_init();
				goto quit;
			case 'H':
			case 'h':
				show_help = TRUE;
				(void) werase(stdscr);
				(void) refresh();
				print_help();
				break;
			case ',':
			case '<':
			case KEY_LEFT:
				--list_index;

				if (list_index < 0) {
					list_index = 0;
				}

				break;
			case '.':
			case '>':
			case KEY_RIGHT:
				++list_index;

				if (list_index >= list_len) {
					list_index = list_len - 1;
				}

				break;
			case 'a':
			case 'A':
				sort_type = LT_SORT_AVG;
				print_sysglobal();
				break;
			case 'p':
			case 'P':
				sort_type = LT_SORT_TOTAL;
				print_sysglobal();
				break;
			case 'm':
			case 'M':
				sort_type = LT_SORT_MAX;
				print_sysglobal();
				break;
			case 'c':
			case 'C':
				sort_type = LT_SORT_COUNT;
				print_sysglobal();
				break;
			case 't':
			case 'T':
				if (plist != NULL) {
					selected_pid = plist[list_index];
				}

				selected_tid = INVALID_TID;
				thread_mode = !thread_mode;
				get_plist(&plist, &tlist,
				    &list_len, &list_index);
				break;
			case '1':
			case '!':
				current_list_type = LT_LIST_CAUSE;
				print_sysglobal();
				break;
			case '2':
			case '@':
				if (g_config.lt_cfg_low_overhead_mode) {
					lt_display_error("Switching mode is "
					    "not available for '-f low'.");
				} else {
					current_list_type = LT_LIST_SPECIALS;
					print_sysglobal();
				}

				break;
			case '3':
			case '#':
				if (g_config.lt_cfg_trace_syncobj) {
					current_list_type = LT_LIST_SOBJ;
					print_sysglobal();
				} else if (g_config.lt_cfg_low_overhead_mode) {
					lt_display_error("Switching mode is "
					    "not available for '-f low'.");
				} else {
					lt_display_error("Tracing "
					    "synchronization objects is "
					    "disabled.");
				}

				break;
			default:
				/* Wake up for nothing; no refresh is needed */
				need_refresh = FALSE;
				break;
			}
		} else {
			need_refresh = FALSE;
		}
	}

quit:
	if (plist != NULL) {
		selected_pid = plist[list_index];
	}

	if (tlist != NULL) {
		selected_tid = tlist[list_index];
	}

	lt_stat_proc_list_free(plist, tlist);

	return (retval);
}
Ejemplo n.º 12
0
/*
 * Display the list of processes that are tracked, in task bar.
 * This one is called when mode of operation is process.
 */
static void
print_taskbar_process(pid_t *pidlist, int pidlist_len, int pidlist_index)
{
	const int ITEM_WIDTH = 8;

	int number_item;
	int i;
	int xpos = 0;

	if (!display_initialized) {
		return;
	}

	number_item = (screen_width / ITEM_WIDTH) - 1;
	i = pidlist_index - (pidlist_index % number_item);

	(void) werase(taskbar);

	if (i != 0) {
		(void) mvwprintw(taskbar, 0, xpos, "<-");
	}

	xpos = ITEM_WIDTH / 2;

	while (xpos + ITEM_WIDTH <= screen_width && i < pidlist_len) {
		char str[ITEM_WIDTH+1];
		int slen;
		const char *pname = lt_stat_proc_get_name(pidlist[i]);

		if (pname && pname[0]) {
			(void) snprintf(str, sizeof (str) - 1, "%s", pname);
		} else {
			(void) snprintf(str, sizeof (str) - 1,
			    "<%d>", pidlist[i]);
		}

		slen = strlen(str);

		if (slen < ITEM_WIDTH) {
			(void) memset(&str[slen], ' ', ITEM_WIDTH - slen);
		}

		str[sizeof (str) - 1] = '\0';

		if (i == pidlist_index) {
			(void) wattron(taskbar, A_REVERSE);
		}

		(void) mvwprintw(taskbar, 0, xpos, "%s", str);

		if (i == pidlist_index) {
			(void) wattroff(taskbar, A_REVERSE);
		}

		xpos += ITEM_WIDTH;
		i++;
	}

	if (i != pidlist_len) {
		(void) mvwprintw(taskbar, 0, screen_width - 2, "->");
	}

	(void) wrefresh(taskbar);
}
Ejemplo n.º 13
0
void faction_manager::display() const
{
    std::vector<const faction *> valfac; // Factions that we know of.
    for( const faction &elem : factions ) {
        if( elem.known_by_u ) {
            valfac.push_back( &elem );
        }
    }
    if( valfac.empty() ) { // We don't know of any factions!
        popup( _( "You don't know of any factions.  Press Spacebar..." ) );
        return;
    }

    catacurses::window w_list = catacurses::newwin( FULL_SCREEN_HEIGHT, FULL_SCREEN_WIDTH,
                                ( ( TERMY > FULL_SCREEN_HEIGHT ) ? ( TERMY - FULL_SCREEN_HEIGHT ) / 2 : 0 ),
                                ( TERMX > FULL_SCREEN_WIDTH ) ? ( TERMX - FULL_SCREEN_WIDTH ) / 2 : 0 );
    catacurses::window w_info = catacurses::newwin( FULL_SCREEN_HEIGHT - 2,
                                FULL_SCREEN_WIDTH - 1 - MAX_FAC_NAME_SIZE,
                                1 + ( ( TERMY > FULL_SCREEN_HEIGHT ) ? ( TERMY - FULL_SCREEN_HEIGHT ) / 2 : 0 ),
                                MAX_FAC_NAME_SIZE + ( ( TERMX > FULL_SCREEN_WIDTH ) ? ( TERMX - FULL_SCREEN_WIDTH ) / 2 : 0 ) );

    const int maxlength = FULL_SCREEN_WIDTH - 1 - MAX_FAC_NAME_SIZE;
    size_t sel = 0;
    bool redraw = true;

    input_context ctxt( "FACTIONS" );
    ctxt.register_action( "UP", _( "Move cursor up" ) );
    ctxt.register_action( "DOWN", _( "Move cursor down" ) );
    ctxt.register_action( "QUIT" );
    ctxt.register_action( "HELP_KEYBINDINGS" );
    while( true ) {
        const faction &cur_frac = *valfac[sel];
        if( redraw ) {
            werase( w_list );
            draw_border( w_list );
            mvwprintz( w_list, 1, 1, c_white, _( "FACTIONS:" ) );
            for( size_t i = 0; i < valfac.size(); i++ ) {
                nc_color col = ( i == sel ? h_white : c_white );
                mvwprintz( w_list, i + 2, 1, col, _( valfac[i]->name.c_str() ) );
            }
            wrefresh( w_list );
            werase( w_info );
            mvwprintz( w_info, 0, 0, c_white, _( "Ranking:           %s" ),
                       fac_ranking_text( cur_frac.likes_u ) );
            mvwprintz( w_info, 1, 0, c_white, _( "Respect:           %s" ),
                       fac_respect_text( cur_frac.respects_u ) );
            mvwprintz( w_info, 2, 0, c_white, _( "Wealth:            %s" ), fac_wealth_text( cur_frac.wealth,
                       cur_frac.size ) );
            mvwprintz( w_info, 3, 0, c_white, _( "Food Supply:       %s" ),
                       fac_food_supply_text( cur_frac.food_supply, cur_frac.size ) );
            mvwprintz( w_info, 4, 0, c_white, _( "Combat Ability:    %s" ),
                       fac_combat_ability_text( cur_frac.combat_ability ) );
            fold_and_print( w_info, 6, 0, maxlength, c_white, cur_frac.describe() );
            wrefresh( w_info );
            redraw = false;
        }
        const std::string action = ctxt.handle_input();
        if( action == "DOWN" ) {
            mvwprintz( w_list, sel + 2, 1, c_white, cur_frac.name );
            sel = ( sel + 1 ) % valfac.size();
            redraw = true;
        } else if( action == "UP" ) {
            mvwprintz( w_list, sel + 2, 1, c_white, cur_frac.name );
            sel = ( sel + valfac.size() - 1 ) % valfac.size();
            redraw = true;
        } else if( action == "HELP_KEYBINDINGS" ) {
            redraw = true;
        } else if( action == "QUIT" ) {
            break;
        } else if( action == "CONFIRM" ) {
            break;
        }
    }
}
Ejemplo n.º 14
0
/*
 * Display some text on somebody's window, processing some control
 * characters while we are at it.
 */
void
display(xwin_t *win, char *text, int size)
{
	int i;
	char cch;

	for (i = 0; i < size; i++) {
		if (*text == '\n' || *text == '\r') {
			waddch(win->x_win, '\n');
			getyx(win->x_win, win->x_line, win->x_col);
			text++;
			continue;
		}
		if (*text == 004 && win == &my_win) {
			/* control-D clears the screen */
			werase(my_win.x_win);
			getyx(my_win.x_win, my_win.x_line, my_win.x_col);
			wrefresh(my_win.x_win);
			werase(his_win.x_win);
			getyx(his_win.x_win, his_win.x_line, his_win.x_col);
			wrefresh(his_win.x_win);
			text++;
			continue;
		}

		/* erase character */
		if (   *text == win->cerase
		    || *text == 010     /* BS */
		    || *text == 0177    /* DEL */
		   ) {
			wmove(win->x_win, win->x_line, max(--win->x_col, 0));
			getyx(win->x_win, win->x_line, win->x_col);
			waddch(win->x_win, ' ');
			wmove(win->x_win, win->x_line, win->x_col);
			getyx(win->x_win, win->x_line, win->x_col);
			text++;
			continue;
		}
		/*
		 * On word erase search backwards until we find
		 * the beginning of a word or the beginning of
		 * the line.
		 */
		if (   *text == win->werase
		    || *text == 027     /* ^W */
		   ) {
			int endcol, xcol, ii, c;

			endcol = win->x_col;
			xcol = endcol - 1;
			while (xcol >= 0) {
				c = readwin(win->x_win, win->x_line, xcol);
				if (c != ' ')
					break;
				xcol--;
			}
			while (xcol >= 0) {
				c = readwin(win->x_win, win->x_line, xcol);
				if (c == ' ')
					break;
				xcol--;
			}
			wmove(win->x_win, win->x_line, xcol + 1);
			for (ii = xcol + 1; ii < endcol; ii++)
				waddch(win->x_win, ' ');
			wmove(win->x_win, win->x_line, xcol + 1);
			getyx(win->x_win, win->x_line, win->x_col);
			text++;
			continue;
		}
		/* line kill */
		if (   *text == win->kill
		    || *text == 025     /* ^U */
		   ) {
			wmove(win->x_win, win->x_line, 0);
			wclrtoeol(win->x_win);
			getyx(win->x_win, win->x_line, win->x_col);
			text++;
			continue;
		}
		if (*text == '\f') {
			if (win == &my_win)
				wrefresh(curscr);
			text++;
			continue;
		}
		if (*text == '\7') {
			write(STDOUT_FILENO, text, 1);
			text++;
			continue;
		}
		if (!isprint((unsigned char)*text) && *text != '\t') {
			waddch(win->x_win, '^');
			getyx(win->x_win, win->x_line, win->x_col);
			cch = (*text & 63) + 64;
			waddch(win->x_win, cch);
		} else
			waddch(win->x_win, (unsigned char)*text);
		getyx(win->x_win, win->x_line, win->x_col);
		text++;
	}
	wrefresh(win->x_win);
}
Ejemplo n.º 15
0
void game::mutation_wish()
{
 WINDOW* w_list = newwin(25, 30, 0,  0);
 WINDOW* w_info = newwin(25, 50, 0, 30);
 int a = 0, shift = 0, result_selected = 0;
 int line;
 char ch = '.';
 bool search = false, found = false;
 std::string pattern;
 std::string info;
 std::vector<int> search_results;
 do {
  werase(w_info);
  werase(w_list);
  mvwprintw(w_list, 0, 0, "Mutate: ");
  if (search) {
   found = false;
   if (ch == '\n') {
    search = false;
    found = true;
    ch = '.';
   } else if (ch == KEY_BACKSPACE || ch == 127) {
    if (pattern.length() > 0)
     pattern.erase(pattern.end() - 1);
   } else if (ch == '>') {
    search = false;
    if (!search_results.empty()) {
     result_selected++;
     if (result_selected > search_results.size())
      result_selected = 0;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > PF_MAX2) {
      a = shift + 23 - PF_MAX2;
      shift = PF_MAX2 - 23;
     }
    }
   } else if (ch == '<') {
    search = false;
    if (!search_results.empty()) {
     result_selected--;
     if (result_selected < 0)
      result_selected = search_results.size() - 1;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > PF_MAX2) {
      a = shift + 23 - PF_MAX2;
      shift = PF_MAX2 - 23;
     }
    }
   } else {
    pattern += ch;
    search_results.clear();
   }

   if (search) {
    for (int i = 0; i < PF_MAX2; i++) {
     if (traits[i].name.find(pattern) != std::string::npos) {
      shift = i;
      a = 0;
      result_selected = 0;
      if (shift + 23 > PF_MAX2) {
       a = shift + 23 - PF_MAX2;
       shift = PF_MAX2 - 23;
      }
      found = true;
      search_results.push_back(i);
     }
    }
    if (search_results.size() > 0) {
     shift = search_results[0];
     a = 0;
    }
   }

  } else {	// Not searching; scroll by keys
   if (ch == 'j') a++;
   if (ch == 'k') a--;
   if (ch == '/') { 
    search = true;
    pattern =  "";
    found = false;
    search_results.clear();
   }
   if (ch == '>' && !search_results.empty()) {
    result_selected++;
    if (result_selected > search_results.size())
     result_selected = 0;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > PF_MAX2) {
     a = shift + 23 - PF_MAX2;
     shift = PF_MAX2 - 23;
    }
   } else if (ch == '<' && !search_results.empty()) {
    result_selected--;
    if (result_selected < 0)
     result_selected = search_results.size() - 1;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > PF_MAX2) {
     a = shift + 23 - PF_MAX2;
     shift = PF_MAX2 - 23;
    }
   }
  }
  if (!search_results.empty())
   mvwprintz(w_list, 0, 11, c_green, "%s               ", pattern.c_str());
  else if (pattern.length() > 0)
   mvwprintz(w_list, 0, 11, c_red, "%s not found!            ",pattern.c_str());
  if (a < 0) {
   a = 0;
   shift--;
   if (shift < 0) shift = 0;
  }
  if (a > 22) {
   a = 22;
   shift++;
   if (shift + 23 > PF_MAX2) shift = PF_MAX2 - 23;
  }
  for (int i = 1; i < 24; i++) {
   nc_color col = c_white;
   if (i == a + 1)
    col = h_white;
   mvwprintz(w_list, i, 0, col, traits[i-1+shift].name.c_str());
  }
  mvwprintw(w_info, 1, 0, mutation_data[a+shift].valid ? "Valid" : "Nonvalid");
  int line2 = 2;
  mvwprintw(w_info, line2, 0, "Prereqs:");
  for (int j = 0; j < mutation_data[a+shift].prereqs.size(); j++) {
   mvwprintw(w_info, line2, 9, traits[ mutation_data[a+shift].prereqs[j] ].name.c_str());
   line2++;
  }
  mvwprintw(w_info, line2, 0, "Cancels:");
  for (int j = 0; j < mutation_data[a+shift].cancels.size(); j++) {
   mvwprintw(w_info, line2, 9, traits[ mutation_data[a+shift].cancels[j] ].name.c_str());
   line2++;
  }
  mvwprintw(w_info, line2, 0, "Becomes:");
  for (int j = 0; j < mutation_data[a+shift].replacements.size(); j++) {
   mvwprintw(w_info, line2, 9, traits[ mutation_data[a+shift].replacements[j] ].name.c_str());
   line2++;
  }
  mvwprintw(w_info, line2, 0, "Add-ons:");
  for (int j = 0; j < mutation_data[a+shift].additions.size(); j++) {
   mvwprintw(w_info, line2, 9, traits[ mutation_data[a+shift].additions[j] ].name.c_str());
   line2++;
  }
  wrefresh(w_info);
  wrefresh(w_list);
  if (search)
   ch = getch();
  else
   ch = input();
 } while (ch != '\n');
 clear();
 if (a+shift == 0)
  u.mutate(this);
 else
  u.mutate_towards(this, pl_flag(a + shift));
 delwin(w_info);
 delwin(w_list);
}
Ejemplo n.º 16
0
/* Launch a dialog that asks OK/Cancel for a question,
 * pausing the game while it waits for input */
bool confirm(char *question)
{
   int c;
   bool status=true;
   WINDOW *confirm;

   /* Cancel alarm */
   alarm(0);
   game_pause(1);
   /* Only redraw the grid if the help isn't open */
   if (!scrl_open) draw_grid();

redraw:
   confirm = newwin(row * 0.4, col * 0.7, row * 0.3, col * 0.15);

   /* Draw dialog */
   wbkgd(confirm, COLOR_PAIR(C_DIALOG));
   box(confirm, 0, 0);
   mvwaddstr(confirm, 0, col * 0.35 - 4, "Confirm");
   mvwaddstr(confirm, 2, col * 0.35 - (strlen(question) / 2), question);

   /* Draw over top of everything */
   overwrite(confirm, stats);
   /* Draw the options */
   ungetch('h');

   /* Handle input */
   while ((c = getkey())) {
      switch (c) {
         case KEY_RESIZE:
            getmaxyx(stdscr, row, col);
            draw_all();
            goto redraw;
         case KEY_LEFT:
         case KEY_RIGHT:
         case 'h':
         case 'l':
         case 'a':
         case 'd':
         case CTRL('f'):
         case CTRL('b'):
            wattrset(confirm, A_REVERSE);	
            if (!status) {
               mvwaddstr(confirm, (row * 0.4) -3, col *0.35 - 9, "   OK   ");
               wattroff(confirm, A_REVERSE);
               mvwaddstr(confirm, (row * 0.4) -3, col *0.35, " Cancel ");
            } else {
               mvwaddstr(confirm, (row * 0.4) -3, col *0.35, " Cancel ");
               wattroff(confirm, A_REVERSE);
               mvwaddstr(confirm, (row * 0.4) -3, col *0.35 - 9, "   OK   ");
            }
            status = !status;
            wrefresh(confirm);
            break;				
         /* Enter pressed */
         case 10:
            werase(confirm);
            delwin(confirm);
            if (!scrl_open) {
               game_pause(0);
            }
            catch_alarm(0);
            fbar_time=0;
            return status;
         default:
            break;
      }
   }
   return 0;
}
Ejemplo n.º 17
0
void game::wish()
{
 WINDOW* w_list = newwin(25, 30, 0,  0);
 WINDOW* w_info = newwin(25, 50, 0, 30);
 int a = 0, shift = 0, result_selected = 0;
 int line;
 char ch = '.';
 bool search = false, found = false;
 std::string pattern;
 std::string info;
 std::vector<int> search_results;
 item tmp;
 tmp.corpse = mtypes[0];
 do {
  werase(w_info);
  werase(w_list);
  mvwprintw(w_list, 0, 0, "Wish for a: ");
  if (search) {
   found = false;
   if (ch == '\n') {
    search = false;
    found = true;
    ch = '.';
   } else if (ch == KEY_BACKSPACE || ch == 127) {
    if (pattern.length() > 0)
     pattern.erase(pattern.end() - 1);
   } else if (ch == '>') {
    search = false;
    if (!search_results.empty()) {
     result_selected++;
     if (result_selected > search_results.size())
      result_selected = 0;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > itypes.size()) {
      a = shift + 23 - itypes.size();
      shift = itypes.size() - 23;
     }
    }
   } else if (ch == '<') {
    search = false;
    if (!search_results.empty()) {
     result_selected--;
     if (result_selected < 0)
      result_selected = search_results.size() - 1;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > itypes.size()) {
      a = shift + 23 - itypes.size();
      shift = itypes.size() - 23;
     }
    }
   } else {
    pattern += ch;
    search_results.clear();
   }

   if (search) {
    for (int i = 0; i < itypes.size(); i++) {
     if (itypes[i]->name.find(pattern) != std::string::npos) {
      shift = i;
      a = 0;
      result_selected = 0;
      if (shift + 23 > itypes.size()) {
       a = shift + 23 - itypes.size();
       shift = itypes.size() - 23;
      }
      found = true;
      search_results.push_back(i);
     }
    }
    if (search_results.size() > 0) {
     shift = search_results[0];
     a = 0;
    }
   }

  } else {	// Not searching; scroll by keys
   if (ch == 'j') a++;
   if (ch == 'k') a--;
   if (ch == '/') { 
    search = true;
    pattern =  "";
    found = false;
    search_results.clear();
   }
   if (ch == '>' && !search_results.empty()) {
    result_selected++;
    if (result_selected > search_results.size())
     result_selected = 0;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > itypes.size()) {
     a = shift + 23 - itypes.size();
     shift = itypes.size() - 23;
    }
   } else if (ch == '<' && !search_results.empty()) {
    result_selected--;
    if (result_selected < 0)
     result_selected = search_results.size() - 1;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > itypes.size()) {
     a = shift + 23 - itypes.size();
     shift = itypes.size() - 23;
    }
   }
  }
  if (!search_results.empty())
   mvwprintz(w_list, 0, 11, c_green, "%s               ", pattern.c_str());
  else if (pattern.length() > 0)
   mvwprintz(w_list, 0, 11, c_red, "%s not found!            ",pattern.c_str());
  if (a < 0) {
   a = 0;
   shift--;
   if (shift < 0) shift = 0;
  }
  if (a > 22) {
   a = 22;
   shift++;
   if (shift + 23 > itypes.size()) shift = itypes.size() - 23;
  }
  for (int i = 1; i < 24 && i-1+shift < itypes.size(); i++) {
   nc_color col = c_white;
   if (i == a + 1)
    col = h_white;
   mvwprintz(w_list, i, 0, col, itypes[i-1+shift]->name.c_str());
   wprintz(w_list, itypes[i-1+shift]->color, "%c%", itypes[i-1+shift]->sym);
  }
  tmp.make(itypes[a + shift]);
  if (tmp.is_tool())
   tmp.charges = dynamic_cast<it_tool*>(tmp.type)->max_charges;
  else if (tmp.is_ammo())
   tmp.charges = 100;
  else
   tmp.charges = -1;
  info = tmp.info(true);
  mvwprintw(w_info, 1, 0, info.c_str());
  wrefresh(w_info);
  wrefresh(w_list);
  if (search)
   ch = getch();
  else
   ch = input();
 } while (ch != '\n');
 clear();
 mvprintw(0, 0, "\nWish granted - %d (%d).", tmp.type->id, itm_antibiotics);
 tmp.invlet = nextinv;
 u.i_add(tmp);
 advance_nextinv();
 getch();
 delwin(w_info);
 delwin(w_list);
}
Ejemplo n.º 18
0
void Nwindow::clear(){
	werase(winptr);
}
Ejemplo n.º 19
0
int selection_box(void **list, char *needs_mark, int nlines, selbox_type_t type, int what_help, char *heading)
{
	NEWWIN *mywin;
	int wlines = min(nlines, (max_y - 1) - 4);
	int total_win_size = wlines + 4;
	int win_width = max(32, max_x / 3);
	int wcols = win_width - 4;
	int pos = 0, ppos = -1, offs = 0, poffs = -1;
	int loop = 0, sel = -1;
	char first = 1;
	char *dummy = (char *)mymalloc(wcols + 1);
	int path_max = find_path_max();
	char *selstr = (char *)mymalloc(path_max + 1), selfound = 0;

	selstr[0] = 0x00;

	mywin = create_popup(total_win_size, win_width);

	for(;;)
	{
		int c;

		/* draw list */
		if (pos != ppos)
		{
			int entries_left = (nlines - pos);

			werase(mywin -> win);

			if (heading)
				win_header(mywin, heading);
			else if (type == SEL_WIN)
				win_header(mywin, "Select window");
			else if (type == SEL_SUBWIN)
				win_header(mywin, "Select subwindow");
			else if (type == SEL_FILES)
				win_header(mywin, "Select file");
			else if (type == SEL_CSCHEME)
				win_header(mywin, "Select color scheme");
			else if (type == SEL_HISTORY)
				win_header(mywin, "Select string from history");

			for(loop=0; loop<min(entries_left, wlines); loop++)
			{
				char invert = generate_string(dummy, list, type, wcols, loop + pos);
				if (loop == offs)
					ui_inverse_on(mywin);
				if (invert) color_on(mywin, find_colorpair(COLOR_YELLOW, -1, 0));
				if (needs_mark && needs_mark[loop + pos])
					mvwprintw(mywin -> win, loop + 2, 1, "*");
				mvwprintw(mywin -> win, loop + 2, 2, "%s", dummy);
				if (invert) color_off(mywin, find_colorpair(COLOR_YELLOW, -1, 0));
				if (loop == offs)
					ui_inverse_off(mywin);
			}

			draw_border(mywin);

			ppos = pos;
			poffs = offs;
		}
		else if (poffs != offs)
		{
			int yellow_cp = find_colorpair(COLOR_YELLOW, -1, 0);
			char invert = generate_string(dummy, list, type, wcols, poffs + pos);
			if (invert) color_on(mywin, yellow_cp);
			mvwprintw(mywin -> win, poffs + 2, 2, "%s", dummy);
			if (invert) color_off(mywin, yellow_cp);

			invert = generate_string(dummy, list, type, wcols, offs + pos);

			ui_inverse_on(mywin);
			if (invert) color_on(mywin, yellow_cp);
			if (needs_mark && needs_mark[offs + pos])
				mvwprintw(mywin -> win, loop + 2, 1, "*");
			mvwprintw(mywin -> win, offs + 2, 2, "%s", dummy);
			if (invert) color_off(mywin, yellow_cp);
			ui_inverse_off(mywin);

			poffs = offs;
		}

		if (first)
		{
			first = 0;
			color_on(mywin, find_colorpair(COLOR_GREEN, -1, 0));
			mvwprintw(mywin -> win, total_win_size - 2, 2, "Press ^G to abort");
			color_off(mywin, find_colorpair(COLOR_GREEN, -1, 0));
		}
		else
		{
			int loop, len = strlen(selstr);

			for(loop=0; loop<wcols; loop++)
				mvwprintw(mywin -> win, total_win_size - 2, 1 + loop, " ");

			if (!selfound) color_on(mywin, find_colorpair(COLOR_RED, -1, 0));
			mvwprintw(mywin -> win, total_win_size - 2, 1, "%s", &selstr[max(0, len - wcols)]);
			if (!selfound) color_off(mywin, find_colorpair(COLOR_RED, -1, 0));
		}

		mydoupdate();

		c = wait_for_keypress(what_help, 0, mywin, 1);

		if (c == KEY_UP)
		{
			if ((offs + pos) > 0)
			{
				if (offs)
					offs--;
				else
					pos--;
			}
			else
			{
				wrong_key();
			}
		}
		else if (c == KEY_DOWN)
		{
			if ((pos + offs) < (nlines-1))
			{
				if (offs < (wlines-1))
					offs++;
				else
					pos++;
			}
			else
			{
				wrong_key();
			}
		}
		else if (c == KEY_NPAGE)
		{
			if ((pos + offs) < (nlines - 1))
			{
				pos += min(wlines, (nlines - 1) - (pos + offs));
			}
			else
			{
				wrong_key();
			}
		}
		else if (c == KEY_PPAGE)
		{
			if ((pos + offs - wlines) >= 0)
			{
				if (pos > wlines)
				{
					pos -= wlines;
				}
				else
				{
					pos -= (wlines - offs);
					offs = 0;
				}
			}
			else if (offs > 0)
			{
				offs = 0;
			}
			else if (pos > 0)
			{
				pos = 0;
			}
			else
			{
				wrong_key();
			}
		}
		else if (c == KEY_ENTER || c == 13 || c == 10)
		{
			sel = pos + offs;
			break;
		}
		else if (c == abort_key || c == -1)
		{
			break;
		}
		else if ((c > 31 && c != 127) || (c == KEY_BACKSPACE))
		{
			int index, curlen;

			curlen = strlen(selstr);
			if (c == KEY_BACKSPACE)
			{
				if (curlen > 0)
					selstr[curlen - 1] = 0x00;
				else
					wrong_key();
			}
			else if (curlen < path_max)
			{
				selstr[curlen] = c;
				selstr[curlen + 1] = 0x00;
			}
			else
				wrong_key();


			curlen = strlen(selstr);
			if (curlen > 0)
			{
				index = find_sb_string(list, type, nlines, selstr);
				if (index != -1)
				{
					ppos = -1;
					sel = pos = index;
					selfound = 1;
				}
				else
				{
					selfound = 0;
				}
			}
		}
		else
		{
			wrong_key();
		}
	}

	delete_popup(mywin);

	myfree(dummy);
	myfree(selstr);

	return sel;
}
Ejemplo n.º 20
0
// WINDOW *echowindow points to the window that processes the input
// basically it's input_win during the game and stdscr before the game screen is loaded
bool todd_getline(char **line, size_t *len, WINDOW *echowindow)
{
	// curs_set displays a nice cursor for user convenience
	curs_set(1);
	chat_typing = 1;
	bool ret = false;
	size_t buf_len = 20;
	*line = malloc(buf_len);
	*len = 0;
	unsigned char c;
	do
	{
		bool rc = todd_getchar(&c);
		if (!rc || c == '\t')	
		{
		// pressing TAB (\t) when in input mode is supposed to toggle chat
		//
		// however, pressing TAB when logging in (typing name or password)
		// would cause the program to quit
		// -> don't accept TAB when logging in

		// echowindow == input_win either when 
		//	todd_getline is called with input_win
		// OR   they are both NULL (when logging in)
		//	therefore, those two cases can't be true at the same time
		if (echowindow == input_win && input_win != NULL)
			{		
				free(*line);
				*line = NULL;
				*len = 0;
				goto cleanup;
	
			}
		continue;	// don't accept TAB unless in input_win, just skip it

		}
		if (c == '\b') // it's a backspace, go back a character
		{
			// if echowindow is NULL it means we're asking for the password
			// in this case, make backspace work
			int password = 0;
			if (echowindow == NULL)
				{
				password = 1;
				echowindow = stdscr;
				}

			// don't backspace on an empty string or the pointer will cause a segfault
			if ((*len) != 0) 
			{
				// if it's a multibyte (scandic letters, § and so on)
				// len -1 and len -2 have negative values
				int multibyte = 0;
				if ((*line)[*len - 1] < 0)
					multibyte = 1;

				int y,x;
				// get current position of cursor to y and x
				getyx(echowindow,y,x);
				// move the cursor left by one
				wmove(echowindow, y,x-1);
				// blank it from screen and from buffer
				wechochar(echowindow, ' ');
				(*line)[*len] = '\0';
				(*len)--;
				if (multibyte) // there's two chars in buffer, not one
				{
				(*line)[*len] = '\0';
				(*len)--;
				}

				// by calling wechochar, the cursor moves right. move it back
				wmove(echowindow, y,x-1);
				wrefresh(echowindow);

			// if this was in the password field, change echowindow back to original value
			if (password)
				echowindow = NULL;
			}
		}
		else	// it's just a normal character
		{
			if (buf_len <= *len)
			{
				buf_len += 20;
				*line = realloc(*line, buf_len);
			}

			(*line)[*len] = c;
			(*len)++;
			// echo the character, except when echowindow is NULL echo a * to stdscr
			// this is a hack: echowindow is NULL only when asking for a password
			// also, don't echo a \r
			if (echowindow == NULL && c != '\r')
				wechochar(stdscr, '*');
			else
			if (c != '\r')	// without this, todd_getline would eat the "Halt! who goes there" -message 
					// when asking for player name
				wechochar(echowindow, c);
		}

	} while (c != '\r');

	(*len)--; // strip trailing newline
	(*line)[*len] = '\0'; // insert null terminator

	curs_set(0);

	if (*len == 0) // it's an empty string..
		return false;
	// else, return true
	ret = true;

cleanup:
	if (echowindow == input_win)
		{
		werase(echowindow);
		wrefresh(echowindow);
		}

	chat_typing = 0;
	curs_set(0);

	return ret;
}
Ejemplo n.º 21
0
int
curses_getpos(int *x, int *y, nh_bool force, const char *goal)
{
    int result = 0;
    int cx, cy;
    int key, dx, dy;
    int sidx;
    static const char pick_chars[] = " \r\n.,;:";
    static const int pick_vals[] = {1, 1, 1, 1, 2, 3, 4};
    const char *cp;
    char printbuf[BUFSZ];
    char *matching = NULL;
    enum nh_direction dir;
    struct coord *monpos = NULL;
    int moncount, monidx;
    int firstmove = 1;

    werase(statuswin);
    mvwaddstr(statuswin, 0, 0,
              "Move the cursor with the direction keys. Press "
              "the letter of a dungeon symbol");
    mvwaddstr(statuswin, 1, 0,
              "to select it or use m to move to a nearby "
              "monster. Finish with one of .,;:");
    wrefresh(statuswin);

    cx = *x >= 1 ? *x : player.x;
    cy = *y >= 0 ? *y : player.y;
    wmove(mapwin, cy, cx - 1);

    while (1) {
        if (!firstmove) {
            struct nh_desc_buf descbuf;
            int mx = 0, my = 0;

            nh_describe_pos(cx, cy, &descbuf, NULL);

            werase(statuswin);
            place_desc_message(statuswin, &mx, &my, descbuf.effectdesc);
            place_desc_message(statuswin, &mx, &my, descbuf.invisdesc);
            place_desc_message(statuswin, &mx, &my, descbuf.mondesc);
            place_desc_message(statuswin, &mx, &my, descbuf.objdesc);
            place_desc_message(statuswin, &mx, &my, descbuf.trapdesc);
            place_desc_message(statuswin, &mx, &my, descbuf.bgdesc);
            wrefresh(statuswin);

            wmove(mapwin, cy, cx - 1);
        }
        firstmove = 0;
        dx = dy = 0;
        key = get_map_key(FALSE);
        if (key == KEY_ESC) {
            cx = cy = -10;
            result = -1;
            break;
        }

        if ((cp = strchr(pick_chars, (char)key)) != 0) {
            /* '.' => 0, ',' => 1, ';' => 2, ':' => 3 */
            result = pick_vals[cp - pick_chars];
            break;
        }

        dir = key_to_dir(key);
        if (dir != DIR_NONE) {
            dx = xdir[dir];
            dy = ydir[dir];
        } else if ((dir = key_to_dir(tolower((char)key))) != DIR_NONE) {
            /* a shifted movement letter */
            dx = xdir[dir] * 8;
            dy = ydir[dir] * 8;
        }

        if (dx || dy) {
            /* truncate at map edge */
            if (cx + dx < 1)
                dx = 1 - cx;
            if (cx + dx > COLNO - 1)
                dx = COLNO - 1 - cx;
            if (cy + dy < 0)
                dy = -cy;
            if (cy + dy > ROWNO - 1)
                dy = ROWNO - 1 - cy;
            cx += dx;
            cy += dy;
            goto nxtc;
        }

        if (key == 'm') {
            if (!monpos) {
                int i, j;

                moncount = 0;
                for (i = 0; i < ROWNO; i++)
                    for (j = 0; j < COLNO; j++)
                        if (display_buffer[i][j].mon &&
                            (j != player.x || i != player.y))
                            moncount++;
                monpos = malloc(moncount * sizeof (struct coord));
                monidx = 0;
                for (i = 0; i < ROWNO; i++)
                    for (j = 0; j < COLNO; j++)
                        if (display_buffer[i][j].mon &&
                            (j != player.x || i != player.y)) {
                            monpos[monidx].x = j;
                            monpos[monidx].y = i;
                            monidx++;
                        }
                monidx = 0;
                qsort(monpos, moncount, sizeof (struct coord),
                      compare_coord_dist);
            }

            if (moncount) {     /* there is at least one monster to move to */
                cx = monpos[monidx].x;
                cy = monpos[monidx].y;
                monidx = (monidx + 1) % moncount;
            }
        } else {
            int k = 0, tx, ty;
            int pass, lo_x, lo_y, hi_x, hi_y;

            matching = malloc(default_drawing->num_bgelements);
            memset(matching, 0, default_drawing->num_bgelements);
            for (sidx = default_drawing->bg_feature_offset;
                 sidx < default_drawing->num_bgelements; sidx++)
                if (key == default_drawing->bgelements[sidx].ch)
                    matching[sidx] = (char)++k;
            if (k) {
                for (pass = 0; pass <= 1; pass++) {
                    /* pass 0: just past current pos to lower right; pass 1:
                       upper left corner to current pos */
                    lo_y = (pass == 0) ? cy : 0;
                    hi_y = (pass == 0) ? ROWNO - 1 : cy;
                    for (ty = lo_y; ty <= hi_y; ty++) {
                        lo_x = (pass == 0 && ty == lo_y) ? cx + 1 : 1;
                        hi_x = (pass == 1 && ty == hi_y) ? cx : COLNO - 1;
                        for (tx = lo_x; tx <= hi_x; tx++) {
                            k = display_buffer[ty][tx].bg;
                            if (k && matching[k]) {
                                cx = tx;
                                cy = ty;
                                goto nxtc;
                            }
                        }       /* column */
                    }   /* row */
                }       /* pass */
                sprintf(printbuf, "Can't find dungeon feature '%c'.",
                        (char)key);
                curses_msgwin(printbuf);
            } else {
                sprintf(printbuf, "Unknown direction%s.",
                        !force ? " (ESC to abort)" : "");
                curses_msgwin(printbuf);
            }
        }
        if (force)
            goto nxtc;
        cx = -1;
        cy = 0;
        result = 0;     /* not -1 */
        break;

    nxtc:
        wmove(mapwin, cy, cx - 1);
        wrefresh(mapwin);
    }

    *x = cx;
    *y = cy;
    if (monpos)
        free(monpos);
    if (matching)
        free(matching);
    curses_update_status(NULL); /* clear the help message */
    return result;
}
Ejemplo n.º 22
0
//clears a window
int wclear(WINDOW *win)
{
    werase(win);
    wrefresh(win);
    return 1;
};
Ejemplo n.º 23
0
int showmenu(list<Mod>& options) {
    int ch;
    int line = 0;
    int offset = 0;
    int typed = 0;
    WINDOW* menu = newwin(LINES-1, (COLS-1)/2, 0, 0);
    PANEL* pmenu = new_panel(menu);
    WINDOW* info = newwin(LINES-1, COLS/2, 0, (COLS-1)/2);
    PANEL* pinfo = new_panel(info);
    status(" ");

    do {
        werase(menu);
        wprintw(menu, "Select Mods");

        int start = offset;
        int end = offset + (LINES-4);
        if (end > (int)options.size()) end = options.size();

        list<Mod>::iterator i = options.begin();
        int x = 0;
        while (x < start) x++, i++;
        if (x++ == 0) {
            mvwprintw(menu, 3, 0, "Done\n");
            if (line == 0) mvwchgat(menu, 3, 0, -1, A_REVERSE, 0, NULL);
        }
        while (x <= end && i != options.end()) {
            mvwprintw(menu, x-start+3, 0, "%d: %s\n", x, i->name);
            if (x == line) {
                mvwchgat(menu, x-start+3, 0, -1, A_REVERSE, 0, NULL);
                showinfo(info, *i);
            }
            x++, i++;
        }
        end = x;
        update_panels();
        doupdate();

        ch = getch();
        switch (ch) {
        case KEY_UP:
            line--;
            if (line < 0) line = 0;
            if (line-1 <= start) {
                offset--;
                if (offset < 0) offset = 0;
            }
            if (typed) status(" ");
            typed = 0;
            break;
        case KEY_DOWN:
            line++;
            if (line >= end) line = end-1;
            if (line-start+5 >= LINES) {
                offset++;
            }
            if (typed) status(" ");
            typed = 0;
            break;
        case KEY_PPAGE:
            line -= LINES-4;
            if (line < 0) line = 0;
            offset = line-1;
            if (offset < 0) offset = 0;
            break;
        case KEY_NPAGE:
            line += LINES-4;
            if (line > (int)options.size())
                line = options.size();
            offset = line-LINES+6;
            if (offset < 0) offset = 0;
            break;
        case KEY_HOME:
            line = 0;
            offset = 0;
            break;
        case KEY_END:
            line = options.size();
            offset = line-LINES+6;
            if (offset < 0) offset = 0;
            break;
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            typed *= 10;
            typed += ch - '0';
            line = typed;
            if (line > (int)options.size()) line = options.size();
            status("%d", typed);
            break;
        }
    } while (ch != '\n');

    del_panel(pinfo);
    delwin(info);
    del_panel(pmenu);
    delwin(menu);
    update_panels();
    doupdate();
    return line-1;
}
Ejemplo n.º 24
0
/// update information at ncurses mode
extern void Ncurses_progress_update(struct progress_bar *prog, unsigned long long copied, unsigned long long current, int done)
{
#ifdef HAVE_LIBNCURSESW

    char *p_block, *t_block;
    prog_stat_t prog_stat;

    memset(&prog_stat, 0, sizeof(prog_stat_t));
    calculate_speed(prog, copied, current, done, &prog_stat);

    /// set bar color
    init_pair(4, COLOR_RED, COLOR_RED);
    init_pair(5, COLOR_WHITE, COLOR_BLUE);
    init_pair(6, COLOR_WHITE, COLOR_RED);
    werase(p_win);
    werase(bar_win);

    if (done != 1){
        if (difftime(time(0), prog->resolution_time) < prog->interval_time)
            return;
	prog->resolution_time = time(0);

        mvwprintw(p_win, 0, 0, _("Elapsed: %s Remaining: %s ") , prog_stat.Eformated, prog_stat.Rformated);
	if((prog->flag == IO) || (prog->flag == NO_BLOCK_DETAIL))
	    mvwprintw(p_win, 0, 40, _("Rate: %6.2f%s/min"), prog_stat.speed, prog_stat.speed_unit);
	if (prog->flag == IO)
	    mvwprintw(p_win, 1, 0, _("Current Block: %lld  Total Block: %lld ") , current, prog->total);
        p_block = calloc(sizeof(char), 50);
        t_block = calloc(sizeof(char), 50);
        memset(p_block, ' ', (size_t)(prog_stat.percent*0.5));
        memset(t_block, ' ', (size_t)(prog_stat.total_percent*0.5));
        
	if (prog->flag == IO)
	    mvwprintw(p_win, 3, 0, "Data Block Process:");
	else if (prog->flag == BITMAP)
	    mvwprintw(p_win, 3, 0, "Calculating Bitmap Process:");
	wattrset(bar_win, COLOR_PAIR(4));
        mvwprintw(bar_win, 0, 0, "%s", p_block);
        wattroff(bar_win, COLOR_PAIR(4));
        mvwprintw(p_win, 4, 52, "%6.2f%%", prog_stat.percent);
        
	if (prog->flag == IO) {
	    werase(tbar_win);
	    mvwprintw(p_win, 6, 0, "Total Block Process:");
	    wattrset(tbar_win, COLOR_PAIR(4));
	    mvwprintw(tbar_win, 0, 0, "%s", t_block);
	    wattroff(tbar_win, COLOR_PAIR(4));
	    mvwprintw(p_win, 7, 52, "%6.2f%%", prog_stat.total_percent);
	}

	free(p_block);
	free(t_block);
        
	wrefresh(p_win);
        wrefresh(bar_win);
        wrefresh(tbar_win);
    } else {
        mvwprintw(p_win, 0, 0, _("Total Time: %s Remaining: %s "), prog_stat.Eformated, prog_stat.Rformated);
	if((prog->flag == IO) || (prog->flag == NO_BLOCK_DETAIL))
	    mvwprintw(p_win, 1, 0, _("Ave. Rate: %6.2f%s/min"), prog_stat.speed, prog_stat.speed_unit);

	if (prog->flag == IO)
	    mvwprintw(p_win, 3, 0, "Data Block Process:");
	else if (prog->flag == BITMAP)
	    mvwprintw(p_win, 3, 0, "Calculating Bitmap Process:");
        wattrset(bar_win, COLOR_PAIR(4));
	mvwprintw(bar_win, 0, 0, "%50s", " ");
        wattroff(bar_win, COLOR_PAIR(4));
        mvwprintw(p_win, 4, 52, "100.00%%");

	if (prog->flag == IO) {
	    werase(tbar_win);
	    mvwprintw(p_win, 6, 0, "Total Block Process:");
	    wattrset(tbar_win, COLOR_PAIR(4));
	    mvwprintw(tbar_win, 0, 0, "%50s", " ");
	    wattroff(tbar_win, COLOR_PAIR(4));
	    mvwprintw(p_win, 7, 52, "100.00%%");
	}

        wrefresh(p_win);
        wrefresh(bar_win);
        wrefresh(tbar_win);
        refresh();
	sleep(1);
    }

#endif
}
Ejemplo n.º 25
0
/* 
 * called to redraw the menu
 */
static int wdg_input_redraw(struct wdg_object *wo)
{
   WDG_WO_EXT(struct wdg_input_handle, ww);
   size_t c, l, x, y;
   
   WDG_DEBUG_MSG("wdg_input_redraw");
   
   /* center the window on the screen */
   wo->x1 = (current_screen.cols - (ww->x + 2)) / 2;
   wo->y1 = (current_screen.lines - (ww->y + 2)) / 2;
   wo->x2 = -wo->x1;
   wo->y2 = -wo->y1;
   
   c = wdg_get_ncols(wo);
   l = wdg_get_nlines(wo);
   x = wdg_get_begin_x(wo);
   y = wdg_get_begin_y(wo);
   
   /* deal with rouding */
   if (l != ww->y + 2) l = ww->y + 2;
   if (c != ww->x + 2) c = ww->x + 2;
 
   /* the window already exist */
   if (ww->win) {
      /* erase the border */
      wbkgd(ww->win, COLOR_PAIR(wo->screen_color));
      werase(ww->win);
      /* destroy the internal form */
      wdg_input_form_destroy(wo);
      
      touchwin(ww->win);
      wnoutrefresh(ww->win);

      /* set the form color */
      wbkgd(ww->win, COLOR_PAIR(wo->window_color));
     
      /* resize the window */
      mvwin(ww->win, y, x);
      wresize(ww->win, l, c);
      
      /* redraw the window */
      wdg_input_borders(wo);
      
      /* create the internal form */
      wdg_input_form_create(wo);
      
      touchwin(ww->win);

   /* the first time we have to allocate the window */
   } else {

      /* create the menu window (fixed dimensions) */
      if ((ww->win = newwin(l, c, y, x)) == NULL)
         return -WDG_E_FATAL;

      /* set the window color */
      wbkgd(ww->win, COLOR_PAIR(wo->window_color));
      redrawwin(ww->win);
      
      /* draw the titles */
      wdg_input_borders(wo);

      /* create the internal form */
      wdg_input_form_create(wo);

      /* no scrolling for menu */
      scrollok(ww->win, FALSE);

   }
   
   /* refresh the window */
   touchwin(ww->win);
   wnoutrefresh(ww->win);
   
   touchwin(ww->fwin);
   wnoutrefresh(ww->fwin);

   wo->flags |= WDG_OBJ_VISIBLE;

   return WDG_E_SUCCESS;
}
Ejemplo n.º 26
0
static void
draw_status(struct nh_player_info *pi, nh_bool threeline)
{
    char buf[ui_flags.mapwidth];
    int i, j, k;

    if (!statuswin)
        return;

    if (ui_flags.statusheight < 2) {
        werase(statuswin);
        return;
    }

    /* penultimate line */
    wmove(statuswin, (threeline ? 1 : 0), 0);
    draw_bar(15, pi->hp, pi->hpmax, TRUE);
    wprintw(statuswin, " Def:%d %s:%d", 10 - pi->ac,
            pi->monnum == pi->cur_monnum ? "Xp" : "HD", pi->level);
    if (threeline && pi->monnum == pi->cur_monnum) {
        /* keep this synced with newuexp in exper.c */
        long newuexp = 10L * (1L << pi->level);

        if (pi->level >= 10)
            newuexp = 10000L * (1L << (pi->level - 10));
        if (pi->level >= 20)
            newuexp = 10000000L * ((long)(pi->level - 19));
        wprintw(statuswin, "(%ld)", newuexp - pi->xp);
    }
    wprintw(statuswin, " %s", pi->level_desc);
    wclrtoeol(statuswin);

    /* last line */
    wmove(statuswin, (threeline ? 2 : 1), 0);
    draw_bar(15, pi->en, pi->enmax, FALSE);
    wprintw(statuswin, " %c%ld S:%ld T:%ld", pi->coinsym, pi->gold, pi->score,
            pi->moves);
    if (getcurx(statuswin) > 0)
        wclrtoeol(statuswin);

    /* status */
    int mainframe_color = CLR_GRAY;
    j = getmaxx(statuswin) + 1;
    for (i = 0; i < pi->nr_items; i++) {
        int color = CLR_WHITE, colorattr;

        j -= strlen(pi->statusitems[i]) + 1;
        for (k = 0; statuscolors[k].name; k++) {
            if (!strcmp(pi->statusitems[i], statuscolors[k].name)) {
                color = statuscolors[k].color;
                if (statuscolors[k].framecolor != -1)
                    mainframe_color = statuscolors[k].framecolor;
                break;
            }
        }
        colorattr = curses_color_attr(color, 0);
        wmove(statuswin, (threeline ? 2 : 1), j);
        wattron(statuswin, colorattr);
        wprintw(statuswin, "%s", pi->statusitems[i]);
        wattroff(statuswin, colorattr);
    }

    /* frame color */
    if (pi->hp * 7 <= pi->hpmax)
        mainframe_color = CLR_ORANGE;
    else if (pi->hp * 3 <= pi->hpmax)
        mainframe_color = CLR_RED;

    if (ui_flags.current_followmode != FM_PLAY)
        mainframe_color = CLR_BLACK;     /* a hint that we can't write */

    /* We change the frame color via palette manipulation, because it's awkward
       to correctly redraw otherwise. However, we don't want to do color
       mapping logic here. So we copy an existing palette entry. */
    uncursed_color fgcode, bgcode;
    pair_content(PAIR_NUMBER(curses_color_attr(mainframe_color, 0)),
                 &fgcode, &bgcode);
    init_pair(MAINFRAME_PAIR, fgcode, bgcode);

    /* name */
    if (threeline) {
        sprintf(buf, "%.12s the %s %s", pi->plname,
                (pi->align == A_CHAOTIC) ? "Chaotic" :
                (pi->align == A_NEUTRAL) ? "Neutral" :
                "Lawful", pi->rank);
        wmove(statuswin, 0, 0);
    } else {
        sprintf(buf, "%.12s, %s", pi->plname, pi->rank);
        wmove(statuswin, 0, getmaxx(statuswin) - strlen(buf));
    }
    wprintw(statuswin, "%s", buf);
    if (getcurx(statuswin) > 0)
        wclrtoeol(statuswin);

    /* abilities (in threeline mode) "In:18 Wi:18 Ch:18" = 17 chars */
    if (threeline) {
        wmove(statuswin, 0, getmaxx(statuswin) - (pi->st == 18 ? 20 : 17));
        wprintw(statuswin, "Dx:%-2d Co:%-2d St:%-2d", pi->dx, pi->co, pi->st);
        if (pi->st == 18 && pi->st_extra == 100)
            wprintw(statuswin, "/**");
        else if (pi->st == 18)
            wprintw(statuswin, "/%02d", pi->st_extra);
        wmove(statuswin, 1, getmaxx(statuswin) - (pi->st == 18 ? 20 : 17));
        wprintw(statuswin, "In:%-2d Wi:%-2d Ch:%-2d", pi->in, pi->wi, pi->ch);
    }
}
Ejemplo n.º 27
0
static int SCW_Erase( lua_State *L ){
	WINDOW **w = checkSelCWindow(L);

	werase( *w );
	return 0;
}
Ejemplo n.º 28
0
void game::monster_wish()
{
 WINDOW* w_list = newwin(25, 30, 0,  0);
 WINDOW* w_info = newwin(25, 50, 0, 30);
 int a = 0, shift = 1, result_selected = 0;
 int line;
 char ch = '.';
 bool search = false, found = false, friendly = false;
 std::string pattern;
 std::string info;
 std::vector<int> search_results;
 monster tmp;
 do {
  werase(w_info);
  werase(w_list);
  mvwprintw(w_list, 0, 0, "Spawn a: ");
  if (search) {
   found = false;
   if (ch == '\n') {
    search = false;
    found = true;
    ch = '.';
   } else if (ch == KEY_BACKSPACE || ch == 127) {
    if (pattern.length() > 0)
     pattern.erase(pattern.end() - 1);
   } else if (ch == '>') {
    search = false;
    if (!search_results.empty()) {
     result_selected++;
     if (result_selected > search_results.size())
      result_selected = 0;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > mtypes.size()) {
      a = shift + 23 - mtypes.size();
      shift = mtypes.size() - 23;
     }
    }
   } else if (ch == '<') {
    search = false;
    if (!search_results.empty()) {
     result_selected--;
     if (result_selected < 0)
      result_selected = search_results.size() - 1;
     shift = search_results[result_selected];
     a = 0;
     if (shift + 23 > mtypes.size()) {
      a = shift + 23 - mtypes.size();
      shift = mtypes.size() - 23;
     }
    }
   } else {
    pattern += ch;
    search_results.clear();
   }

   if (search) {
    for (int i = 1; i < mtypes.size(); i++) {
     if (mtypes[i]->name.find(pattern) != std::string::npos) {
      shift = i;
      a = 0;
      result_selected = 0;
      if (shift + 23 > mtypes.size()) {
       a = shift + 23 - mtypes.size();
       shift = mtypes.size() - 23;
      }
      found = true;
      search_results.push_back(i);
     }
    }
   }

  } else {	// Not searching; scroll by keys
   if (ch == 'j') a++;
   if (ch == 'k') a--;
   if (ch == 'f') friendly = !friendly;
   if (ch == '/') { 
    search = true;
    pattern =  "";
    found = false;
    search_results.clear();
   }
   if (ch == '>' && !search_results.empty()) {
    result_selected++;
    if (result_selected > search_results.size())
     result_selected = 0;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > mtypes.size()) {
     a = shift + 23 - mtypes.size();
     shift = mtypes.size() - 23;
    }
   } else if (ch == '<' && !search_results.empty()) {
    result_selected--;
    if (result_selected < 0)
     result_selected = search_results.size() - 1;
    shift = search_results[result_selected];
    a = 0;
    if (shift + 23 > mtypes.size()) {
     a = shift + 23 - mtypes.size();
     shift = mtypes.size() - 23;
    }
   }
  }
  if (!search_results.empty())
   mvwprintz(w_list, 0, 11, c_green, "%s               ", pattern.c_str());
  else if (pattern.length() > 0)
   mvwprintz(w_list, 0, 11, c_red, "%s not found!            ",pattern.c_str());
  if (a < 0) {
   a = 0;
   shift--;
   if (shift < 1) shift = 1;
  }
  if (a > 22) {
   a = 22;
   shift++;
   if (shift + 23 > mtypes.size()) shift = mtypes.size() - 23;
  }
  for (int i = 1; i < 24; i++) {
   nc_color col = c_white;
   if (i == a + 1)
    col = h_white;
   mvwprintz(w_list, i, 0, col, mtypes[i-1+shift]->name.c_str());
   wprintz(w_list, mtypes[i-1+shift]->color, " %c%", mtypes[i-1+shift]->sym);
  }
  tmp = monster(mtypes[a + shift]);
  if (friendly)
   tmp.friendly = -1;
  tmp.print_info(this, w_info);
  wrefresh(w_info);
  wrefresh(w_list);
  if (search)
   ch = getch();
  else
   ch = input();
 } while (ch != '\n');
 clear();
 delwin(w_info);
 delwin(w_list);
 refresh_all();
 wrefresh(w_terrain);
 point spawn = look_around();
 if (spawn.x == -1)
  return;
 tmp.spawn(spawn.x, spawn.y);
 z.push_back(tmp);
}
Ejemplo n.º 29
0
//erases the main window of all text and attributes
int erase(void)
{
    return werase(mainwin);
}
Ejemplo n.º 30
0
int worldfactory::show_worldgen_tab_options(WINDOW *win, WORLDPTR world)
{
    const int iTooltipHeight = 1;
    const int iContentHeight = FULL_SCREEN_HEIGHT - 3 - iTooltipHeight;

    const int iOffsetX = (TERMX > FULL_SCREEN_WIDTH) ? (TERMX - FULL_SCREEN_WIDTH) / 2 : 0;
    const int iOffsetY = (TERMY > FULL_SCREEN_HEIGHT) ? (TERMY - FULL_SCREEN_HEIGHT) / 2 : 0;

    WINDOW *w_options = newwin(iContentHeight, FULL_SCREEN_WIDTH - 2, iTooltipHeight + 2 + iOffsetY, 1 + iOffsetX);

    std::stringstream sTemp;

    std::map<int, bool> mapLines;
    mapLines[3] = true;
    mapLines[60] = true;
    // only populate once
    if (world->world_options.size() == 0) {
        for (std::map<std::string, cOpt>::iterator it = OPTIONS.begin(); it != OPTIONS.end(); ++it) {
            if (it->second.getPage() == "world_default") {
                world->world_options[it->first] = it->second;
            }
        }
    }

    std::vector<std::string> keys;
    for (std::map<std::string, cOpt>::iterator it = world->world_options.begin(); it != world->world_options.end(); ++it) {
        keys.push_back(it->first);
    }

    for (std::map<int, bool>::iterator mLine = mapLines.begin(); mLine != mapLines.end(); ++mLine){
        if (mLine->second){
            mvwputch(win, FULL_SCREEN_HEIGHT-1, mLine->first+1, c_ltgray, LINE_XXOX); // _|_
        }
    }
    mvwputch(win, 2, 61, c_ltgray, LINE_OXXX); //TODO: replace 61 by dynamic mapLines stuff, like it done above
    wrefresh(win);
    refresh();

    InputEvent ch;

    int sel = 0;

    int curoption = 0;
    do {
        for (int i = 0; i < iContentHeight; i++) {
            for (int j = 0; j < 79; j++) {
                if (mapLines[j]) {
                    mvwputch(w_options, i, j, c_ltgray, LINE_XOXO);
                } else {
                    mvwputch(w_options, i, j, c_black, ' ');
                }
            }
        }
        curoption = 0;
        for (std::map<std::string, cOpt>::iterator it = world->world_options.begin(); it != world->world_options.end(); ++it) {
            nc_color cLineColor = c_ltgreen;

            sTemp.str("");
            sTemp << curoption + 1;
            mvwprintz(w_options, curoption , 0, c_white, sTemp.str().c_str());
            mvwprintz(w_options, curoption , 4, c_white, "");

            if (sel == curoption) {
                wprintz(w_options, c_yellow, ">> ");
            } else {
                wprintz(w_options, c_yellow, " ");
            }

            wprintz(w_options, c_white, "%s", (it->second.getMenuText()).c_str());

            if (it->second.getValue() == "False") {
                cLineColor = c_ltred;
            }

            mvwprintz(w_options, curoption, 62, (sel == curoption) ? hilite(cLineColor) : cLineColor, "%s", (it->second.getValueName()).c_str());
            ++curoption;
        }

        wrefresh(w_options);
        refresh();

        ch = get_input();
        if (world->world_options.size() > 0 || ch == Tab) {
            switch(ch) {
                case DirectionS: //move down
                    sel++;
                    if (sel >= world->world_options.size()) {
                        sel = 0;
                    }
                    break;
                case DirectionN: //move up
                    sel--;
                    if (sel < 0) {
                        sel = world->world_options.size() - 1;
                    }
                    break;
                case DirectionW: //set to prev value
                    world->world_options[keys[sel]].setPrev();
                    break;
                case DirectionE: //set to next value
                    world->world_options[keys[sel]].setNext();
                    break;

                case DirectionUp: // '<'
                    werase(w_options);
                    delwin(w_options);
                    return -1;
                    break;
                case DirectionDown: // '>'
                    werase(w_options);
                    delwin(w_options);
                    return 1;
                    break;
                case Cancel:
                    return -999;
                    break;
            }
        }
    } while (true);

    return 0;
}