int main(void)
{
        WINDOW *win1;
        int x, y, i, j, k, tmp;	// j, k not used yet.
	int ridx;
	float ymufin=0.0, ftemp = 0.0, ftmp2 = 0.0, deltamu = 0.0, deltavar = 0.0, yvarmax = 0.0;
	float ymu[3500] = {}, yvar[3500] = {};
	int xrnd[3500] = {}, yhts[100] = {};
	int scnarr[35][100] = {};
	int slowness = 1000;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


//if ENTER, end:
		} else if (k == 10) {
		        delwin(win1);
			endwin();
			system("clear");
			break;
		}
	}
	return k;
	/*
***********************************************************************************************
	*/
	delwin(win1);
	endwin();
	system("clear");
        return 0;
}
예제 #2
0
파일: ui.cpp 프로젝트: DavidKeaton/dre
void window::shutdown(void)
{
	delwin(win);
}
예제 #3
0
/*
 * Display a menu for choosing among a number of options
 */
int dialog_menu(const char *title, const char *prompt, int height, int width,
		int menu_height, const char *current, int item_no,
		const char *const *items)
{
	int i, j, x, y, box_x, box_y;
	int key = 0, button = 0, scroll = 0, choice = 0;
	int first_item =  0, max_choice;
	WINDOW *dialog, *menu;
	FILE *f;

	max_choice = MIN(menu_height, item_no);

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

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

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

	draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
	wattrset(dialog, border_attr);
	mvwaddch(dialog, height - 3, 0, ACS_LTEE);
	for (i = 0; i < width - 2; i++)
		waddch(dialog, ACS_HLINE);
	wattrset(dialog, dialog_attr);
	wbkgdset(dialog, dialog_attr & A_COLOR);
	waddch(dialog, ACS_RTEE);

	print_title(dialog, title, width);

	wattrset(dialog, dialog_attr);
	print_autowrap(dialog, prompt, width - 2, 1, 3);

	menu_width = width - 6;
	box_y = height - menu_height - 5;
	box_x = (width - menu_width) / 2 - 1;

	/* create new window for the menu */
	menu = subwin(dialog, menu_height, menu_width,
		      y + box_y + 1, x + box_x + 1);
	keypad(menu, TRUE);

	/* draw a box around the menu items */
	draw_box(dialog, box_y, box_x, menu_height + 2, menu_width + 2,
		 menubox_border_attr, menubox_attr);

	item_x = (menu_width - 70) / 2;

	/* Set choice to default item */
	for (i = 0; i < item_no; i++)
		if (strcmp(current, items[i * 2]) == 0)
			choice = i;

	/* get the scroll info from the temp file */
	if ((f = fopen("lxdialog.scrltmp", "r")) != NULL) {
		if ((fscanf(f, "%d\n", &scroll) == 1) && (scroll <= choice) &&
		    (scroll + max_choice > choice) && (scroll >= 0) &&
		    (scroll + max_choice <= item_no)) {
			first_item = scroll;
			choice = choice - scroll;
			fclose(f);
		} else {
			scroll = 0;
			remove("lxdialog.scrltmp");
			fclose(f);
			f = NULL;
		}
	}
	if ((choice >= max_choice) || (f == NULL && choice >= max_choice / 2)) {
		if (choice >= item_no - max_choice / 2)
			scroll = first_item = item_no - max_choice;
		else
			scroll = first_item = choice - max_choice / 2;
		choice = choice - scroll;
	}

	/* Print the menu */
	for (i = 0; i < max_choice; i++) {
		print_item(first_item + i, i, i == choice);
	}

	wnoutrefresh(menu);

	print_arrows(dialog, item_no, scroll,
		     box_y, box_x + item_x + 1, menu_height);

	print_buttons(dialog, height, width, 0);
	wmove(menu, choice, item_x + 1);
	wrefresh(menu);

	while (key != ESC) {
		key = wgetch(menu);

		if (key < 256 && isalpha(key))
			key = tolower(key);

		if (strchr("ynmh", key))
			i = max_choice;
		else {
			for (i = choice + 1; i < max_choice; i++) {
				j = first_alpha(items[(scroll + i) * 2 + 1], "YyNnMmHh");
				if (key == tolower(items[(scroll + i) * 2 + 1][j]))
					break;
			}
			if (i == max_choice)
				for (i = 0; i < max_choice; i++) {
					j = first_alpha(items [(scroll + i) * 2 + 1], "YyNnMmHh");
					if (key == tolower(items[(scroll + i) * 2 + 1][j]))
						break;
				}
		}

		if (i < max_choice ||
		    key == KEY_UP || key == KEY_DOWN ||
		    key == '-' || key == '+' ||
		    key == KEY_PPAGE || key == KEY_NPAGE) {
			/* Remove highligt of current item */
			print_item(scroll + choice, choice, FALSE);

			if (key == KEY_UP || key == '-') {
				if (choice < 2 && scroll) {
					/* Scroll menu down */
					do_scroll(menu, &scroll, -1);

					print_item(scroll, 0, FALSE);
				} else
					choice = MAX(choice - 1, 0);

			} else if (key == KEY_DOWN || key == '+') {
				print_item(scroll+choice, choice, FALSE);

				if ((choice > max_choice - 3) &&
				    (scroll + max_choice < item_no)) {
					/* Scroll menu up */
					do_scroll(menu, &scroll, 1);

					print_item(scroll+max_choice - 1,
						   max_choice - 1, FALSE);
				} else
					choice = MIN(choice + 1, max_choice - 1);

			} else if (key == KEY_PPAGE) {
				scrollok(menu, TRUE);
				for (i = 0; (i < max_choice); i++) {
					if (scroll > 0) {
						do_scroll(menu, &scroll, -1);
						print_item(scroll, 0, FALSE);
					} else {
						if (choice > 0)
							choice--;
					}
				}

			} else if (key == KEY_NPAGE) {
				for (i = 0; (i < max_choice); i++) {
					if (scroll + max_choice < item_no) {
						do_scroll(menu, &scroll, 1);
						print_item(scroll+max_choice-1,
							   max_choice - 1, FALSE);
					} else {
						if (choice + 1 < max_choice)
							choice++;
					}
				}
			} else
				choice = i;

			print_item(scroll + choice, choice, TRUE);

			print_arrows(dialog, item_no, scroll,
				     box_y, box_x + item_x + 1, menu_height);

			wnoutrefresh(dialog);
			wrefresh(menu);

			continue;	/* wait for another key press */
		}

		switch (key) {
		case KEY_LEFT:
		case TAB:
		case KEY_RIGHT:
			button = ((key == KEY_LEFT ? --button : ++button) < 0)
			    ? 2 : (button > 2 ? 0 : button);

			print_buttons(dialog, height, width, button);
			wrefresh(menu);
			break;
		case ' ':
		case 's':
		case 'y':
		case 'n':
		case 'm':
		case '/':
			/* save scroll info */
			if ((f = fopen("lxdialog.scrltmp", "w")) != NULL) {
				fprintf(f, "%d\n", scroll);
				fclose(f);
			}
			delwin(dialog);
			fprintf(stderr, "%s\n", items[(scroll + choice) * 2]);
			switch (key) {
			case 's':
				return 3;
			case 'y':
				return 3;
			case 'n':
				return 4;
			case 'm':
				return 5;
			case ' ':
				return 6;
			case '/':
				return 7;
			}
			return 0;
		case 'h':
		case '?':
			button = 2;
		case '\n':
			delwin(dialog);
			if (button == 2)
				fprintf(stderr, "%s \"%s\"\n",
					items[(scroll + choice) * 2],
					items[(scroll + choice) * 2 + 1] +
					first_alpha(items [(scroll + choice) * 2 + 1], ""));
			else
				fprintf(stderr, "%s\n",
					items[(scroll + choice) * 2]);

			remove("lxdialog.scrltmp");
			return button;
		case 'e':
		case 'x':
			key = ESC;
		case ESC:
			break;
		}
	}

	delwin(dialog);
	remove("lxdialog.scrltmp");
	return -1;		/* ESC pressed */
}
예제 #4
0
파일: main.c 프로젝트: JonathanFu/OpenAM-1
int main(int argc, char** argv) {
    WINDOW *lic = NULL;
    int x, y, mr;
    int opt = 0, cnt = 0;
    char remname[256];
    char *licpath = NULL;
    FILE *fout = NULL;
    char *version = NULL;
    if (am_bin_path(instance_path, sizeof (instance_path)) == -1) {
        return 0;
    } else {
        if (am_whitespace(instance_path) > 0) {
            fprintf(stderr, "Whitespace in path: %s \n", instance_path);
            return 0;
        }

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

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

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

    net_initialize();

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

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

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

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

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

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

ret_to_menu:

    refresh();

    mr = mainmenu(y, x);

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

all_done:

    am_free(licpath);
    clean_main_menu();
    move(0, 0);
    clrtoeol();
    refresh();
    endwin();
    net_shutdown();
    return (EXIT_SUCCESS);
}
예제 #5
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.empty()) {
        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, 2, mLine->first + 1, BORDER_COLOR, LINE_OXXX); // -.-
            mvwputch(win, FULL_SCREEN_HEIGHT - 1, mLine->first + 1, BORDER_COLOR, LINE_XXOX); // _|_
        }
    }
    wrefresh(win);
    refresh();

    input_context ctxt("WORLDGEN_OPTION_DIALOG");
    ctxt.register_cardinal();
    ctxt.register_action("HELP_KEYBINDINGS");
    ctxt.register_action("QUIT");
    ctxt.register_action("NEXT_TAB");
    ctxt.register_action("PREV_TAB");
    unsigned int sel = 0;
    unsigned 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, BORDER_COLOR, 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, "%s", 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();

        const std::string action = ctxt.handle_input();
        if (action == "DOWN") {
                    sel++;
                    if (sel >= world->world_options.size()) {
                        sel = 0;
                    }
        } else if (action == "UP") {
                    if (sel == 0) {
                        sel = world->world_options.size() - 1;
                    } else {
                        sel--;
                    }
        } else if (!world->world_options.empty() && action == "LEFT") {
                    world->world_options[keys[sel]].setPrev();
        } else if (!world->world_options.empty() && action == "RIGHT") {
                    world->world_options[keys[sel]].setNext();
        } else if (action == "PREV_TAB") {
                    werase(w_options);
                    delwin(w_options);
                    return -1;
        } else if (action == "NEXT_TAB") {
                    werase(w_options);
                    delwin(w_options);
                    return 1;
        } else if (action == "QUIT") {
                    return -999;
        }
    } while (true);

    return 0;
}
예제 #6
0
파일: debugger.c 프로젝트: Alcaro/ZMZ
void closewindow(WINDOW *w) {
    delwin(w);
    touchwin(debugwin);
    wrefresh(debugwin);
}
예제 #7
0
void game::craft()
{
 if (u.morale_level() < MIN_MORALE_CRAFT) {	// See morale.h
  add_msg("Your morale is too low to craft...");
  return;
 }
 WINDOW *w_head = newwin( 3, 80, 0, 0);
 WINDOW *w_data = newwin(22, 80, 3, 0);
 craft_cat tab = CC_WEAPON;
 std::vector<recipe*> current;
 std::vector<bool> available;
 item tmp;
 int line = 0, xpos, ypos;
 bool redraw = true;
 bool done = false;
 char ch;

 inventory crafting_inv;
 crafting_inv.form_from_map(this, point(u.posx, u.posy), PICKUP_RANGE);
 crafting_inv += u.inv;
 crafting_inv += u.weapon;
 if (u.has_bionic(bio_tools)) {
  item tools(itypes[itm_toolset], turn);
  tools.charges = u.power_level;
  crafting_inv += tools;
 }

 do {
  if (redraw) { // When we switch tabs, redraw the header
   redraw = false;
   line = 0;
   draw_recipe_tabs(w_head, tab);
   current.clear();
   available.clear();
// Set current to all recipes in the current tab; available are possible to make
   pick_recipes(current, available, tab);
  }

// Clear the screen of recipe data, and draw it anew
  werase(w_data);
   mvwprintz(w_data, 20, 0, c_white, "\
Press ? to describe object.  Press <ENTER> to attempt to craft object.");
  wrefresh(w_data);
  for (int i = 0; i < current.size() && i < 23; i++) {
   if (i == line)
    mvwprintz(w_data, i, 0, (available[i] ? h_white : h_dkgray),
              itypes[current[i]->result]->name.c_str());
   else
    mvwprintz(w_data, i, 0, (available[i] ? c_white : c_dkgray),
              itypes[current[i]->result]->name.c_str());
  }
  if (current.size() > 0) {
   nc_color col = (available[line] ? c_white : c_dkgray);
   mvwprintz(w_data, 0, 30, col, "Primary skill: %s",
             (current[line]->sk_primary == sk_null ? "N/A" :
              skill_name(current[line]->sk_primary).c_str()));
   mvwprintz(w_data, 1, 30, col, "Secondary skill: %s",
             (current[line]->sk_secondary == sk_null ? "N/A" :
              skill_name(current[line]->sk_secondary).c_str()));
   mvwprintz(w_data, 2, 30, col, "Difficulty: %d", current[line]->difficulty);
   if (current[line]->sk_primary == sk_null)
    mvwprintz(w_data, 3, 30, col, "Your skill level: N/A");
   else
    mvwprintz(w_data, 3, 30, col, "Your skill level: %d",
              u.sklevel[current[line]->sk_primary]);
   if (current[line]->time >= 1000)
    mvwprintz(w_data, 4, 30, col, "Time to complete: %d minutes",
              int(current[line]->time / 1000));
   else
    mvwprintz(w_data, 4, 30, col, "Time to complete: %d turns",
              int(current[line]->time / 100));
   mvwprintz(w_data, 5, 30, col, "Tools required:");
   if (current[line]->tools[0].size() == 0) {
    mvwputch(w_data, 6, 30, col, '>');
    mvwprintz(w_data, 6, 32, c_green, "NONE");
    ypos = 6;
   } else {
    ypos = 5;
// Loop to print the required tools
    for (int i = 0; i < 5 && current[line]->tools[i].size() > 0; i++) {
     ypos++;
     xpos = 32;
     mvwputch(w_data, ypos, 30, col, '>');

     for (int j = 0; j < current[line]->tools[i].size(); j++) {
      itype_id type = current[line]->tools[i][j].type;
      int charges = current[line]->tools[i][j].count;
      nc_color toolcol = c_red;

      if (charges < 0 && crafting_inv.has_amount(type, 1))
       toolcol = c_green;
      else if (charges > 0 && crafting_inv.has_charges(type, charges))
       toolcol = c_green;

      std::stringstream toolinfo;
      toolinfo << itypes[type]->name + " ";
      if (charges > 0)
       toolinfo << "(" << charges << " charges) ";
      std::string toolname = toolinfo.str();
      if (xpos + toolname.length() >= 80) {
       xpos = 32;
       ypos++;
      }
      mvwprintz(w_data, ypos, xpos, toolcol, toolname.c_str());
      xpos += toolname.length();
      if (j < current[line]->tools[i].size() - 1) {
       if (xpos >= 77) {
        xpos = 32;
        ypos++;
       }
       mvwprintz(w_data, ypos, xpos, c_white, "OR ");
       xpos += 3;
      }
     }
    }
   }
 // Loop to print the required components
   ypos++;
   mvwprintz(w_data, ypos, 30, col, "Components required:");
   for (int i = 0; i < 5; i++) {
    if (current[line]->components[i].size() > 0) {
     ypos++;
     mvwputch(w_data, ypos, 30, col, '>');
    }
    xpos = 32;
    for (int j = 0; j < current[line]->components[i].size(); j++) {
     int count = current[line]->components[i][j].count;
     itype_id type = current[line]->components[i][j].type;
     nc_color compcol = c_red;
     if (itypes[type]->count_by_charges() && count > 0)  {
      if (crafting_inv.has_charges(type, count))
       compcol = c_green;
     } else if (crafting_inv.has_amount(type, abs(count)))
      compcol = c_green;
     std::stringstream dump;
     dump << abs(count) << "x " << itypes[type]->name << " ";
     std::string compname = dump.str();
     if (xpos + compname.length() >= 80) {
      ypos++;
      xpos = 32;
     }
     mvwprintz(w_data, ypos, xpos, compcol, compname.c_str());
     xpos += compname.length();
     if (j < current[line]->components[i].size() - 1) {
      if (xpos >= 77) {
       ypos++;
       xpos = 32;
      }
      mvwprintz(w_data, ypos, xpos, c_white, "OR ");
      xpos += 3;
     }
    }
   }
  }

  wrefresh(w_data);
  ch = input();
  switch (ch) {
  case '<':
   if (tab == CC_WEAPON)
    tab = CC_MISC;
   else
    tab = craft_cat(int(tab) - 1);
   redraw = true;
   break;
  case '>':
   if (tab == CC_MISC)
    tab = CC_WEAPON;
   else
    tab = craft_cat(int(tab) + 1);
   redraw = true;
   break;
  case 'j':
   line++;
   break;
  case 'k':
   line--;
   break;
  case '\n':
   if (!available[line])
    popup("You can't do that!");
   else if (itypes[current[line]->result]->m1 == LIQUID &&
            !u.has_watertight_container())
    popup("You don't have anything to store that liquid in!");
   else {
    make_craft(current[line]);
    done = true;
   }
   break;
  case '?':
   tmp = item(itypes[current[line]->result], 0);
   full_screen_popup(tmp.info(true).c_str());
   redraw = true;
   break;
  }
  if (line < 0)
   line = current.size() - 1;
  else if (line >= current.size())
   line = 0;
 } while (ch != KEY_ESCAPE && ch != 'q' && ch != 'Q' && !done);

 werase(w_head);
 werase(w_data);
 delwin(w_head);
 delwin(w_data);
 refresh_all();
}
예제 #8
0
int
main(int ac, char *av[])
{
	bool	restore;

	/* Revoke setgid privileges */
	setgid(getgid());

	if (strcmp(av[0], "a.out") == 0) {
		outf = fopen("q", "w");
		setbuf(outf, NULL);
		Debug = TRUE;
	}
	restore = FALSE;
	switch (ac) {
	  case 2:
		rest_f(av[1]);
		restore = TRUE;
	  case 1:
		break;
	  default:
		usage();
		/* NOTREACHED */
	}
	Play = PLAYER;
	initscr();
	delwin(stdscr);
	stdscr = Board = newwin(BOARD_Y, BOARD_X, 0, 0);
	Score = newwin(SCORE_Y, SCORE_X, 0, 40);
	Miles = newwin(MILES_Y, MILES_X, 17, 0);
#ifdef attron
	idlok(Board, TRUE);
	idlok(Score, TRUE);
	idlok(Miles, TRUE);
#endif
	leaveok(Score, TRUE);
	leaveok(Miles, TRUE);
	clearok(curscr, TRUE);
	srandomdev();
	cbreak();
	noecho();
	signal(SIGINT, rub);
	for (;;) {
		if (!restore || (Player[PLAYER].total >= 5000
		    || Player[COMP].total >= 5000)) {
			if (Player[COMP].total < Player[PLAYER].total)
				Player[PLAYER].games++;
			else if (Player[COMP].total > Player[PLAYER].total)
				Player[COMP].games++;
			Player[COMP].total = 0;
			Player[PLAYER].total = 0;
		}
		do {
			if (!restore)
				Handstart = Play = other(Handstart);
			if (!restore || On_exit) {
				shuffle();
				init();
			}
			newboard();
			if (restore)
				mvwaddstr(Score, ERR_Y, ERR_X, Initstr);
			prboard();
			do {
				domove();
				if (Finished)
					newscore();
				prboard();
			} while (!Finished);
			check_more();
			restore = On_exit = FALSE;
		} while (Player[COMP].total < 5000
		    && Player[PLAYER].total < 5000);
	}
}
예제 #9
0
void delWindows(struct windows *win) {
    delwin(win->main);
    delwin(win->textpad);
    delwin(win->menu);
    delwin(win->status);
}
예제 #10
0
파일: tasks.c 프로젝트: auca/com.341
int main(int argc, char **argv)
{
        int exit_status = 0;

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

        pid_t *pid_list = NULL;

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

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

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

        bool show_kernel_threads = false;

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

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

            exit_status =
                EXIT_FAILURE;

            goto cleanup;
        }

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

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

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

            memset(pid_list, 0, pid_list_size);

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

                exit_status =
                    EXIT_FAILURE;

                goto cleanup;
            }

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

                if (pad) {
                    delwin(pad);
                }

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

                    exit_status =
                        EXIT_FAILURE;

                    goto cleanup;
                }

                keypad(pad, true);
            }

            size_t header_height =
                Header_Height;

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

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

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

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

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

            werase(pad);

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

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

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

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

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

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

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

                    ++real_pad_height;
                }
            }

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

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

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

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

                        break;
                    case 'q':
                        goto cleanup;
                }

                int pad_height_limit =
                    real_pad_height - 2;

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

                int pad_width_limit =
                    header_length - 5;

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

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

        endwin();

        return exit_status;
}
예제 #11
0
void veh_interact::exec (game *gm, vehicle *v, int x, int y)
{
    g = gm;
    veh = v;
    ex = x;
    ey = y;
    //        x1      x2
    // y1 ----+------+--
    //        |      |
    // y2 ----+------+
    //               |
    //               |
    winw1 = 12;
    winw2 = 35;
    winh1 = 3;
    winh2 = 12;
    winw12 = winw1 + winw2 + 1;
    winw3 = 80 - winw1 - winw2 - 2;
    winh3 = 25 - winh1 - winh2 - 2;
    winh23 = winh2 + winh3 + 1;
    winx1 = winw1;
    winx2 = winw1 + winw2 + 1;
    winy1 = winh1;
    winy2 = winh1 + winh2 + 1;

    page_size = winh23;
    //               h   w    y     x
    w_grid  = newwin(25, 80,  0,    0);
    w_mode  = newwin(1,  80, 0,    0);
    w_msg   = newwin(winh1 - 1, 80, 1,    0);
    w_disp  = newwin(winh2, winw1,  winy1 + 1, 0);
    w_parts = newwin(winh2, winw2,  winy1 + 1, winx1 + 1);
    w_stats = newwin(winh3, winw12, winy2 + 1, 0);
    w_list  = newwin(winh23, winw3, winy1 + 1, winx2 + 1);

    for (int i = 0; i < 25; i++)
    {
        mvwputch(w_grid, i, winx2, c_ltgray, i == winy1 || i == winy2? LINE_XOXX : LINE_XOXO);
        if (i >= winy1 && i < winy2)
            mvwputch(w_grid, i, winx1, c_ltgray, LINE_XOXO);
    }
    for (int i = 0; i < 80; i++)
    {
        mvwputch(w_grid, winy1, i, c_ltgray, i == winx1? LINE_OXXX : (i == winx2? LINE_OXXX : LINE_OXOX));
        if (i < winx2)
            mvwputch(w_grid, winy2, i, c_ltgray, i == winx1? LINE_XXOX : LINE_OXOX);
    }
    wrefresh(w_grid);

    crafting_inv = gm->crafting_inventory();

    int charges = ((it_tool *) g->itypes["welder"])->charges_per_use;
    has_wrench = crafting_inv.has_amount("wrench", 1) ||
                 crafting_inv.has_amount("toolset", 1);
    has_hacksaw = crafting_inv.has_amount("hacksaw", 1) ||
                  crafting_inv.has_amount("toolset", 1);
    has_welder = (crafting_inv.has_amount("welder", 1) &&
                  crafting_inv.has_charges("welder", charges)) ||
                 (crafting_inv.has_amount("toolset", 1) &&
                 crafting_inv.has_charges("toolset", charges/5));

    display_stats ();
    display_veh   ();
    move_cursor (0, 0);
    bool finish = false;
    while (!finish)
    {
        char ch = input(); // See keypress.h
        int dx, dy;
        get_direction (gm, dx, dy, ch);
        if (ch == KEY_ESCAPE)
            finish = true;
        else
        if (dx != -2 && (dx || dy) &&
            cx + dx >= -6 && cx + dx < 6 &&
            cy + dy >= -6 && cy + dy < 6)
            move_cursor(dx, dy);
        else
        {
            int mval = cant_do(ch);
            display_mode (ch);
            switch (ch)
            {
            case 'i': do_install(mval); break;
            case 'r': do_repair(mval);  break;
            case 'f': do_refill(mval);  break;
            case 'o': do_remove(mval);  break;
            case 'e': do_rename(mval);  break;
            default:;
            }
            if (sel_cmd != ' ')
                finish = true;
            display_mode (' ');
        }
    }
    werase(w_grid);
    werase(w_mode);
    werase(w_msg);
    werase(w_disp);
    werase(w_parts);
    werase(w_stats);
    werase(w_list);
    delwin(w_grid);
    delwin(w_mode);
    delwin(w_msg);
    delwin(w_disp);
    delwin(w_parts);
    delwin(w_stats);
    delwin(w_list);
    erase();
}
예제 #12
0
const recipe *select_crafting_recipe( int &batch_size )
{
    if( normalized_names.empty() ) {
        translate_all();
    }

    const int headHeight = 3;
    const int subHeadHeight = 2;
    const int freeWidth = TERMX - FULL_SCREEN_WIDTH;
    bool isWide = ( TERMX > FULL_SCREEN_WIDTH && freeWidth > 15 );

    const int width = isWide ? ( freeWidth > FULL_SCREEN_WIDTH ? FULL_SCREEN_WIDTH * 2 : TERMX ) :
                      FULL_SCREEN_WIDTH;
    const int wStart = ( TERMX - width ) / 2;
    const int tailHeight = isWide ? 3 : 4;
    const int dataLines = TERMY - ( headHeight + subHeadHeight ) - tailHeight;
    const int dataHalfLines = dataLines / 2;
    const int dataHeight = TERMY - ( headHeight + subHeadHeight );
    const int infoWidth = width - FULL_SCREEN_WIDTH - 1;

    int lastid = -1;

    WINDOW *w_head = newwin( headHeight, width, 0, wStart );
    WINDOW *w_subhead = newwin( subHeadHeight, width, 3, wStart );
    WINDOW *w_data = newwin( dataHeight, width, headHeight + subHeadHeight, wStart );

    int item_info_x = infoWidth;
    int item_info_y = dataHeight - 3;
    int item_info_width = wStart + width - infoWidth;
    int item_info_height = headHeight + subHeadHeight;

    if ( !isWide ) {
        item_info_x = 1;
        item_info_y = 1;
        item_info_width = 1;
        item_info_height = 1;
    }

    WINDOW *w_iteminfo = newwin( item_info_y, item_info_x, item_info_height, item_info_width );

    list_circularizer<std::string> tab( craft_cat_list );
    list_circularizer<std::string> subtab( craft_subcat_list[tab.cur()] );
    std::vector<const recipe *> current;
    std::vector<bool> available;
    std::vector<std::string> component_print_buffer;
    const int componentPrintHeight = dataHeight - tailHeight - 1;
    //preserves component color printout between mode rotations
    nc_color rotated_color = c_white;
    int previous_item_line = -1;
    std::string previous_tab = "";
    std::string previous_subtab = "";
    item tmp;
    int line = 0, ypos, scroll_pos = 0;
    bool redraw = true;
    bool keepline = false;
    bool done = false;
    bool batch = false;
    int batch_line = 0;
    int display_mode = 0;
    const recipe *chosen = NULL;
    std::vector<iteminfo> thisItem, dummy;

    input_context ctxt( "CRAFTING" );
    ctxt.register_cardinal();
    ctxt.register_action( "QUIT" );
    ctxt.register_action( "CONFIRM" );
    ctxt.register_action( "CYCLE_MODE" );
    ctxt.register_action( "SCROLL_UP" );
    ctxt.register_action( "SCROLL_DOWN" );
    ctxt.register_action( "PREV_TAB" );
    ctxt.register_action( "NEXT_TAB" );
    ctxt.register_action( "FILTER" );
    ctxt.register_action( "RESET_FILTER" );
    ctxt.register_action( "HELP_RECIPE" );
    ctxt.register_action( "HELP_KEYBINDINGS" );
    ctxt.register_action( "CYCLE_BATCH" );

    const inventory &crafting_inv = g->u.crafting_inventory();
    std::string filterstring = "";
    do {
        if( redraw ) {
            // When we switch tabs, redraw the header
            redraw = false;
            if( ! keepline ) {
                line = 0;
            } else {
                keepline = false;
            }

            if( display_mode > 2 ) {
                display_mode = 2;
            }

            TAB_MODE m = ( batch ) ? BATCH : ( filterstring == "" ) ? NORMAL : FILTERED;
            draw_recipe_tabs( w_head, tab.cur(), m );
            draw_recipe_subtabs( w_subhead, tab.cur(), subtab.cur(), m );
            current.clear();
            available.clear();
            if( batch ) {
                batch_recipes( crafting_inv, current, available, chosen );
            } else {
                // Set current to all recipes in the current tab; available are possible to make
                pick_recipes( crafting_inv, current, available, tab.cur(), subtab.cur(), filterstring );
            }
        }

        // Clear the screen of recipe data, and draw it anew
        werase( w_data );

        if ( isWide ) {
            werase( w_iteminfo );
        }

        if( isWide ) {
            mvwprintz( w_data, dataLines + 1, 5, c_white,
                       _( "Press <ENTER> to attempt to craft object." ) );
            wprintz( w_data, c_white, "  " );
            if( filterstring != "" ) {
                wprintz( w_data, c_white, _( "[E]: Describe, [F]ind, [R]eset, [m]ode, %s [?] keybindings" ),
                         ( batch ) ? _( "cancel [b]atch" ) : _( "[b]atch" ) );
            } else {
                wprintz( w_data, c_white, _( "[E]: Describe, [F]ind, [m]ode, %s [?] keybindings" ),
                         ( batch ) ? _( "cancel [b]atch" ) : _( "[b]atch" ) );
            }
        } else {
            if( filterstring != "" ) {
                mvwprintz( w_data, dataLines + 1, 5, c_white,
                           _( "[E]: Describe, [F]ind, [R]eset, [m]ode, [b]atch [?] keybindings" ) );
            } else {
                mvwprintz( w_data, dataLines + 1, 5, c_white,
                           _( "[E]: Describe, [F]ind, [m]ode, [b]atch [?] keybindings" ) );
            }
            mvwprintz( w_data, dataLines + 2, 5, c_white,
                       _( "Press <ENTER> to attempt to craft object." ) );
        }
        // Draw borders
        for( int i = 1; i < width - 1; ++i ) { // _
            mvwputch( w_data, dataHeight - 1, i, BORDER_COLOR, LINE_OXOX );
        }
        for( int i = 0; i < dataHeight - 1; ++i ) { // |
            mvwputch( w_data, i, 0, BORDER_COLOR, LINE_XOXO );
            mvwputch( w_data, i, width - 1, BORDER_COLOR, LINE_XOXO );
        }
        mvwputch( w_data, dataHeight - 1,  0, BORDER_COLOR, LINE_XXOO ); // _|
        mvwputch( w_data, dataHeight - 1, width - 1, BORDER_COLOR, LINE_XOOX ); // |_

        int recmin = 0, recmax = current.size();
        if( recmax > dataLines ) {
            if( line <= recmin + dataHalfLines ) {
                for( int i = recmin; i < recmin + dataLines; ++i ) {
                    std::string tmp_name = item::nname( current[i]->result );
                    if( batch ) {
                        tmp_name = string_format( _( "%2dx %s" ), i + 1, tmp_name.c_str() );
                    }
                    mvwprintz( w_data, i - recmin, 2, c_dkgray, "" ); // Clear the line
                    if( i == line ) {
                        mvwprintz( w_data, i - recmin, 2, ( available[i] ? h_white : h_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    } else {
                        mvwprintz( w_data, i - recmin, 2, ( available[i] ? c_white : c_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    }
                }
            } else if( line >= recmax - dataHalfLines ) {
                for( int i = recmax - dataLines; i < recmax; ++i ) {
                    std::string tmp_name = item::nname( current[i]->result );
                    if( batch ) {
                        tmp_name = string_format( _( "%2dx %s" ), i + 1, tmp_name.c_str() );
                    }
                    mvwprintz( w_data, dataLines + i - recmax, 2, c_ltgray, "" ); // Clear the line
                    if( i == line ) {
                        mvwprintz( w_data, dataLines + i - recmax, 2,
                                   ( available[i] ? h_white : h_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    } else {
                        mvwprintz( w_data, dataLines + i - recmax, 2,
                                   ( available[i] ? c_white : c_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    }
                }
            } else {
                for( int i = line - dataHalfLines; i < line - dataHalfLines + dataLines; ++i ) {
                    std::string tmp_name = item::nname( current[i]->result );
                    if( batch ) {
                        tmp_name = string_format( _( "%2dx %s" ), i + 1, tmp_name.c_str() );
                    }
                    mvwprintz( w_data, dataHalfLines + i - line, 2, c_ltgray, "" ); // Clear the line
                    if( i == line ) {
                        mvwprintz( w_data, dataHalfLines + i - line, 2,
                                   ( available[i] ? h_white : h_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    } else {
                        mvwprintz( w_data, dataHalfLines + i - line, 2,
                                   ( available[i] ? c_white : c_dkgray ),
                                   utf8_truncate( tmp_name, 28 ).c_str() );
                    }
                }
            }
        } else {
            for( size_t i = 0; i < current.size() && i < ( size_t )dataHeight + 1; ++i ) {
                std::string tmp_name = item::nname( current[i]->result );
                if( batch ) {
                    tmp_name = string_format( _( "%2dx %s" ), ( int )i + 1, tmp_name.c_str() );
                }
                if( ( int )i == line ) {
                    mvwprintz( w_data, i, 2, ( available[i] ? h_white : h_dkgray ),
                               utf8_truncate( tmp_name, 28 ).c_str() );
                } else {
                    mvwprintz( w_data, i, 2, ( available[i] ? c_white : c_dkgray ),
                               utf8_truncate( tmp_name, 28 ).c_str() );
                }
            }
        }
        if( !current.empty() ) {
            nc_color col = ( available[line] ? c_white : c_ltgray );
            ypos = 0;

            component_print_buffer = current[line]->requirements.get_folded_components_list(
                                         FULL_SCREEN_WIDTH - 30 - 1, col, crafting_inv, ( batch ) ? line + 1 : 1 );
            if( !g->u.knows_recipe( current[line] ) ) {
                component_print_buffer.push_back( _( "Recipe not memorized yet" ) );
            }

            //handle positioning of component list if it needed to be scrolled
            int componentPrintOffset = 0;
            if( display_mode > 2 ) {
                componentPrintOffset = ( display_mode - 2 ) * componentPrintHeight;
            }
            if( component_print_buffer.size() < static_cast<size_t>( componentPrintOffset ) ) {
                componentPrintOffset = 0;
                if( previous_tab != tab.cur() || previous_subtab != subtab.cur() || previous_item_line != line ) {
                    display_mode = 2;
                } else {
                    display_mode = 0;
                }
            }

            //only used to preserve mode position on components when
            //moving to another item and the view is already scrolled
            previous_tab = tab.cur();
            previous_subtab = subtab.cur();
            previous_item_line = line;

            if( display_mode == 0 ) {
                mvwprintz( w_data, ypos++, 30, col, _( "Skills used: %s" ),
                           ( !current[line]->skill_used ? _( "N/A" ) :
                             current[line]->skill_used.obj().name().c_str() ) );

                mvwprintz( w_data, ypos++, 30, col, _( "Required skills: %s" ),
                           ( current[line]->required_skills_string().c_str() ) );
                mvwprintz( w_data, ypos++, 30, col, _( "Difficulty: %d" ), current[line]->difficulty );
                if( !current[line]->skill_used ) {
                    mvwprintz( w_data, ypos++, 30, col, _( "Your skill level: N/A" ) );
                } else {
                    mvwprintz( w_data, ypos++, 30, col, _( "Your skill level: %d" ),
                               // Macs don't seem to like passing this as a class, so force it to int
                               ( int )g->u.skillLevel( current[line]->skill_used ) );
                }
                ypos += current[line]->print_time( w_data, ypos, 30, FULL_SCREEN_WIDTH - 30 - 1, col,
                                                   ( batch ) ? line + 1 : 1 );
                ypos += current[line]->print_items( w_data, ypos, 30, col, ( batch ) ? line + 1 : 1 );
            }
            if( display_mode == 0 || display_mode == 1 ) {
                ypos += current[line]->requirements.print_tools(
                            w_data, ypos, 30, FULL_SCREEN_WIDTH - 30 - 1, col,
                            crafting_inv, ( batch ) ? line + 1 : 1 );
            }

            //color needs to be preserved in case part of the previous page was cut off
            nc_color stored_color = col;
            if( display_mode > 2 ) {
                stored_color = rotated_color;
            } else {
                rotated_color = col;
            }
            int components_printed = 0;
            for( size_t i = static_cast<size_t>( componentPrintOffset );
                 i < component_print_buffer.size(); i++ ) {
                if( ypos >= componentPrintHeight ) {
                    break;
                }

                components_printed++;
                print_colored_text( w_data, ypos++, 30, stored_color, col, component_print_buffer[i] );
            }

            if( ypos >= componentPrintHeight &&
                component_print_buffer.size() > static_cast<size_t>( components_printed ) ) {
                mvwprintz( w_data, ypos++, 30, col, _( "v (more)" ) );
                rotated_color = stored_color;
            }

            if( isWide ) {
                if( lastid != current[line]->id ) {
                    lastid = current[line]->id;
                    tmp = current[line]->create_result();
                    tmp.info(true, thisItem);
                }
                draw_item_info(w_iteminfo, tmp.tname(), tmp.type_name(), thisItem, dummy,
                               scroll_pos, true, true, true, false, true);
            }
        }

        draw_scrollbar( w_data, line, dataLines, recmax, 0 );
        wrefresh( w_data );

        if ( isWide ) {
            wrefresh( w_iteminfo );
        }

        const std::string action = ctxt.handle_input();
        if( action == "CYCLE_MODE" ) {
            display_mode = display_mode + 1;
            if( display_mode <= 0 ) {
                display_mode = 0;
            }
        } else if( action == "LEFT" ) {
            subtab.prev();
            redraw = true;
        } else if( action == "SCROLL_UP" ) {
            scroll_pos--;
        } else if( action == "SCROLL_DOWN" ) {
            scroll_pos++;
        } else if( action == "PREV_TAB" ) {
            tab.prev();
            subtab = list_circularizer<std::string>( craft_subcat_list[tab.cur()] );//default ALL
            redraw = true;
        } else if( action == "RIGHT" ) {
            subtab.next();
            redraw = true;
        } else if( action == "NEXT_TAB" ) {
            tab.next();
            subtab = list_circularizer<std::string>( craft_subcat_list[tab.cur()] );//default ALL
            redraw = true;
        } else if( action == "DOWN" ) {
            line++;
        } else if( action == "UP" ) {
            line--;
        } else if( action == "CONFIRM" ) {
            if( available.empty() || !available[line] ) {
                popup( _( "You can't do that!" ) );
            } else if( !current[line]->check_eligible_containers_for_crafting( ( batch ) ? line + 1 : 1 ) ) {
                ; // popup is already inside check
            } else {
                chosen = current[line];
                batch_size = ( batch ) ? line + 1 : 1;
                done = true;
            }
        } else if( action == "HELP_RECIPE" ) {
            if( current.empty() ) {
                popup( _( "Nothing selected!" ) );
                redraw = true;
                continue;
            }
            tmp = current[line]->create_result();

            full_screen_popup( "%s\n%s", tmp.type_name( 1 ).c_str(),  tmp.info( true ).c_str() );
            redraw = true;
            keepline = true;
        } else if( action == "FILTER" ) {
            filterstring = string_input_popup( _( "Search:" ), 85, filterstring,
                                               _( "Special prefixes for requirements:\n"
                                                  "  [t] search tools\n"
                                                  "  [c] search components\n"
                                                  "  [q] search qualities\n"
                                                  "  [s] search skills\n"
                                                  "  [S] search skill used only\n"
                                                  "Special prefixes for results:\n"
                                                  "  [Q] search qualities\n"
                                                  "Examples:\n"
                                                  "  t:soldering iron\n"
                                                  "  c:two by four\n"
                                                  "  q:metal sawing\n"
                                                  "  s:cooking\n"
                                                  "  Q:fine bolt turning"
                                                ) );
            redraw = true;
        } else if( action == "QUIT" ) {
            chosen = nullptr;
            done = true;
        } else if( action == "RESET_FILTER" ) {
            filterstring = "";
            redraw = true;
        } else if( action == "CYCLE_BATCH" ) {
            if( current.empty() ) {
                popup( _( "Nothing selected!" ) );
                redraw = true;
                continue;
            }
            batch = !batch;
            if( batch ) {
                batch_line = line;
                chosen = current[batch_line];
            } else {
                line = batch_line;
                keepline = true;
            }
            redraw = true;
        }
        if( line < 0 ) {
            line = current.size() - 1;
        } else if( line >= ( int )current.size() ) {
            line = 0;
        }
    } while( !done );

    werase( w_head );
    werase( w_subhead );
    werase( w_data );
    delwin( w_head );
    delwin( w_subhead );
    delwin( w_data );
    g->refresh_all();

    return chosen;
}
예제 #13
0
파일: checklist.c 프로젝트: 16rd/rt-n56u
/*
 * Display a dialog box with a list of options that can be turned on or off
 * in the style of radiolist (only one option turned on at a time).
 */
int dialog_checklist(const char *title, const char *prompt, int height,
		     int width, int list_height)
{
	int i, x, y, box_x, box_y;
	int key = 0, button = 0, choice = 0, scroll = 0, max_choice;
	WINDOW *dialog, *list;

	/* which item to highlight */
	item_foreach() {
		if (item_is_tag('X'))
			choice = item_n();
		if (item_is_selected()) {
			choice = item_n();
			break;
		}
	}

do_resize:
	if (getmaxy(stdscr) < (height + 6))
		return -ERRDISPLAYTOOSMALL;
	if (getmaxx(stdscr) < (width + 6))
		return -ERRDISPLAYTOOSMALL;

	max_choice = MIN(list_height, item_count());

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

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

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

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

	print_title(dialog, title, width);

	wattrset(dialog, dlg.dialog.atr);
	print_autowrap(dialog, prompt, width - 2, 1, 3);

	list_width = width - 6;
	box_y = height - list_height - 5;
	box_x = (width - list_width) / 2 - 1;

	/* create new window for the list */
	list = subwin(dialog, list_height, list_width, y + box_y + 1,
	              x + box_x + 1);

	keypad(list, TRUE);

	/* draw a box around the list items */
	draw_box(dialog, box_y, box_x, list_height + 2, list_width + 2,
	         dlg.menubox_border.atr, dlg.menubox.atr);

	/* Find length of longest item in order to center checklist */
	check_x = 0;
	item_foreach()
		check_x = MAX(check_x, strlen(item_str()) + 4);

	check_x = (list_width - check_x) / 2;
	item_x = check_x + 4;

	if (choice >= list_height) {
		scroll = choice - list_height + 1;
		choice -= scroll;
	}

	/* Print the list */
	for (i = 0; i < max_choice; i++) {
		item_set(scroll + i);
		print_item(list, i, i == choice);
	}

	print_arrows(dialog, choice, item_count(), scroll,
		     box_y, box_x + check_x + 5, list_height);

	print_buttons(dialog, height, width, 0);

	wnoutrefresh(dialog);
	wnoutrefresh(list);
	doupdate();

	while (key != KEY_ESC) {
		key = wgetch(dialog);

		for (i = 0; i < max_choice; i++) {
			item_set(i + scroll);
			if (toupper(key) == toupper(item_str()[0]))
				break;
		}

		if (i < max_choice || key == KEY_UP || key == KEY_DOWN ||
		    key == '+' || key == '-') {
			if (key == KEY_UP || key == '-') {
				if (!choice) {
					if (!scroll)
						continue;
					/* Scroll list down */
					if (list_height > 1) {
						/* De-highlight current first item */
						item_set(scroll);
						print_item(list, 0, FALSE);
						scrollok(list, TRUE);
						wscrl(list, -1);
						scrollok(list, FALSE);
					}
					scroll--;
					item_set(scroll);
					print_item(list, 0, TRUE);
					print_arrows(dialog, choice, item_count(),
						     scroll, box_y, box_x + check_x + 5, list_height);

					wnoutrefresh(dialog);
					wrefresh(list);

					continue;	/* wait for another key press */
				} else
					i = choice - 1;
			} else if (key == KEY_DOWN || key == '+') {
				if (choice == max_choice - 1) {
					if (scroll + choice >= item_count() - 1)
						continue;
					/* Scroll list up */
					if (list_height > 1) {
						/* De-highlight current last item before scrolling up */
						item_set(scroll + max_choice - 1);
						print_item(list,
							    max_choice - 1,
							    FALSE);
						scrollok(list, TRUE);
						wscrl(list, 1);
						scrollok(list, FALSE);
					}
					scroll++;
					item_set(scroll + max_choice - 1);
					print_item(list, max_choice - 1, TRUE);

					print_arrows(dialog, choice, item_count(),
						     scroll, box_y, box_x + check_x + 5, list_height);

					wnoutrefresh(dialog);
					wrefresh(list);

					continue;	/* wait for another key press */
				} else
					i = choice + 1;
			}
			if (i != choice) {
				/* De-highlight current item */
				item_set(scroll + choice);
				print_item(list, choice, FALSE);
				/* Highlight new item */
				choice = i;
				item_set(scroll + choice);
				print_item(list, choice, TRUE);
				wnoutrefresh(dialog);
				wrefresh(list);
			}
			continue;	/* wait for another key press */
		}
		switch (key) {
		case 'H':
		case 'h':
		case '?':
			button = 1;
			/* fall-through */
		case 'S':
		case 's':
		case ' ':
		case '\n':
			item_foreach()
				item_set_selected(0);
			item_set(scroll + choice);
			item_set_selected(1);
			delwin(list);
			delwin(dialog);
			return button;
		case TAB:
		case KEY_LEFT:
		case KEY_RIGHT:
			button = ((key == KEY_LEFT ? --button : ++button) < 0)
			    ? 1 : (button > 1 ? 0 : button);

			print_buttons(dialog, height, width, button);
			wrefresh(dialog);
			break;
		case 'X':
		case 'x':
			key = KEY_ESC;
			break;
		case KEY_ESC:
			key = on_key_esc(dialog);
			break;
		case KEY_RESIZE:
			delwin(list);
			delwin(dialog);
			on_key_resize();
			goto do_resize;
		}

		/* Now, update everything... */
		doupdate();
	}
	delwin(list);
	delwin(dialog);
	return key;		/* ESC pressed */
}
예제 #14
0
getwin(FILE * filep)
{
    WINDOW tmp, *nwin;
    int n;

    T((T_CALLED("getwin(%p)"), filep));

    clearerr(filep);
    (void) fread(&tmp, sizeof(WINDOW), 1, filep);
    if (ferror(filep))
	returnWin(0);

    if (tmp._flags & _ISPAD) {
	nwin = newpad(tmp._maxy + 1, tmp._maxx + 1);
    } else {
	nwin = newwin(tmp._maxy + 1, tmp._maxx + 1, 0, 0);
    }

    /*
     * We deliberately do not restore the _parx, _pary, or _parent
     * fields, because the window hierarchy within which they
     * made sense is probably gone.
     */
    if (nwin != 0) {
	nwin->_curx = tmp._curx;
	nwin->_cury = tmp._cury;
	nwin->_maxy = tmp._maxy;
	nwin->_maxx = tmp._maxx;
	nwin->_begy = tmp._begy;
	nwin->_begx = tmp._begx;
	nwin->_yoffset = tmp._yoffset;
	nwin->_flags = tmp._flags & ~(_SUBWIN);

	nwin->_attrs = tmp._attrs;
	nwin->_nc_bkgd = tmp._nc_bkgd;

	nwin->_notimeout = tmp._notimeout;
	nwin->_clear = tmp._clear;
	nwin->_leaveok = tmp._leaveok;
	nwin->_idlok = tmp._idlok;
	nwin->_idcok = tmp._idcok;
	nwin->_immed = tmp._immed;
	nwin->_scroll = tmp._scroll;
	nwin->_sync = tmp._sync;
	nwin->_use_keypad = tmp._use_keypad;
	nwin->_delay = tmp._delay;

	nwin->_regtop = tmp._regtop;
	nwin->_regbottom = tmp._regbottom;

	if (tmp._flags & _ISPAD)
	    nwin->_pad = tmp._pad;

	for (n = 0; n <= nwin->_maxy; n++) {
	    clearerr(filep);
	    (void) fread(nwin->_line[n].text,
			 sizeof(NCURSES_CH_T),
			 (size_t) (nwin->_maxx + 1),
			 filep);
	    if (ferror(filep)) {
		delwin(nwin);
		returnWin(0);
	    }
	}
	touchwin(nwin);
    }
    returnWin(nwin);
}
예제 #15
0
void npc::talk_to_u(game *g)
{
    if (attitude == NPCATT_TALK)
        attitude = NPCATT_NULL;
    dialogue d;
    d.alpha = &g->u;
    d.beta = this;

    d.topic_stack.push_back(chatbin.first_topic);

    if (is_friend())
        d.topic_stack.push_back(TALK_FRIEND);

    int most_difficult_mission = 0;
    for (int i = 0; i < chatbin.missions.size(); i++) {
        mission_type *type = g->find_mission_type(chatbin.missions[i]);
        if (type->urgent && type->difficulty > most_difficult_mission) {
            d.topic_stack.push_back(TALK_MISSION_DESCRIBE);
            chatbin.mission_selected = i;
            most_difficult_mission = type->difficulty;
        }
    }
    most_difficult_mission = 0;
    bool chosen_urgent = false;
    for (int i = 0; i < chatbin.missions_assigned.size(); i++) {
        mission_type *type = g->find_mission_type(chatbin.missions_assigned[i]);
        if ((type->urgent && !chosen_urgent) ||
                (type->difficulty > most_difficult_mission &&
                 (type->urgent || !chosen_urgent)            )) {
            chosen_urgent = type->urgent;
            d.topic_stack.push_back(TALK_MISSION_INQUIRE);
            chatbin.mission_selected = i;
            most_difficult_mission = type->difficulty;
        }
    }

    if (d.topic_stack.back() == TALK_NONE) {
        g->add_msg(_("%s says, \"Leave me alone.\""), name.c_str());
        return;
    }

    moves -= 100;
    decide_needs();


    d.win = newwin(25, 80, 0, 0);
    wborder(d.win, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX,
            LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX );
    for (int i = 1; i < 24; i++)
        mvwputch(d.win, i, 41, c_ltgray, LINE_XOXO);
    mvwputch(d.win,  0, 41, c_ltgray, LINE_OXXX);
    mvwputch(d.win, 24, 41, c_ltgray, LINE_XXOX);
    mvwprintz(d.win, 1,  1, c_white, _("Dialogue with %s"), name.c_str());
    mvwprintz(d.win, 1, 43, c_white, _("Your response:"));

// Main dialogue loop
    do {
        talk_topic next = d.opt(d.topic_stack.back(), g);
        if (next == TALK_NONE) {
            int cat = topic_category(d.topic_stack.back());
            do
                d.topic_stack.pop_back();
            while (cat != -1 && topic_category(d.topic_stack.back()) == cat);
        }
        if (next == TALK_DONE || d.topic_stack.empty())
            d.done = true;
        else if (next != TALK_NONE)
            d.topic_stack.push_back(next);
    } while (!d.done);
    delwin(d.win);
    g->refresh_all();
}
예제 #16
0
CWindows::~CWindows()
{
	delwin(m_this);
}
예제 #17
0
void curses_line_input_dialog(const char *prompt, char *answer, int buffer)
{
    int map_height, map_width, maxwidth, remaining_buf, winx, winy, count;
    WINDOW *askwin, *bwin;
    char input[buffer];
    char *tmpstr;
    int prompt_width = strlen(prompt) + buffer + 1;
    int prompt_height = 1;
    int height = prompt_height;

    maxwidth = term_cols - 2;

    if (iflags.window_inited) {
        curses_get_window_size(MAP_WIN, &map_height, &map_width);
        if ((prompt_width + 2) > map_width)
            maxwidth = map_width - 2;
    }

    if (prompt_width > maxwidth) {
        prompt_height = curses_num_lines(prompt, maxwidth);
        height = prompt_height;
        prompt_width = maxwidth;
        tmpstr = curses_break_str(prompt, maxwidth, prompt_height);
        remaining_buf = buffer - (strlen(tmpstr) - 1);
        if (remaining_buf > 0 ) {
            height += (remaining_buf / prompt_width);
            if ((remaining_buf % prompt_width) > 0) {
                height++;
            }
        }
    }

    if (iflags.window_inited) {
        bwin = curses_create_window(prompt_width, height, UP);
        wrefresh(bwin);
        getbegyx(bwin, winy, winx);
        askwin = newwin(height, prompt_width, winy + 1, winx + 1);
    } else {
        bwin = curses_create_window(prompt_width, height, CENTER);
        wrefresh(bwin);
        getbegyx(bwin, winy, winx);
        askwin = newwin(height, prompt_width, winy + 1, winx + 1);
    }
    for (count = 0; count < prompt_height; count++) {
        tmpstr = curses_break_str(prompt, maxwidth, count + 1);
        if (count == (prompt_height - 1)) {  /* Last line */
            mvwprintw(askwin, count, 0, "%s ", tmpstr);
        } else {
            mvwaddstr(askwin, count, 0, tmpstr);
        }
        free(tmpstr);
    }

    echo();
    curs_set(1);
    wgetnstr(askwin, input, buffer-1);
    curs_set(0);
    strcpy(answer, input);
    werase(bwin);
    delwin(bwin);
    curses_destroy_win(askwin);
    noecho();
}
예제 #18
0
파일: menubox.c 프로젝트: VargMon/dd-wrt
/*
 * Display a menu for choosing among a number of options
 */
int
dialog_menu (const char *title, const char *prompt, int height, int width,
		int menu_height, const char *current, int item_no,
		struct dialog_list_item ** items)
{
    int i, j, x, y, box_x, box_y;
    int key = 0, button = 0, scroll = 0, choice = 0, first_item = 0, max_choice;
    WINDOW *dialog, *menu;
    FILE *f;

    max_choice = MIN (menu_height, item_no);

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

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

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

    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);
    wattrset (dialog, border_attr);
    mvwaddch (dialog, height - 3, 0, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
	waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    wbkgdset (dialog, dialog_attr & A_COLOR);
    waddch (dialog, ACS_RTEE);

    if (title != NULL && strlen(title) >= width-2 ) {
	/* truncate long title -- mec */
	char * title2 = malloc(width-2+1);
	memcpy( title2, title, width-2 );
	title2[width-2] = '\0';
	title = title2;
    }

    if (title != NULL) {
	wattrset (dialog, title_attr);
	mvwaddch (dialog, 0, (width - strlen(title))/2 - 1, ' ');
	waddstr (dialog, (char *)title);
	waddch (dialog, ' ');
    }

    wattrset (dialog, dialog_attr);
    print_autowrap (dialog, prompt, width - 2, 1, 3);

    menu_width = width - 6;
    box_y = height - menu_height - 5;
    box_x = (width - menu_width) / 2 - 1;

    /* create new window for the menu */
    menu = subwin (dialog, menu_height, menu_width,
		y + box_y + 1, x + box_x + 1);
    keypad (menu, TRUE);

    /* draw a box around the menu items */
    draw_box (dialog, box_y, box_x, menu_height + 2, menu_width + 2,
	      menubox_border_attr, menubox_attr);

    /*
     * Find length of longest item in order to center menu.
     * Set 'choice' to default item. 
     */
    item_x = 0;
    for (i = 0; i < item_no; i++) {
	item_x = MAX (item_x, MIN(menu_width, strlen (items[i]->name) + 2));
	if (strcmp(current, items[i]->tag) == 0) choice = i;
    }

    item_x = (menu_width - item_x) / 2;

    /* get the scroll info from the temp file */
    if ( (f=fopen("lxdialog.scrltmp","r")) != NULL ) {
	if ( (fscanf(f,"%d\n",&scroll) == 1) && (scroll <= choice) &&
	     (scroll+max_choice > choice) && (scroll >= 0) &&
	     (scroll+max_choice <= item_no) ) {
	    first_item = scroll;
	    choice = choice - scroll;
	    fclose(f);
	} else {
	    scroll=0;
	    remove("lxdialog.scrltmp");
	    fclose(f);
	    f=NULL;
	}
    }
    if ( (choice >= max_choice) || (f==NULL && choice >= max_choice/2) ) {
	if (choice >= item_no-max_choice/2)
	    scroll = first_item = item_no-max_choice;
	else
	    scroll = first_item = choice - max_choice/2;
	choice = choice - scroll;
    }

    /* Print the menu */
    for (i=0; i < max_choice; i++) {
	print_item (menu, items[first_item + i]->name, i, i == choice,
                    (items[first_item + i]->tag[0] != ':'));
    }

    wnoutrefresh (menu);

    print_arrows(dialog, item_no, scroll,
		 box_y, box_x+item_x+1, menu_height);

    print_buttons (dialog, height, width, 0);
    wmove (menu, choice, item_x+1);
    wrefresh (menu);

    while (key != ESC) {
	key = wgetch(menu);

	if (key < 256 && isalpha(key)) key = tolower(key);

	if (strchr("ynm", key))
		i = max_choice;
	else {
        for (i = choice+1; i < max_choice; i++) {
		j = first_alpha(items[scroll + i]->name, "YyNnMm>");
		if (key == tolower(items[scroll + i]->name[j]))
                	break;
	}
	if (i == max_choice)
       		for (i = 0; i < max_choice; i++) {
			j = first_alpha(items[scroll + i]->name, "YyNnMm>");
			if (key == tolower(items[scroll + i]->name[j]))
                		break;
		}
	}

	if (i < max_choice || 
            key == KEY_UP || key == KEY_DOWN ||
            key == '-' || key == '+' ||
            key == KEY_PPAGE || key == KEY_NPAGE) {

            print_item (menu, items[scroll + choice]->name, choice, FALSE,
                       (items[scroll + choice]->tag[0] != ':'));

	    if (key == KEY_UP || key == '-') {
                if (choice < 2 && scroll) {
	            /* Scroll menu down */
                    scrollok (menu, TRUE);
                    wscrl (menu, -1);
                    scrollok (menu, FALSE);

                    scroll--;

                    print_item (menu, items[scroll]->name, 0, FALSE,
                               (items[scroll]->tag[0] != ':'));
		} else
		    choice = MAX(choice - 1, 0);

	    } else if (key == KEY_DOWN || key == '+')  {

		print_item (menu, items[scroll + choice]->name, choice, FALSE,
                                (items[scroll + choice]->tag[0] != ':'));

                if ((choice > max_choice-3) &&
                    (scroll + max_choice < item_no)
                   ) {
		    /* Scroll menu up */
		    scrollok (menu, TRUE);
                    scroll (menu);
                    scrollok (menu, FALSE);

                    scroll++;

                    print_item (menu, items[scroll + max_choice - 1]->name,
                               max_choice-1, FALSE,
                               (items[scroll + max_choice - 1]->tag[0] != ':'));
                } else
                    choice = MIN(choice+1, max_choice-1);

	    } else if (key == KEY_PPAGE) {
	        scrollok (menu, TRUE);
                for (i=0; (i < max_choice); i++) {
                    if (scroll > 0) {
                	wscrl (menu, -1);
                	scroll--;
                	print_item (menu, items[scroll]->name, 0, FALSE,
                	(items[scroll]->tag[0] != ':'));
                    } else {
                        if (choice > 0)
                            choice--;
                    }
                }
                scrollok (menu, FALSE);

            } else if (key == KEY_NPAGE) {
                for (i=0; (i < max_choice); i++) {
                    if (scroll+max_choice < item_no) {
			scrollok (menu, TRUE);
			scroll(menu);
			scrollok (menu, FALSE);
                	scroll++;
                	print_item (menu, items[scroll + max_choice - 1]->name,
			            max_choice-1, FALSE,
			            (items[scroll + max_choice - 1]->tag[0] != ':'));
		    } else {
			if (choice+1 < max_choice)
			    choice++;
		    }
                }

            } else
                choice = i;

            print_item (menu, items[scroll + choice]->name, choice, TRUE,
                       (items[scroll + choice]->tag[0] != ':'));

            print_arrows(dialog, item_no, scroll,
                         box_y, box_x+item_x+1, menu_height);

            wnoutrefresh (dialog);
            wrefresh (menu);

	    continue;		/* wait for another key press */
        }

	switch (key) {
	case KEY_LEFT:
	case TAB:
	case KEY_RIGHT:
	    button = ((key == KEY_LEFT ? --button : ++button) < 0)
			? 2 : (button > 2 ? 0 : button);

	    print_buttons(dialog, height, width, button);
	    wrefresh (menu);
	    break;
	case ' ':
	case 's':
	case 'y':
	case 'n':
	case 'm':
	    /* save scroll info */
	    if ( (f=fopen("lxdialog.scrltmp","w")) != NULL ) {
		fprintf(f,"%d\n",scroll);
		fclose(f);
	    }
	    delwin (dialog);
            items[scroll + choice]->selected = 1;
            switch (key) {
            case 's': return 3;
            case 'y': return 3;
            case 'n': return 4;
            case 'm': return 5;
            case ' ': return 6;
            }
	    return 0;
	case 'h':
	case '?':
	    button = 2;
	case '\n':
	    delwin (dialog);
	    items[scroll + choice]->selected = 1;

	    remove("lxdialog.scrltmp");
	    return button;
	case 'e':
	case 'x':
	    key = ESC;
	case ESC:
	    break;
	}
    }

    delwin (dialog);
    remove("lxdialog.scrltmp");
    return -1;			/* ESC pressed */
}
예제 #19
0
파일: yesno.c 프로젝트: 0919061/PX4NuttX
/*
 * Display a dialog box with two buttons - Yes and No
 */
int dialog_yesno(const char *title, const char *prompt, int height, int width)
{
	int i, x, y, key = 0, button = 0;
	WINDOW *dialog;

do_resize:
	if (getmaxy(stdscr) < (height + 4))
		return -ERRDISPLAYTOOSMALL;
	if (getmaxx(stdscr) < (width + 4))
		return -ERRDISPLAYTOOSMALL;

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

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

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

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

	print_title(dialog, title, width);

	wattrset(dialog, dlg.dialog.atr);
	print_autowrap(dialog, prompt, width - 2, 1, 3);

	print_buttons(dialog, height, width, 0);

	while (key != KEY_ESC) {
		key = wgetch(dialog);
		switch (key) {
		case 'Y':
		case 'y':
			delwin(dialog);
			return 0;
		case 'N':
		case 'n':
			delwin(dialog);
			return 1;

		case TAB:
		case KEY_LEFT:
		case KEY_RIGHT:
			button = ((key == KEY_LEFT ? --button : ++button) < 0) ? 1 : (button > 1 ? 0 : button);

			print_buttons(dialog, height, width, button);
			wrefresh(dialog);
			break;
		case ' ':
		case '\n':
			delwin(dialog);
			return button;
		case KEY_ESC:
			key = on_key_esc(dialog);
			break;
		case KEY_RESIZE:
			delwin(dialog);
			on_key_resize();
			goto do_resize;
		}
	}

	delwin(dialog);
	return key;		/* ESC pressed */
}
예제 #20
0
char game::inv_type(std::string title, item_cat inv_item_type)
{
// this function lists inventory objects by type
// refer to enum item_cat in itype.h for list of categories

 WINDOW* w_inv = newwin(((VIEWY < 12) ? 25 : VIEWY*2+1), ((VIEWX < 12) ? FULL_SCREEN_WIDTH : VIEWX*2+56), VIEW_OFFSET_Y, VIEW_OFFSET_X);
 const int maxitems = (VIEWY < 12) ? 20 : VIEWY*2-4;    // Number of items to show at one time.
 int ch = (int)'.';
 int start = 0, cur_it = 0, max_it;
 u.inv.sort();
 u.inv.restack(&u);
 std::vector<char> null_vector;
 print_inv_statics(this, w_inv, title, null_vector);
// Gun, ammo, weapon, armor, food, tool, book, other

// Create the reduced inventory
 inventory reduced_inv = u.inv.filter_by_category(inv_item_type, u);

 invslice slice = reduced_inv.slice(0, reduced_inv.size());
 std::vector<int> firsts = find_firsts(slice);

 int selected=-1;
 int selected_char=(int)' ';
 do {
  if (( ch == '<' || ch == KEY_PPAGE ) && start > 0) { // Clear lines and shift
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
   start -= maxitems;
   if (start < 0)
    start = 0;
   mvwprintw(w_inv, maxitems + 4, 0, "         ");
   if ( selected > -1 ) selected = start; // oy, the cheese
  }
  if (( ch == '>' || ch == KEY_NPAGE ) && cur_it < reduced_inv.size()) { // Clear lines and shift
   start = cur_it;
   mvwprintw(w_inv, maxitems + 4, 12, "            ");
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
   if ( selected < start && selected > -1 ) selected = start;
  }
  int cur_line = 2;
  max_it = 0;
  for (cur_it = start; cur_it < start + maxitems && cur_line < maxitems+3; cur_it++) {
// Clear the current line;
   mvwprintw(w_inv, cur_line, 0, "                                             ");

   for (int i = 1; i < iCategorieNum; i++) {
    if (cur_it == firsts[i-1]) {
     mvwprintz(w_inv, cur_line, 0, c_magenta, _(CATEGORIES[i].c_str()));
     cur_line++;
    }
   }

   if (cur_it < slice.size())
   {
    item& it = slice[cur_it]->front();
    if(cur_it==selected) selected_char=(int)it.invlet;
    mvwputch (w_inv, cur_line, 0, (cur_it == selected ? h_white : c_white), it.invlet);
    mvwprintz(w_inv, cur_line, 1, (cur_it == selected ? h_white : it.color_in_inventory(&u) ), " %s",
              it.tname(this).c_str());
    if (slice[cur_it]->size() > 1)
     wprintw(w_inv, " [%d]", slice[cur_it]->size());
    if (it.charges > 0)
     wprintw(w_inv, " (%d)", it.charges);
    else if (it.contents.size() == 1 &&
             it.contents[0].charges > 0)
     wprintw(w_inv, " (%d)", it.contents[0].charges);
    cur_line++;
    max_it=cur_it;
   }
//   cur_line++;
  }
  if (start > 0)
   mvwprintw(w_inv, maxitems + 4, 0, _("< Go Back"));
  if (cur_it < reduced_inv.size())
   mvwprintw(w_inv, maxitems + 4, 12, _("> More items"));
  wrefresh(w_inv);

  ch = getch();

  if ( ch == KEY_DOWN ) {
    if ( selected < 0 ) {
      selected = start;
    } else {
      selected++;
    }
    if ( selected > max_it ) {
      if( cur_it < u.inv.size() ) {
        ch='>';
      } else {
        selected = u.inv.size() - 1; // wraparound?
      }
    }
  } else if ( ch == KEY_UP ) {
    selected--;
    if ( selected < -1 ) {
      selected = -1; // wraparound?
    } else if ( selected < start ) {
      if ( start > 0 ) {
        for (int i = 1; i < maxitems+4; i++)
         mvwprintz(w_inv, i, 0, c_black, "                                             ");
        start -= maxitems;
        if (start < 0)
         start = 0;
        mvwprintw(w_inv, maxitems + 4, 0, "         ");
      }
    }
  } else if ( ch == '\n' || ch == KEY_RIGHT ) {
    ch = selected_char;
  }

 } while (ch == '<' || ch == '>' || ch == KEY_NPAGE || ch == KEY_PPAGE || ch == KEY_UP || ch == KEY_DOWN );
 werase(w_inv);
 delwin(w_inv);
 erase();
 refresh_all();
 return (char)ch;
}
예제 #21
0
Window::~Window()
{
  delwin(p->win);
  delete p;
}
예제 #22
0
std::vector<item> game::multidrop()
{
 u.inv.sort();
 u.inv.restack(&u);
 WINDOW* w_inv = newwin(((VIEWY < 12) ? 25 : VIEWY*2+1), ((VIEWX < 12) ? FULL_SCREEN_WIDTH : VIEWX*2+56), VIEW_OFFSET_Y, VIEW_OFFSET_X);
 int drp_line_width=getmaxx(w_inv)-90;
 const std::string drp_line_padding = ( drp_line_width > 1 ? std::string(drp_line_width, ' ') : " ");
 const int maxitems = (VIEWY < 12) ? 20 : VIEWY*2-4;    // Number of items to show at one time.
 std::map<char, int> dropping; // Count of how many we'll drop from each stack
 int count = 0; // The current count
 std::vector<char> weapon_and_armor; // Always single, not counted
 bool warned_about_bionic = false; // Printed add_msg re: dropping bionics
 print_inv_statics(this, w_inv, _("Multidrop:"), weapon_and_armor);
 int base_weight = u.weight_carried();
 int base_volume = u.volume_carried();

 int ch = (int)'.';
 int start = 0, cur_it = 0, max_it;
 invslice stacks = u.inv.slice(0, u.inv.size());
 std::vector<int> firsts = find_firsts(stacks);
 int selected=-1;
 int selected_char=(int)' ';
 do {
  inventory drop_subset = u.inv.subset(dropping);
  int new_weight = base_weight - drop_subset.weight();
  int new_volume = base_volume - drop_subset.volume();
  for (int i = 0; i < weapon_and_armor.size(); ++i) {
   new_weight -= u.i_at(weapon_and_armor[i]).weight();
  }
  print_inv_weight_vol(this, w_inv, new_weight, new_volume);
  int cur_line = 2;
  max_it = 0;
  int drp_line = 1;
  // Print weapon to be dropped, the first position is reserved for high visibility
  mvwprintw(w_inv, 0, 90, "%s", drp_line_padding.c_str());
  bool dropping_w = false;
  for (int k = 0; k < weapon_and_armor.size() && !dropping_w; k++) {
    if (weapon_and_armor[k] == u.weapon.invlet) {
      dropping_w = true;
    }
    if (dropping_w && u.is_armed()) {
      mvwprintz(w_inv, 0, 90, c_ltblue, "%c + %s", u.weapon.invlet, u.weapname().c_str());
    }
  }
  // Print worn items to be dropped
  if(dropping_w) {
    mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
    drp_line++;
  }
  bool dropping_a = false;
  if (u.worn.size() > 0){
    for (int k = 0; k < u.worn.size(); k++) {
      bool dropping_w = false;
      for (int j = 0; j < weapon_and_armor.size() && !dropping_w; j++) {
        if (weapon_and_armor[j] == u.worn[k].invlet) {
          dropping_w = true;
          dropping_a = true;
          mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
          mvwprintz(w_inv, drp_line, 90, c_cyan, "%c + %s", u.worn[k].invlet, u.worn[k].tname(this).c_str());
          drp_line++;
        }
      }
    }
  }
  if(dropping_a) {
    mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
    drp_line++;
  }
  for (cur_it = start; cur_it < start + maxitems && cur_line < maxitems+3; cur_it++) {
// Clear the current line;
   mvwprintw(w_inv, cur_line, 0, "                                             ");
   mvwprintw(w_inv, drp_line, 90, "%s", drp_line_padding.c_str());
   mvwprintw(w_inv, drp_line + 1, 90, "%s", drp_line_padding.c_str());
// Print category header
   for (int i = 1; i < iCategorieNum; i++) {
    if (cur_it == firsts[i-1]) {
     mvwprintz(w_inv, cur_line, 0, c_magenta, _(CATEGORIES[i].c_str()));
     cur_line++;
    }
   }

   if ( selected < start && selected > -1 ) selected = start;

   if (cur_it < stacks.size()) {
    item& it = stacks[cur_it]->front();
    if(cur_it==selected) selected_char=(int)it.invlet;
    mvwputch (w_inv, cur_line, 0, (cur_it == selected ? h_white : c_white), it.invlet);
    char icon = '-';
    if (dropping[it.invlet] >= (it.count_by_charges() ? it.charges : stacks[cur_it]->size()))
     icon = '+';
    else if (dropping[it.invlet] > 0)
     icon = '#';
    nc_color col = ( cur_it == selected ? h_white : (dropping[it.invlet] == 0 ? c_ltgray : c_white ) );
    mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
              it.tname(this).c_str());
    if (stacks[cur_it]->size() > 1)
     wprintz(w_inv, col, " [%d]", stacks[cur_it]->size());
    if (it.charges > 0)
     wprintz(w_inv, col, " (%d)", it.charges);
    else if (it.contents.size() == 1 &&
             it.contents[0].charges > 0)
     wprintw(w_inv, " (%d)", it.contents[0].charges);
    if (icon=='+'||icon=='#') {
      mvwprintz(w_inv, drp_line, 90, col, "%c %c %s", it.invlet, icon, it.tname(this).c_str());
      if (icon=='+'){
        if (stacks[cur_it]->size() > 1)
          wprintz(w_inv, col, " [%d]", stacks[cur_it]->size());
        if (it.charges > 0)
          wprintz(w_inv, col, " (%d)", it.charges);
      }
      if (icon=='#') {
        wprintz(w_inv, col, " {%d}", dropping[it.invlet]);
      }
      drp_line++;
    }
   }
   cur_line++;
   max_it=cur_it;
  }
  if (start > 0)
   mvwprintw(w_inv, maxitems + 4, 0, _("< Go Back"));
  if (cur_it < u.inv.size())
   mvwprintw(w_inv, maxitems + 4, 12, _("> More items"));
  wrefresh(w_inv);
/* back to (int)getch() as input() mangles arrow keys
  ch = input();
*/
  ch = getch();
  if ( ch == '<' || ch == KEY_PPAGE ) {
   if( start > 0) {
    for (int i = 1; i < maxitems+4; i++)
     mvwprintz(w_inv, i, 0, c_black, "                                             ");
    start -= maxitems;
    if (start < 0)
     start = 0;
    mvwprintw(w_inv, maxitems + 4, 0, "         ");
    if ( selected > -1 ) selected = start; // oy, the cheese
    }
  } else if ( ch == '>' || ch == KEY_NPAGE ) {
   if ( cur_it < u.inv.size()) {
    start = cur_it;
    mvwprintw(w_inv, maxitems + 4, 12, "            ");
    for (int i = 1; i < maxitems+4; i++)
     mvwprintz(w_inv, i, 0, c_black, "                                             ");
    if ( selected < start && selected > -1 ) selected = start;
   }
  } else if ( ch == KEY_DOWN ) {
    if ( selected < 0 ) {
      selected = start;
    } else {
      selected++;
    }
    if ( selected > max_it ) {
      if( cur_it < u.inv.size() ) {
        start = cur_it;
        mvwprintw(w_inv, maxitems + 4, 12, "            ");
        for (int i = 1; i < maxitems+4; i++)
         mvwprintz(w_inv, i, 0, c_black, "                                             ");
      } else {
        selected = u.inv.size() - 1; // wraparound?
      }
    }
  } else if ( ch == KEY_UP ) {
    selected--;
    if ( selected < -1 ) {
      selected = -1; // wraparound?
    } else if ( selected < start ) {
      if ( start > 0 ) {
        for (int i = 1; i < maxitems+4; i++)
         mvwprintz(w_inv, i, 0, c_black, "                                             ");
        start -= maxitems;
        if (start < 0)
         start = 0;
        mvwprintw(w_inv, maxitems + 4, 0, "         ");
      }
    }
  } else if (ch >= '0'&& ch <= '9') {
   ch = (char)ch - '0';
   count *= 10;
   count += ch;
  } else { // todo: reformat and maybe rewrite
     if ( ch == '\t' || ch == KEY_RIGHT || ch == KEY_LEFT ) {
        ch = selected_char;
     }
     if (u.has_item(ch)) {
       item& it = u.inv.item_by_letter(ch);
       if (it.is_null()) { // Not from inventory
        int found = false;
        for (int i = 0; i < weapon_and_armor.size() && !found; i++) {
         if (weapon_and_armor[i] == ch) {
          weapon_and_armor.erase(weapon_and_armor.begin() + i);
          found = true;
          print_inv_statics(this, w_inv, _("Multidrop:"), weapon_and_armor);
         }
        }
        if (!found) {
         if ( ch == u.weapon.invlet &&
              std::find(unreal_itype_ids.begin(), unreal_itype_ids.end(), u.weapon.type->id) != unreal_itype_ids.end()){
          if (!warned_about_bionic)
           add_msg(_("You cannot drop your %s."), u.weapon.tname(this).c_str());
          warned_about_bionic = true;
         } else {
          weapon_and_armor.push_back(ch);
          print_inv_statics(this, w_inv, _("Multidrop:"), weapon_and_armor);
         }
        }
       } else {
        int index = -1;
        for (int i = 0; i < stacks.size(); ++i) {
         if (stacks[i]->front().invlet == it.invlet) {
          index = i;
          break;
         }
        }
        if (index == -1) {
         debugmsg("Inventory got out of sync with inventory slice?");
        }
        if (count == 0) {
        if (it.count_by_charges())
          {
           if (dropping[it.invlet] == 0)
            dropping[it.invlet] = -1;
           else
            dropping[it.invlet] = 0;
          }
        else
          {
           if (dropping[it.invlet] == 0)
            dropping[it.invlet] = stacks[index]->size();
           else
            dropping[it.invlet] = 0;
          }
        }

        else if (count >= stacks[index]->size() && !it.count_by_charges())
           dropping[it.invlet] = stacks[index]->size();
        else
          dropping[it.invlet] = count;

       count = 0;
       }
     }
  }
 } while (ch != '\n' && ch != KEY_ESCAPE && ch != ' ');
 werase(w_inv);
 delwin(w_inv);
 erase();
 refresh_all();

 std::vector<item> ret;

 if (ch != '\n')
  return ret; // Canceled!

 for (std::map<char,int>::iterator it = dropping.begin(); it != dropping.end(); it++) {
  if (it->second == -1)
   ret.push_back( u.inv.remove_item_by_letter( it->first));
  else if (it->second && u.inv.item_by_letter( it->first).count_by_charges()) {
   int charges = u.inv.item_by_letter( it->first).charges;// >= it->second ? : it->second;
   ret.push_back( u.inv.remove_item_by_charges( it->first, it->second > charges ? charges : it->second));
  } else if (it->second)
   for (int j = it->second; j > 0; j--)
    ret.push_back( u.inv.remove_item_by_letter( it->first));
 }

 for (int i = 0; i < weapon_and_armor.size(); i++)
 {
     if (!u.takeoff(this, weapon_and_armor[i], true))
     {
         continue;
     }

     // Item could have been dropped after taking it off
     if (&u.inv.item_by_letter(weapon_and_armor[i]) != &u.inv.nullitem)
     {
         ret.push_back(u.i_rem(weapon_and_armor[i]));
     }
 }

 return ret;
}
예제 #23
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_y = 1;
    unsigned namebar_x = 3 + utf8_width(_("World Name:"));

    int line = 1;
    bool noname = false;
    input_context ctxt("WORLDGEN_CONFIRM_DIALOG");
    // Disabled because it conflicts with the "pick random world name" option,
    // feel free to enable it and change its keybinding in keybindings.json
    // ctxt.register_action("HELP_KEYBINDINGS");
    ctxt.register_action("QUIT");
    ctxt.register_action("ANY_INPUT");
    ctxt.register_action("NEXT_TAB");
    ctxt.register_action("PREV_TAB");
    ctxt.register_action("PICK_RANDOM_WORLDNAME");

    std::string worldname = world->world_name;
    do {
        mvwprintz(w_confirmation, namebar_y, 2, c_white, _("World Name:"));
        mvwprintz(w_confirmation, namebar_y, namebar_x, c_ltgray, "______________________________");
        fold_and_print(w_confirmation, 3, 2, 76, c_ltgray,
                       _("Press <color_yellow>?</color> to pick a random name for your world."));
        fold_and_print(w_confirmation, FULL_SCREEN_HEIGHT / 2 - 2, 2, 76, c_ltgray, _("\
Press <color_yellow>></color> when you are satisfied with the world as it is and are ready \
to continue, or <color_yellow><</color> to go back and review your world."));
        if (!noname) {
            mvwprintz(w_confirmation, namebar_y, namebar_x, c_ltgray, "%s", worldname.c_str());
            if (line == 1) {
                wprintz(w_confirmation, h_ltgray, "_");
            }
        }
        if (noname) {
            mvwprintz(w_confirmation, namebar_y, namebar_x, c_ltgray, "______________________________");
            noname = false;
        }

        wrefresh(win);
        wrefresh(w_confirmation);
        refresh();

        const std::string action = ctxt.handle_input();
        if (action == "NEXT_TAB") {
            if (worldname.empty()) {
                mvwprintz(w_confirmation, namebar_y, namebar_x, 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;
                } 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 (action == "PREV_TAB") {
            world->world_name = worldname;
            werase(w_confirmation);
            delwin(w_confirmation);
            return -1;
        } else if (action == "PICK_RANDOM_WORLDNAME") {
            mvwprintz(w_confirmation, namebar_y, namebar_x, c_ltgray, "______________________________");
            world->world_name = worldname = pick_random_name();
        } else if (action == "QUIT") {
            world->world_name =
                worldname; // cache the current worldname just in case they say No to the exit query
            return -999;
        } else if (action == "ANY_INPUT") {
            const long ch = ctxt.get_raw_input().get_first_input();
            switch (line) {
                case 1:
                    if (ch == KEY_BACKSPACE || ch == 127) {
                        if (!worldname.empty()) {
                            //erase utf8 character TODO: make a function
                            while(!worldname.empty() &&
                                  ((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, namebar_y, namebar_x, c_ltgray,
                                      "______________________________ ");
                            mvwprintz(w_confirmation, namebar_y, namebar_x, 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;
}
예제 #24
0
void game::compare(int iCompareX, int iCompareY)
{
 int examx, examy;
 std::vector <item> grounditems;
 int ch = (int)'.';

 if (iCompareX != -999 && iCompareX != -999) {
  examx = u.posx + iCompareX;
  examy = u.posy + iCompareY;
 } else if (!choose_adjacent("Compare",examx,examy)) {
     return;
 }

 std::vector <item> here = m.i_at(examx, examy);
 //Filter out items with the same name (keep only one of them)
 std::map <std::string, bool> dups;
 for (int i = 0; i < here.size(); i++) {
  if (!dups[here[i].tname(this).c_str()]) {
   grounditems.push_back(here[i]);
   dups[here[i].tname(this).c_str()] = true;
  }
 }
 //Only the first 10 Items due to numbering 0-9
 const int groundsize = (grounditems.size() > 10 ? 10 : grounditems.size());
 u.inv.sort();
 u.inv.restack(&u);

 invslice stacks = u.inv.slice(0, u.inv.size());

 WINDOW* w_inv = newwin(TERMY-VIEW_OFFSET_Y*2, TERMX-VIEW_OFFSET_X*2, VIEW_OFFSET_Y, VIEW_OFFSET_X);
 int maxitems = TERMY-5-VIEW_OFFSET_Y*2;    // Number of items to show at one time.
 std::vector<int> compare_list; // Count of how many we'll drop from each stack
 bool bFirst = false; // First Item selected
 bool bShowCompare = false;
 char cLastCh = 0;
 compare_list.resize(u.inv.size() + groundsize, 0);
 std::vector<char> weapon_and_armor; // Always single, not counted
 print_inv_statics(this, w_inv, "Compare:", weapon_and_armor);
// Gun, ammo, weapon, armor, food, tool, book, other
 std::vector<int> first = find_firsts(stacks);
 std::vector<int> firsts;
 if (groundsize > 0) {
  firsts.push_back(0);
 }
 for (int i = 0; i < first.size(); i++) {
  firsts.push_back((first[i] >= 0) ? first[i]+groundsize : -1);
 }
 ch = '.';
 int start = 0, cur_it = 0;
 do {
  if (( ch == '<' || ch == KEY_PPAGE ) && start > 0) {
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
   start -= maxitems;
   if (start < 0)
    start = 0;
   mvwprintw(w_inv, maxitems + 4, 0, "         ");
  }
  if (( ch == '>' || ch == KEY_NPAGE ) && cur_it < u.inv.size() + groundsize) {
   start = cur_it;
   mvwprintw(w_inv, maxitems + 4, 12, "            ");
   for (int i = 1; i < maxitems+4; i++)
    mvwprintz(w_inv, i, 0, c_black, "                                             ");
  }
  int cur_line = 2;
  int iHeaderOffset = (groundsize > 0) ? 0 : 1;

  for (cur_it = start; cur_it < start + maxitems && cur_line < maxitems+3; cur_it++) {
// Clear the current line;
   mvwprintw(w_inv, cur_line, 0, "                                             ");
// Print category header
   for (int i = iHeaderOffset; i < iCategorieNum; i++) {
    if (cur_it == firsts[i-iHeaderOffset]) {
     mvwprintz(w_inv, cur_line, 0, c_magenta, _(CATEGORIES[i].c_str()));
     cur_line++;
    }
   }
   if (cur_it < u.inv.size() + groundsize) {
    char icon = '-';
    if (compare_list[cur_it] == 1)
     icon = '+';
    if (cur_it < groundsize) {
     mvwputch (w_inv, cur_line, 0, c_white, '1'+((cur_it<9) ? cur_it: -1));
     nc_color col = (compare_list[cur_it] == 0 ? c_ltgray : c_white);
     mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
               grounditems[cur_it].tname(this).c_str());
    } else {
     item& it = stacks[cur_it-groundsize]->front();
     mvwputch (w_inv, cur_line, 0, c_white, it.invlet);
     nc_color col = (compare_list[cur_it] == 0 ? c_ltgray : c_white);
     mvwprintz(w_inv, cur_line, 1, col, " %c %s", icon,
               it.tname(this).c_str());
     if (stacks[cur_it-groundsize]->size() > 1)
      wprintz(w_inv, col, " [%d]", stacks[cur_it-groundsize]->size());
     if (it.charges > 0)
      wprintz(w_inv, col, " (%d)", it.charges);
     else if (it.contents.size() == 1 &&
              it.contents[0].charges > 0)
      wprintw(w_inv, " (%d)", it.contents[0].charges);
    }
   }
   cur_line++;
  }
  if (start > 0)
   mvwprintw(w_inv, maxitems + 4, 0, _("< Go Back"));
  if (cur_it < u.inv.size() + groundsize)
   mvwprintw(w_inv, maxitems + 4, 12, _("> More items"));
  wrefresh(w_inv);
  ch = getch();
  if (u.has_item(ch)) {
   item& it = u.inv.item_by_letter(ch);
   if (it.is_null()) { // Not from inventory
    bool found = false;
    for (int i = 0; i < weapon_and_armor.size() && !found; i++) {
     if (weapon_and_armor[i] == ch) {
      weapon_and_armor.erase(weapon_and_armor.begin() + i);
      found = true;
      bFirst = false;
      print_inv_statics(this, w_inv, "Compare:", weapon_and_armor);
     }
    }
    if (!found) {

     if ( ch == u.weapon.invlet &&
          std::find(unreal_itype_ids.begin(), unreal_itype_ids.end(), u.weapon.type->id) != unreal_itype_ids.end()){
      //Do Bionic stuff here?!
     } else {
      if (!bFirst)
      {
       weapon_and_armor.push_back(ch);
       print_inv_statics(this, w_inv, "Compare:", weapon_and_armor);
       bFirst = true;
       cLastCh = ch;
      } else {
       bShowCompare = true;
      }
     }
    }
   } else {
    int index = -1;
    for (int i = 0; i < stacks.size(); ++i) {
     if (stacks[i]->front().invlet == it.invlet) {
      index = i;
      break;
     }
    }
    if (index == -1) {
     debugmsg("Inventory got out of sync with inventory slice?");
    }
    if (compare_list[index+groundsize] == 1)
    {
     compare_list[index+groundsize] = 0;
     bFirst = false;
    } else {
     if (!bFirst)
     {
      compare_list[index+groundsize] = 1;
      bFirst = true;
      cLastCh = ch;
     } else {
      bShowCompare = true;
     }
    }
   }
  } else if ((ch >= '1' && ch <= '9' && ch-'1' < groundsize) || (ch == '0' && groundsize == 10)) {
   //Ground Items
   int iZero = 0;
   if (ch == '0') {
    iZero = 10;
   }
   if (compare_list[ch-'1'+iZero] == 1)
   {
    compare_list[ch-'1'+iZero] = 0;
    bFirst = false;
   } else {
    if (!bFirst)
    {
     compare_list[ch-'1'+iZero] = 1;
     bFirst = true;
     cLastCh = ch;
    } else {
     bShowCompare = true;
    }
   }
  }
  if (bShowCompare) {
   std::vector<iteminfo> vItemLastCh, vItemCh;
   std::string sItemLastCh, sItemCh;
   if (cLastCh >= '0' && cLastCh <= '9') {
    int iZero = 0;
    if (cLastCh == '0') {
     iZero = 10;
    }

    grounditems[cLastCh-'1'+iZero].info(true, &vItemLastCh);
    sItemLastCh = grounditems[cLastCh-'1'+iZero].tname(this);
   } else {
    u.i_at(cLastCh).info(true, &vItemLastCh);
    sItemLastCh = u.i_at(cLastCh).tname(this);
   }

   if (ch >= '0' && ch <= '9') {
    int iZero = 0;
    if (ch == '0') {
     iZero = 10;
    }

    grounditems[ch-'1'+iZero].info(true, &vItemCh);
    sItemCh = grounditems[ch-'1'+iZero].tname(this);
   } else {
    u.i_at(ch).info(true, &vItemCh);
    sItemCh = u.i_at(ch).tname(this);
   }

   compare_split_screen_popup(0, (TERMX-VIEW_OFFSET_X*2)/2, TERMY-VIEW_OFFSET_Y*2, sItemLastCh, vItemLastCh, vItemCh);
   compare_split_screen_popup((TERMX-VIEW_OFFSET_X*2)/2, (TERMX-VIEW_OFFSET_X*2)/2, TERMY-VIEW_OFFSET_Y*2, sItemCh, vItemCh, vItemLastCh);

   wclear(w_inv);
   print_inv_statics(this, w_inv, "Compare:", weapon_and_armor);
   bShowCompare = false;
  }
 } while (ch != '\n' && ch != KEY_ESCAPE && ch != ' ');
 werase(w_inv);
 delwin(w_inv);
 erase();
 refresh_all();
}
예제 #25
0
int worldfactory::show_worldgen_tab_modselection(WINDOW *win, WORLDPTR world)
{
    // Use active_mod_order of the world,
    // saves us from writting 'world->active_mod_order' all the time.
    std::vector<std::string> &active_mod_order = world->active_mod_order;
    {
        std::vector<std::string> tmp_mod_order;
        // clear active_mod_order and re-add all the mods, his ensures
        // that changes (like changing depencies) get updated
        tmp_mod_order.swap(active_mod_order);
        for(size_t i = 0; i < tmp_mod_order.size(); i++) {
            mman_ui->try_add(tmp_mod_order[i], active_mod_order);
        }
    }

    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;

    // lots of small windows so that each section can be drawn to independently of the others as necessary
    WINDOW *w_header1, *w_header2, *w_shift, *w_list, *w_active, *w_description;
    w_header1 = newwin(1, FULL_SCREEN_WIDTH / 2 - 5, 3 + iOffsetY, 1 + iOffsetX);
    w_header2 = newwin(1, FULL_SCREEN_WIDTH / 2 - 4, 3 + iOffsetY,
                       FULL_SCREEN_WIDTH / 2 + 3 + iOffsetX);
    w_shift   = newwin(13, 5, 3 + iOffsetY, FULL_SCREEN_WIDTH / 2 - 3 + iOffsetX);
    w_list    = newwin(11, FULL_SCREEN_WIDTH / 2 - 4, 5 + iOffsetY, iOffsetX);
    w_active  = newwin(11, FULL_SCREEN_WIDTH / 2 - 4, 5 + iOffsetY,
                       FULL_SCREEN_WIDTH / 2 + 2 + iOffsetX);
    w_description = newwin(4, FULL_SCREEN_WIDTH - 2, 19 + iOffsetY, 1 + iOffsetX);

    draw_modselection_borders(win);
    std::vector<std::string> headers;
    headers.push_back(_("Mod List"));
    headers.push_back(_("Mod Load Order"));
    std::vector<WINDOW *> header_windows;
    header_windows.push_back(w_header1);
    header_windows.push_back(w_header2);

    int tab_output = 0;
    int last_active_header = 0;
    size_t active_header = 0;
    size_t useable_mod_count = mman_ui->usable_mods.size();
    int startsel[2] = {0, 0};
    int cursel[2] = {0, 0};

    bool redraw_headers = true;
    bool redraw_shift = true;
    bool redraw_description = true;
    bool redraw_list = true;
    bool redraw_active = true;
    bool selection_changed = false;

    input_context ctxt("MODMANAGER_DIALOG");
    ctxt.register_cardinal();
    ctxt.register_action("HELP_KEYBINDINGS");
    ctxt.register_action("QUIT");
    ctxt.register_action("NEXT_TAB");
    ctxt.register_action("PREV_TAB");
    ctxt.register_action("CONFIRM");
    ctxt.register_action("ADD_MOD");
    ctxt.register_action("REMOVE_MOD");
    ctxt.register_action("SAVE_DEFAULT_MODS");

    while (tab_output == 0) {
        if (redraw_headers) {
            for (size_t i = 0; i < headers.size(); ++i) {
                werase(header_windows[i]);
                const int header_x = (getmaxx(header_windows[i]) - headers[i].size()) / 2;
                mvwprintz(header_windows[i], 0, header_x , c_cyan, "%s", headers[i].c_str());

                if (active_header == i) {
                    mvwputch(header_windows[i], 0, header_x - 3, c_red, '<');
                    mvwputch(header_windows[i], 0, header_x + headers[i].size() + 2, c_red, '>');
                }
                wrefresh(header_windows[i]);
            }
            redraw_list = true;
            redraw_active = true;
            redraw_shift = true;
            redraw_headers = false;
        }
        if (selection_changed) {
            if (active_header == 0) {
                redraw_list = true;
            }
            if (active_header == 1) {
                redraw_shift = true;
                redraw_active = true;
            }
            selection_changed = false;
            redraw_description = true;
        }
        if (redraw_description) {
            werase(w_description);

            MOD_INFORMATION *selmod = NULL;
            if (mman_ui->usable_mods.empty()) {
                // Do nothing, leave selmod == NULL
            } else if (active_header == 0) {
                selmod = mman->mod_map[mman_ui->usable_mods[cursel[0]]];
            } else if (!active_mod_order.empty()) {
                selmod = mman->mod_map[active_mod_order[cursel[1]]];
            }

            if (selmod != NULL) {
                fold_and_print(w_description, 0, 1, getmaxx(w_description) - 1,
                               c_white, mman_ui->get_information(selmod));
            }
            redraw_description = false;
            wrefresh(w_description);
        }
        if (redraw_list) {
            werase(w_list);
            calcStartPos(startsel[0], cursel[0], getmaxy(w_list), useable_mod_count);

            if (useable_mod_count == 0) {
                center_print(w_list, 0, c_red, _("--NO AVAILABLE MODS--"));
            } else {
                std::stringstream list_output;

                for (size_t i = startsel[0], c = 0; i < useable_mod_count && c < getmaxy(w_list); ++i, ++c) {
                    if ((ssize_t)i != cursel[0]) {
                        list_output << std::string(3, ' ');
                    } else {
                        if (active_header == 0) {
                            list_output << "<color_yellow>";
                        } else {
                            list_output << "<color_blue>";
                        }
                        list_output << ">></color> ";
                    }
                    list_output << mman->mod_map[mman_ui->usable_mods[i]]->name << "\n";
                }
                fold_and_print(w_list, 0, 1, getmaxx(w_list) - 1, c_white, list_output.str());
            }
            draw_scrollbar(w_list, cursel[0], getmaxy(w_list), useable_mod_count, 0, 0);

            wrefresh(w_list);
        }
        if (redraw_active) {
            werase(w_active);
            const int active_count = active_mod_order.size();
            calcStartPos(startsel[1], cursel[1], getmaxy(w_active), active_count);

            if (active_count == 0) {
                center_print(w_active, 0, c_red, _("--NO ACTIVE MODS--"));
            } else {
                std::stringstream list_output;

                for (int i = startsel[1], c = 0; i < active_count && c < getmaxy(w_active); ++i, ++c) {
                    if (i != cursel[1]) {
                        list_output << std::string(3, ' ');
                    } else {
                        if (active_header == 1) {
                            list_output << "<color_yellow>";
                        } else {
                            list_output << "<color_blue>";
                        }
                        list_output << ">></color> ";
                    }
                    list_output << mman->mod_map[active_mod_order[i]]->name << "\n";
                }
                fold_and_print(w_active, 0, 1, getmaxx(w_active) - 1, c_white, list_output.str());
            }

            draw_scrollbar(w_active, cursel[1], getmaxy(w_active), active_count, 0, 0);

            wrefresh(w_active);
        }
        if (redraw_shift) {
            werase(w_shift);
            if (active_header == 1) {
                std::stringstream shift_display;
                // get shift information for whatever is visible in the active list
                for (size_t i = startsel[1], c = 0; i < active_mod_order.size() && c < getmaxy(w_active); ++i, ++c) {
                    if (mman_ui->can_shift_up(i, active_mod_order)) {
                        shift_display << "<color_blue>+</color> ";
                    } else {
                        shift_display << "<color_dkgray>+</color> ";
                    }
                    if (mman_ui->can_shift_down(i, active_mod_order)) {
                        shift_display << "<color_blue>-</color>";
                    } else {
                        shift_display << "<color_dkgray>-</color>";
                    }
                    shift_display << "\n";
                }
                fold_and_print(w_shift, 2, 1, getmaxx(w_shift), c_white, shift_display.str());
            }
            redraw_shift = false;
            wrefresh(w_shift);
        }
        refresh();

        last_active_header = active_header;
        const int next_header = (active_header == 1) ? 0 : 1;
        const int prev_header = (active_header == 0) ? 1 : 0;

        int selection = (active_header == 0) ? cursel[0] : cursel[1];
        int last_selection = selection;
        unsigned int next_selection = selection + 1;
        int prev_selection = selection - 1;
        if (active_header == 0) {
            next_selection = (next_selection >= useable_mod_count) ? 0 : next_selection;
            prev_selection = (prev_selection < 0) ? useable_mod_count - 1 : prev_selection;
        } else {
            next_selection = (next_selection >= active_mod_order.size()) ? 0 : next_selection;
            prev_selection = (prev_selection < 0) ? active_mod_order.size() - 1 : prev_selection;
        }

        const std::string action = ctxt.handle_input();

        if (action == "DOWN") {
            selection = next_selection;
        } else if (action == "UP") {
            selection = prev_selection;
        } else if (action == "RIGHT") {
            active_header = next_header;
        } else if (action == "LEFT") {
            active_header = prev_header;
        } else if (action == "CONFIRM") {
                if (active_header == 0 && !mman_ui->usable_mods.empty()) {
                    // try-add
                    mman_ui->try_add(mman_ui->usable_mods[cursel[0]], active_mod_order);
                    redraw_active = true;
                    redraw_shift = true;
                } else if (active_header == 1 && !active_mod_order.empty()) {
                    // try-rem
                    mman_ui->try_rem(cursel[1], active_mod_order);
                    redraw_active = true;
                    redraw_shift = true;
                    if (active_mod_order.empty()) {
                        // switch back to other list, we can't change
                        // anything in the empty active mods list.
                        active_header = 0;
                    }
                }
        } else if (action == "ADD_MOD") {
                if (active_header == 1 && active_mod_order.size() > 1) {
                    mman_ui->try_shift('+', cursel[1], active_mod_order);
                    redraw_active = true;
                    redraw_shift = true;
                }
        } else if (action == "REMOVE_MOD") {
                if (active_header == 1 && active_mod_order.size() > 1) {
                    mman_ui->try_shift('-', cursel[1], active_mod_order);
                    redraw_active = true;
                    redraw_shift = true;
                }
        } else if (action == "NEXT_TAB") {
                tab_output = 1;
        } else if (action == "PREV_TAB") {
                tab_output = -1;
        } else if (action == "SAVE_DEFAULT_MODS") {
                if(mman->set_default_mods(active_mod_order)) {
                    popup(_("Saved list of active mods as default"));
                    draw_modselection_borders(win);
                    redraw_headers = true;
                }
        } else if (action == "QUIT") {
                tab_output = -999;
        }
        // RESOLVE INPUTS
        if (last_active_header != (ssize_t)active_header) {
            redraw_headers = true;
            redraw_shift = true;
            redraw_description = true;
        }
        if (last_selection != selection) {
            if (active_header == 0) {
                redraw_list = true;
                cursel[0] = selection;
            } else {
                redraw_active = true;
                redraw_shift = true;
                cursel[1] = selection;
            }
            redraw_description = true;
        }
        if (active_mod_order.empty()) {
            redraw_active = true;
            cursel[1] = 0;
        }

        if (active_header == 1) {
            if (active_mod_order.empty()) {
                cursel[1] = 0;
            } else {
                if (cursel[1] < 0) {
                    cursel[1] = 0;
                } else if (cursel[1] >= (ssize_t)active_mod_order.size()) {
                    cursel[1] = active_mod_order.size() - 1;
                }
            }
        }
        // end RESOLVE INPUTS
    }
    werase(w_header1);
    werase(w_header2);
    werase(w_shift);
    werase(w_list);
    werase(w_active);
    werase(w_description);

    delwin(w_header1);
    delwin(w_header2);
    delwin(w_shift);
    delwin(w_list);
    delwin(w_active);
    delwin(w_description);
    return tab_output;
}
예제 #26
0
void
add_line(const char *fmt, ...)
{
    WINDOW  *tw;
    va_list ap;

    va_start(ap, fmt);

    if (line_cnt == 0)
    {
        wclear(hw);

        if (inv_type == INV_SLOW)
            mpos = 0;
    }

    if (inv_type == INV_SLOW)
    {
        if ( (fmt != NULL) && (*fmt != '\0') )
            vmsg(fmt, ap);
        line_cnt++;
    }
    else
    {
        if ( (line_cnt >= LINES - 2) || (fmt == NULL)) /* end 'o page */
        {
            if (fmt == NULL && !newpage && inv_type == INV_OVER)
            {
                tw = newwin(line_cnt + 2, COLS, 0, 0);
                overwrite(hw, tw);
                wstandout(tw);
                mvwaddstr(tw, line_cnt, 0, spacemsg);
                wstandend(tw);
                touchwin(tw);
                wrefresh(tw); 
                wait_for(' ');
                delwin(tw);
                touchwin(cw);
            }
            else
            {
                wstandout(hw);
                mvwaddstr(hw, LINES - 1, 0, spacemsg);
                wstandend(hw);
                wrefresh(hw);
                w_wait_for(hw, ' ');
                touchwin(cw);
                wclear(hw);
            }
            newpage = TRUE;
            line_cnt = 0;
        }

        /* draw line */
        if (fmt != NULL && !(line_cnt == 0 && *fmt == '\0'))
        {
            static char tmpbuf[1024];
			
            vsprintf(tmpbuf, fmt, ap);
            mvwprintw(hw, line_cnt++, 0, tmpbuf);
        }
    }
}
예제 #27
0
/*
C implementation of curses::Window::delwin
*/
void Window_delwin___impl( Window recv )
{
	delwin(recv);
}
예제 #28
0
bool trade(game *g, npc *p, int cost, std::string deal)
{
    WINDOW* w_head = newwin( 4, 80,  0,  0);
    WINDOW* w_them = newwin(21, 40,  4,  0);
    WINDOW* w_you  = newwin(21, 40,  4, 40);
    WINDOW* w_tmp;
    mvwprintz(w_head, 0, 0, c_white, _("\
Trading with %s\n\
Tab key to switch lists, letters to pick items, Enter to finalize, Esc to quit\n\
? to get information on an item"), p->name.c_str());

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


// End of line drawings

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

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

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

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

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

        for (int i = 0; i < theirs.size(); i++) {
            item tmp = p->inv[theirs[i]];
            if (getting_theirs[i]) {
                practice += 2;
                tmp.invlet = 'a';
                while (g->u.has_item(tmp.invlet)) {
                    if (tmp.invlet == 'z')
                        tmp.invlet = 'A';
                    else if (tmp.invlet == 'Z')
                        return false;	// TODO: Do something else with these.
                    else
                        tmp.invlet++;
                }
                g->u.inv.push_back(tmp);
            } else
                newinv.push_back(tmp);
        }
        g->u.practice(sk_barter, practice / 2);
        p->inv = newinv;
        g->u.cash += cash;
        p->cash   -= cash;
    }
    werase(w_head);
    werase(w_you);
    werase(w_them);
    wrefresh(w_head);
    wrefresh(w_you);
    wrefresh(w_them);
    delwin(w_head);
    delwin(w_you);
    delwin(w_them);
    if (ch == '\n')
        return true;
    return false;
}
예제 #29
0
// Scan MAME ROMs folder, cross-reference against XML (if present) for
// verbose descriptions, generate ncurses menu.
static void find_roms(void) {
	FILE           *fp;
	struct dirent **dirList;
	int             i, nFiles;
	Game           *g;       // For traversing Game linked list
	WINDOW         *scanWin; // Modal 'Scanning...' window

	if(noRomWin) { // Delete 'No ROMS' window if present
		delwin(noRomWin);
		noRomWin = NULL;
		werase(mainWin);
		box(mainWin, 0, 0);
	}

	if(items) { // Delete old ROM menu and contents, if any
		if(menu) {
			unpost_menu(menu);
			free_menu(menu);
			menu = NULL;
		}
		for(i=0; items[i]; i++) free_item(items[i]);
		free(items);
		items = NULL;
	}

	const char scanMsg[] = "Scanning ROM folder...";
	scanWin = newwin(3, strlen(scanMsg) + 4,
	  (LINES - 4) / 2 - 1, (COLS - strlen(scanMsg)) / 2 - 2);
	box(scanWin, 0, 0);
	mvwprintw(scanWin, 1, 2, scanMsg);

	wnoutrefresh(mainWin);
	wnoutrefresh(scanWin);
	doupdate();

	delwin(scanWin);
	werase(mainWin);
	box(mainWin, 0, 0);

	while(gameList) { // Delete existing gameList, if any
		g = gameList->next;
		if(gameList->name) free(gameList->name);
		if(gameList->desc) free(gameList->desc);
		free(gameList);
		gameList = g;
	}

	i = 0; // Count number of games found & successfully alloc'd
	if((nFiles = scandir(rom, &dirList, sel, alphasort)) > 0) {
		// Copy dirent array to a Game linked list
		while(nFiles--) { // List is assembled in reverse
			if((g = (Game *)malloc(sizeof(Game)))) {
				g->name  = strdup(dirList[nFiles]->d_name);
				g->desc  = NULL;
				g->next  = gameList;
				gameList = g;
				i++; // A winner is you
			}
			// dirList contents are freed as we go
			free(dirList[nFiles]);
		}
		free(dirList);
	}

	// Alloc, load, cross-reference XML file against ROM filenames
	if((fp = fopen(xml, "r"))) {
		fseek(fp, 0, SEEK_END);
		char *buf;
		int   len = ftell(fp);
		if((buf = (char *)malloc(len))) {
			int depth = 0;
			fseek(fp, 0, SEEK_SET);
			fread(buf, 1, len, fp);
			XML_Parser parser = XML_ParserCreate(NULL);
			XML_SetUserData(parser, &depth);
			XML_SetElementHandler(parser,
			  startElement, endElement);
			XML_SetCharacterDataHandler(parser, elementData);
			XML_Parse(parser, buf, len, 1);
			XML_ParserFree(parser);
			free(buf);
		}
		fclose(fp);
	}

	if((items = (ITEM**)malloc((i + 1) * sizeof(ITEM *)))) {
		for(i=0, g=gameList; g; g=g->next, i++) {
			items[i] = new_item(g->name, g->desc);
			set_item_userptr(items[i], g);
		}
		items[i] = NULL;
		menu = new_menu(items);
		set_menu_win(menu, mainWin);
		set_menu_sub(menu, derwin(mainWin, LINES-6, COLS-2, 1, 1));
		set_menu_format(menu, LINES-6, 1);
		set_menu_mark(menu, " ");
		post_menu(menu);
	}

	wrefresh(mainWin);

	if(!menu) { // If no ROMs, throw up a message to that effect
		const char noRomMsg[] = "No ROMs found";
		noRomWin = newwin(3, strlen(noRomMsg) + 4,
		  (LINES - 4) / 2 - 1, (COLS - strlen(noRomMsg)) / 2 - 2);
		box(noRomWin, 0, 0);
		mvwprintw(noRomWin, 1, 2, noRomMsg);
		wrefresh(noRomWin);
	}
}
예제 #30
0
파일: item.cpp 프로젝트: ziodice/Cataclysm
int item::pick_reload_ammo(player &u, bool interactive)
{
 if (!type->is_gun() && !type->is_tool()) {
  debugmsg("RELOADING NON-GUN NON-TOOL");
  return false;
 }
 bool has_m203 = false;
 for (int i = 0; i < contents.size() && !has_m203; i++) {
  if (contents[i].type->id == itm_m203)
   has_m203 = true;
 }

 std::vector<int> am;	// List of indicies of valid ammo

 if (type->is_gun()) {
  if (charges > 0) {
   itype_id aid = itype_id(curammo->id);
   for (int i = 0; i < u.inv.size(); i++) {
    if (u.inv[i].type->id == aid)
     am.push_back(i);
   }
  } else {
  it_gun* tmp = dynamic_cast<it_gun*>(type);
   am = u.has_ammo(ammo_type());
   if (has_m203) {
    std::vector<int> grenades = u.has_ammo(AT_40MM);
    for (int i = 0; i < grenades.size(); i++)
     am.push_back(grenades[i]);
   }
  }
 } else {
  it_tool* tmp = dynamic_cast<it_tool*>(type);
  am = u.has_ammo(ammo_type());
 }

 int index = -1;

 if (am.size() > 1 && interactive) {// More than one option; list 'em and pick
  WINDOW* w_ammo = newwin(am.size() + 1, 80, 0, 0);
  if (charges == 0) {
   char ch;
   clear();
   it_ammo* ammo_type;
   mvwprintw(w_ammo, 0, 0, "\
Choose ammo type:         Damage     Armor Pierce     Range     Accuracy");
   for (int i = 0; i < am.size(); i++) {
    ammo_type = dynamic_cast<it_ammo*>(u.inv[am[i]].type);
    mvwaddch(w_ammo, i + 1, 1, i + 'a');
    mvwprintw(w_ammo, i + 1, 3, "%s (%d)", u.inv[am[i]].tname().c_str(),
                                           u.inv[am[i]].charges);
    mvwprintw(w_ammo, i + 1, 27, "%d", ammo_type->damage);
    mvwprintw(w_ammo, i + 1, 38, "%d", ammo_type->pierce);
    mvwprintw(w_ammo, i + 1, 55, "%d", ammo_type->range);
    mvwprintw(w_ammo, i + 1, 65, "%d", 100 - ammo_type->accuracy);
   }
   refresh();
   wrefresh(w_ammo);
   do
    ch = getch();
   while ((ch < 'a' || ch - 'a' > am.size() - 1) && ch != ' ' && ch != 27);
   werase(w_ammo);
   delwin(w_ammo);
   erase();
   if (ch == ' ' || ch == 27)
    index = -1;
   else
    index = am[ch - 'a'];
  } else {