示例#1
0
文件: fpick.c 项目: matyler/mtPaint
static void scan_dir(fpick_dd *dt, DIR *dp, char *select)
{
	char full_name[PATHBUF], txt_size[64], txt_date[64], tmp_txt[64];
	char *nm, *src, *dest, *dir = dt->txt_directory;
	memx2 mem = dt->files;
	struct tm *lt;
	struct dirent *ep;
	struct stat buf;
	int *tc;
	int subdir, tf, n, l = strlen(dir), cnt = 0;

	mem.here = 0;
	getmemx2(&mem, 8000); // default size

	dt->idx = -1;
	if (strcmp(dir, DIR_SEP_STR)) // Have a parent dir to move to?
	{
		// Field #0 - original name
		addstr(&mem, "..", 0);
		// Field #1 - type flag (space) + name in GUI encoding
		addstr(&mem, " " DIR_SEP_STR " ..", 0);
		// Fields #2-4 empty for all dirs
		// Fields #5-6 are empty strings, to keep this sorted first
		addchars(&mem, 0, 3 + 2);
		cnt++;
	}

	while ((ep = readdir(dp)))
	{
		wjstrcat(full_name, PATHBUF, dir, l, ep->d_name, NULL);

		// Error getting file details
		if (stat(full_name, &buf) < 0) continue;

		if (!dt->show_hidden && (ep->d_name[0] == '.')) continue;

#ifdef WIN32
		subdir = S_ISDIR(buf.st_mode);
#else
		subdir = (ep->d_type == DT_DIR) || S_ISDIR(buf.st_mode);
#endif
		tf = 'F'; // Type flag: 'D' for dir, 'F' for file
		if (subdir)
		{
			if (!dt->allow_dirs) continue;
			// Don't look at '.' or '..'
			if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
				continue;
			tf = 'D';
		}
		else if (!dt->allow_files) continue;

		/* Remember which row has matching name */
		if (select && !strcmp(ep->d_name, select)) dt->idx = cnt;

		cnt++;

		// Field #0 - original name
		addstr(&mem, ep->d_name, 0);
		// Field #1 - type flag + name in GUI encoding
		addchars(&mem, tf, 1);
		nm = gtkuncpy(NULL, ep->d_name, 0);
		addstr(&mem, nm, 0);
		// Fields #2-4 empty for dirs
		if (subdir) addchars(&mem, 0, 3);
		else
		{
			// Field #2 - file size
#ifdef WIN32
			n = snprintf(tmp_txt, 64, "%I64u", (unsigned long long)buf.st_size);
#else
			n = snprintf(tmp_txt, 64, "%llu", (unsigned long long)buf.st_size);
#endif
			memset(txt_size, ' ', 20);
			dest = txt_size + 20; *dest-- = '\0';
			for (src = tmp_txt + n - 1; src - tmp_txt > 2; )
			{
				*dest-- = *src--;
				*dest-- = *src--;
				*dest-- = *src--;
				*dest-- = ',';
			}
			while (src - tmp_txt >= 0) *dest-- = *src--;
			addstr(&mem, txt_size, 0);
			// Field #3 - file type (extension)
			src = strrchr(nm, '.');
			if (src && (src != nm) && src[1])
			{
#if GTK_MAJOR_VERSION == 1
				g_strup(src = g_strdup(src + 1));
#else
				src = g_utf8_strup(src + 1, -1);
#endif
				addstr(&mem, src, 0);
				g_free(src);
			}
			else addchars(&mem, 0, 1);
			// Field #4 - file modification time
			strcpy(txt_date, " "); // to sort failed files after dirs
			lt = localtime(&buf.st_mtime);
			/* !!! localtime() can fail and return NULL if given
			 * "wrong" input value */
			if (lt) strftime(txt_date, 60, "%Y-%m-%d   %H:%M.%S", lt);
			addstr(&mem, txt_date, 0);
		}
		// Field #5 - case-insensitive sort key
		src = isort_key(nm);
		addstr(&mem, src, 0);
		g_free(src);
		// Field #6 - alphabetic (case-sensitive) sort key
#if GTK_MAJOR_VERSION == 1
		addstr(&mem, nm, 0);
#else /* if GTK_MAJOR_VERSION == 2 */
		src = g_utf8_collate_key(nm, -1);
		addstr(&mem, src, 0);
		g_free(src);
#endif
		g_free(nm);
	}
	dt->cnt = cnt;

	/* Now add index array and mapping arrays to all this */
	l = (~(unsigned)mem.here + 1) & (sizeof(int) - 1);
	n = cnt * COL_MAX;
	getmemx2(&mem, l + (n + cnt) * sizeof(int));
	// Fill index array
	tc = dt->fcols = (void *)(mem.buf + mem.here + l);
	src = mem.buf;
	while (n-- > 0)
	{
		*tc = src - (char *)tc;
		tc++;
		src += strlen(src) + 1;
	}
	// Setup mapping array
	dt->fmap = tc;

	dt->files = mem;
}
示例#2
0
/*
 * Define a (possibly) new class of objects.
 * The list of indexes for the element names is also specified here,
 * and the number of elements defined for the object.
 *
 * given:
 *	name		name of object type
 *	indices		table of indices for elements
 *	count		number of elements defined for the object
 */
int
defineobject(char *name, int indices[], int count)
{
	OBJECTACTIONS *oap;	/* object definition structure */
	STRINGHEAD *hp;
	OBJECTACTIONS **newobjects;
	int index;

	hp = &objectnames;
	if (hp->h_list == NULL)
		initstr(hp);
	index = findstr(hp, name);
	if (index >= 0) {
		/*
		 * Object is already defined.  Give an error unless this
		 * new definition is exactly the same as the old one.
		 */
		oap = objects[index];
		if (oap->oa_count == count) {
			for (index = 0; ; index++) {
				if (index >= count)
					return 0;
				if (oap->oa_elements[index] != indices[index])
					break;
			}
		}
		return 1;
	}

	if (hp->h_count >= maxobjcount) {
		if (maxobjcount == 0) {
			newobjects = (OBJECTACTIONS **) malloc(
				OBJALLOC * sizeof(OBJECTACTIONS *));
			maxobjcount = OBJALLOC;
		} else {
			maxobjcount += OBJALLOC;
			newobjects = (OBJECTACTIONS **) realloc(objects,
				maxobjcount * sizeof(OBJECTACTIONS *));
		}
		if (newobjects == NULL) {
			math_error("Allocation failure for new object type");
			/*NOTREACHED*/
		}
		objects = newobjects;
	}

	oap = (OBJECTACTIONS *) malloc(objectactionsize(count));
	name = addstr(hp, name);
	if ((oap == NULL) || (name == NULL)) {
		math_error("Cannot allocate object type");
		/*NOTREACHED*/
	}
	oap->oa_count = count;
	for (index = OBJ_MAXFUNC; index >= 0; index--)
		oap->oa_indices[index] = -1;
	for (index = 0; index < count; index++)
		oap->oa_elements[index] = indices[index];
	index = findstr(hp, name);
	oap->oa_index = index;
	objects[index] = oap;
	return 0;
}
示例#3
0
文件: blue.c 项目: kal444/xiang-qi
static void play_game(void)
{
    int dead=0, i, j;
    char c;
    int selection[4], card;

    while (dead<4)
    {
	dead=0;
	for (i=0;i<4;i++)
	{
	    card=grid[freeptr[i]-1];

	    if (	((card % SUIT_LENGTH)==KING)
		||
		(card==NOCARD)	)
		selection[i]=NOCARD;
	    else
		selection[i]=find(card+1);

	    if (selection[i]==NOCARD)
		dead++;
	};

	if (dead < 4)
	{
	    char	live[NSUITS+1], *lp = live;

	    for (i=0;i<4;i++)
	    {
		if (selection[i] != NOCARD)
		{
		    move(BASEROW + (selection[i] / GRID_WIDTH)*2+3,
			 (selection[i] % GRID_WIDTH)*5);
		    (void)printw("   %c ", *lp++ = 'a' + i);
		}
	    };
	    *lp = '\0';

	    if (strlen(live) == 1)
	    {
		move(PROMPTROW,0);
		(void)printw(
		    "Making forced moves...                                 ");
		refresh();
		(void) sleep(1);
		c = live[0];
	    }
	    else
	    {
		char	buf[BUFSIZ];

		(void)sprintf(buf,
			"Type [%s] to move, r to redraw, q or INTR to quit: ",
			live);

		do {
		    move(PROMPTROW,0);
		    (void) addstr(buf);
		    move(PROMPTROW, (int)strlen(buf));
		    clrtoeol();
		    (void) addch(' ');
		} while
		    (((c = getch())<'a' || c>'d') && (c!='r') && (c!='q'));
	    }

	    for (j = 0; j < 4; j++)
		if (selection[j]!=NOCARD)
		{
		    move(BASEROW + (selection[j] / GRID_WIDTH)*2+3,
			 (selection[j] % GRID_WIDTH)*5);
		    (void)printw("     ");
		}

	    if (c == 'r')
		display_cards(deal_number);
	    else if (c == 'q')
		die(SIGINT);
	    else
	    {
		i = c-'a';
		if (selection[i] == NOCARD)
		    beep();
		else
		{
		    movecard(selection[i], freeptr[i]);
		    freeptr[i]=selection[i];
		}
	    }
	}
    }

    move(PROMPTROW, 0);
    standout();
    (void)printw("Finished deal %d - type any character to continue...", deal_number);
    standend();
    (void) getch();
}
示例#4
0
static void ncurses_write_utf32(uint32_t ch)
{
#if defined HAVE_NCURSESW_NCURSES_H
    char buf[10];
    int bytes;
#endif

    if(ch == CACA_MAGIC_FULLWIDTH)
        return;

#if defined HAVE_NCURSESW_NCURSES_H
    bytes = caca_utf32_to_utf8(buf, ch);
    buf[bytes] = '\0';
    addstr(buf);
#else
    if(ch < 0x80)
    {
        addch(ch);
    }
    else
    {
        chtype cch;
        chtype cch2;

        cch = '?';
        cch2 = ' ';
        if ((ch > 0x0000ff00) && (ch < 0x0000ff5f))
        {
            cch = ch - 0x0000ff00 + ' ';
        }
        switch (ch)
        {
        case 0x000000a0: /* <nbsp> */
        case 0x00003000: /*   */
            cch = ' ';
            break;
        case 0x000000a3: /* £ */
            cch = ACS_STERLING;
            break;
        case 0x000000b0: /* ° */
            cch = ACS_DEGREE;
            break;
        case 0x000000b1: /* ± */
            cch = ACS_PLMINUS;
            break;
        case 0x000000b7: /* · */
        case 0x00002219: /* ∙ */
        case 0x000030fb: /* ・ */
            cch = ACS_BULLET;
            break;
        case 0x000003c0: /* π */
            cch = ACS_PI;
            break;
        case 0x00002018: /* ‘ */
        case 0x00002019: /* ’ */
            cch = '\'';
            break;
        case 0x0000201c: /* “ */
        case 0x0000201d: /* ” */
            cch = '"';
            break;
        case 0x00002190: /* ← */
            cch = ACS_LARROW;
            break;
        case 0x00002191: /* ↑ */
            cch = ACS_UARROW;
            break;
        case 0x00002192: /* → */
            cch = ACS_RARROW;
            break;
        case 0x00002193: /* ↓ */
            cch = ACS_DARROW;
            break;
        case 0x00002260: /* ≠ */
            cch = ACS_NEQUAL;
            break;
        case 0x00002261: /* ≡ */
            cch = '=';
            break;
        case 0x00002264: /* ≤ */
            cch = ACS_LEQUAL;
            break;
        case 0x00002265: /* ≥ */
            cch = ACS_GEQUAL;
            break;
        case 0x000023ba: /* ⎺ */
            cch = ACS_S1;
            cch2 = cch;
            break;
        case 0x000023bb: /* ⎻ */
            cch = ACS_S3;
            cch2 = cch;
            break;
        case 0x000023bc: /* ⎼ */
            cch = ACS_S7;
            cch2 = cch;
            break;
        case 0x000023bd: /* ⎽ */
            cch = ACS_S9;
            cch2 = cch;
            break;
        case 0x00002500: /* ─ */
        case 0x00002550: /* ═ */
            cch = ACS_HLINE;
            cch2 = cch;
            break;
        case 0x00002502: /* │ */
        case 0x00002551: /* ║ */
            cch = ACS_VLINE;
            break;
        case 0x0000250c: /* ┌ */
        case 0x00002552: /* ╒ */
        case 0x00002553: /* ╓ */
        case 0x00002554: /* ╔ */
            cch = ACS_ULCORNER;
            cch2 = ACS_HLINE;
            break;
        case 0x00002510: /* ┐ */
        case 0x00002555: /* ╕ */
        case 0x00002556: /* ╖ */
        case 0x00002557: /* ╗ */
            cch = ACS_URCORNER;
            break;
        case 0x00002514: /* └ */
        case 0x00002558: /* ╘ */
        case 0x00002559: /* ╙ */
        case 0x0000255a: /* ╚ */
            cch = ACS_LLCORNER;
            cch2 = ACS_HLINE;
            break;
        case 0x00002518: /* ┘ */
        case 0x0000255b: /* ╛ */
        case 0x0000255c: /* ╜ */
        case 0x0000255d: /* ╝ */
            cch = ACS_LRCORNER;
            break;
        case 0x0000251c: /* ├ */
        case 0x0000255e: /* ╞ */
        case 0x0000255f: /* ╟ */
        case 0x00002560: /* ╠ */
            cch = ACS_LTEE;
            cch2 = ACS_HLINE;
            break;
        case 0x00002524: /* ┤ */
        case 0x00002561: /* ╡ */
        case 0x00002562: /* ╢ */
        case 0x00002563: /* ╣ */
            cch = ACS_RTEE;
            break;
        case 0x0000252c: /* ┬ */
        case 0x00002564: /* ╤ */
        case 0x00002565: /* ╥ */
        case 0x00002566: /* ╦ */
            cch = ACS_TTEE;
            cch2 = ACS_HLINE;
            break;
        case 0x00002534: /* ┴ */
        case 0x00002567: /* ╧ */
        case 0x00002568: /* ╨ */
        case 0x00002569: /* ╩ */
            cch = ACS_BTEE;
            cch2 = ACS_HLINE;
            break;
        case 0x0000253c: /* ┼ */
        case 0x0000256a: /* ╪ */
        case 0x0000256b: /* ╫ */
        case 0x0000256c: /* ╬ */
            cch = ACS_PLUS;
            cch2 = ACS_HLINE;
            break;
        case 0x00002591: /* ░ */
            cch = ACS_BOARD;
            cch2 = cch;
            break;
        case 0x00002592: /* ▒ */
        case 0x00002593: /* ▓ */
            cch = ACS_CKBOARD;
            cch2 = cch;
            break;
        case 0x00002580: /* ▀ */
        case 0x00002584: /* ▄ */
        case 0x00002588: /* █ */
        case 0x0000258c: /* ▌ */
        case 0x00002590: /* ▐ */
        case 0x000025a0: /* ■ */
        case 0x000025ac: /* ▬ */
        case 0x000025ae: /* ▮ */
            cch = ACS_BLOCK;
            cch2 = cch;
            break;
        case 0x000025c6: /* ◆ */
        case 0x00002666: /* ♦ */
            cch = ACS_DIAMOND;
            break;
        case 0x00002022: /* • */
        case 0x000025cb: /* ○ */
        case 0x000025cf: /* ● */
        case 0x00002603: /* ☃ */
        case 0x0000263c: /* ☼ */
            cch = ACS_LANTERN;
            break;
        case 0x0000301c: /* 〜 */
            cch = '~';
            break;
        }
        addch(cch);
        if(caca_utf32_is_fullwidth(ch))
        {
            addch(cch2);
        }
    }
#endif
}
示例#5
0
文件: bs.c 项目: kusumi/DragonFlyBSD
static void
initgame(void)
{
    int i, j, unplaced;
    ship_t *ss;

    clear();
    mvaddstr(0,35,"BATTLESHIPS");
    move(PROMPTLINE + 2, 0);
    announceopts();

    bzero(board, sizeof(char) * BWIDTH * BDEPTH * 2);
    bzero(hits, sizeof(char) * BWIDTH * BDEPTH * 2);
    for (i = 0; i < SHIPTYPES; i++) {
		ss = cpuship + i;
		ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
		ss = plyship + i;
		ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
    }

    /* draw empty boards */
    mvaddstr(PYBASE - 2, PXBASE + 5, "Main Board");
    mvaddstr(PYBASE - 1, PXBASE - 3,numbers);
    for(i=0; i < BDEPTH; ++i)
    {
	mvaddch(PYBASE + i, PXBASE - 3, i + 'A');
#ifdef A_COLOR
	if (has_colors())
	    attron(COLOR_PAIR(COLOR_BLUE));
#endif /* A_COLOR */
	addch(' ');
	for (j = 0; j < BWIDTH; j++)
	    addstr(" . ");
#ifdef A_COLOR
	attrset(0);
#endif /* A_COLOR */
	addch(' ');
	addch(i + 'A');
    }
    mvaddstr(PYBASE + BDEPTH, PXBASE - 3,numbers);
    mvaddstr(CYBASE - 2, CXBASE + 7,"Hit/Miss Board");
    mvaddstr(CYBASE - 1, CXBASE - 3, numbers);
    for(i=0; i < BDEPTH; ++i)
    {
	mvaddch(CYBASE + i, CXBASE - 3, i + 'A');
#ifdef A_COLOR
	if (has_colors())
	    attron(COLOR_PAIR(COLOR_BLUE));
#endif /* A_COLOR */
	addch(' ');
	for (j = 0; j < BWIDTH; j++)
	    addstr(" . ");
#ifdef A_COLOR
	attrset(0);
#endif /* A_COLOR */
	addch(' ');
	addch(i + 'A');
    }

    mvaddstr(CYBASE + BDEPTH,CXBASE - 3,numbers);

    mvprintw(HYBASE,  HXBASE,
		    "To position your ships: move the cursor to a spot, then");
    mvprintw(HYBASE+1,HXBASE,
		    "type the first letter of a ship type to select it, then");
    mvprintw(HYBASE+2,HXBASE,
		    "type a direction ([hjkl] or [4862]), indicating how the");
    mvprintw(HYBASE+3,HXBASE,
		    "ship should be pointed. You may also type a ship letter");
    mvprintw(HYBASE+4,HXBASE,
		    "followed by `r' to position it randomly, or type `R' to");
    mvprintw(HYBASE+5,HXBASE,
		    "place all remaining ships randomly.");

    mvaddstr(MYBASE,   MXBASE, "Aiming keys:");
    mvaddstr(SYBASE,   SXBASE, "y k u    7 8 9");
    mvaddstr(SYBASE+1, SXBASE, " \\|/      \\|/ ");
    mvaddstr(SYBASE+2, SXBASE, "h-+-l    4-+-6");
    mvaddstr(SYBASE+3, SXBASE, " /|\\      /|\\ ");
    mvaddstr(SYBASE+4, SXBASE, "b j n    1 2 3");

    /* have the computer place ships */
    for(ss = cpuship; ss < cpuship + SHIPTYPES; ss++)
    {
	randomplace(COMPUTER, ss);
	placeship(COMPUTER, ss, FALSE);
    }

    ss = NULL;
    do {
	char c, docked[SHIPTYPES + 2], *cp = docked;

	/* figure which ships still wait to be placed */
	*cp++ = 'R';
	for (i = 0; i < SHIPTYPES; i++)
	    if (!plyship[i].placed)
		*cp++ = plyship[i].symbol;
	*cp = '\0';

	/* get a command letter */
	prompt(1, "Type one of [%s] to pick a ship.", docked+1);
	do {
	    c = getcoord(PLAYER);
	} while
	    (!strchr(docked, c));

	if (c == 'R')
	    ungetch('R');
	else
	{
	    /* map that into the corresponding symbol */
	    for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
		if (ss->symbol == c)
		    break;

	    prompt(1, "Type one of [hjklrR] to place your %s.", ss->name);
	    pgoto(cury, curx);
	}

	do {
	    c = getch();
	} while
	    (!strchr("hjklrR", c) || c == FF);

	if (c == FF)
	{
	    clearok(stdscr, TRUE);
	    refresh();
	}
	else if (c == 'r')
	{
	    prompt(1, "Random-placing your %s", ss->name);
	    randomplace(PLAYER, ss);
	    placeship(PLAYER, ss, TRUE);
	    error(NULL);
	    ss->placed = TRUE;
	}
	else if (c == 'R')
	{
	    prompt(1, "Placing the rest of your fleet at random...");
	    for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
		if (!ss->placed)
		{
		    randomplace(PLAYER, ss);
		    placeship(PLAYER, ss, TRUE);
		    ss->placed = TRUE;
		}
	    error(NULL);
	}
	else if (strchr("hjkl8462", c))
	{
	    ss->x = curx;
	    ss->y = cury;

	    switch(c)
	    {
	    case 'k': case '8': ss->dir = N; break;
	    case 'j': case '2': ss->dir = S; break;
	    case 'h': case '4': ss->dir = W; break;
	    case 'l': case '6': ss->dir = E; break;
	    }

	    if (checkplace(PLAYER, ss, TRUE))
	    {
		placeship(PLAYER, ss, TRUE);
		error(NULL);
		ss->placed = TRUE;
	    }
	}

	for (unplaced = i = 0; i < SHIPTYPES; i++)
	    unplaced += !plyship[i].placed;
    } while
	(unplaced);

    turn = rnd(2);

    mvprintw(HYBASE,  HXBASE,
		    "To fire, move the cursor to your chosen aiming point   ");
    mvprintw(HYBASE+1,  HXBASE,
		    "and strike any key other than a motion key.            ");
    mvprintw(HYBASE+2,  HXBASE,
		    "                                                       ");
    mvprintw(HYBASE+3,  HXBASE,
		    "                                                       ");
    mvprintw(HYBASE+4,  HXBASE,
		    "                                                       ");
    mvprintw(HYBASE+5,  HXBASE,
		    "                                                       ");

    prompt(0, "Press any key to start...");
    getch();
}
示例#6
0
/* Method proc. */
static int
method (JSVirtualMachine *vm, JSBuiltinInfo *builtin_info,
	void *instance_context, JSSymbol method,
	JSNode *result_return, JSNode *args)
{
  CursesCtx *ctx = builtin_info->obj_context;
  char *cp;

  /* The default result. */
  result_return->type = JS_BOOLEAN;
  result_return->u.vboolean = 1;

  if (method == ctx->s_addstr)
    {
      if (args->u.vinteger != 1)
	goto argument_error;
      if (args[1].type != JS_STRING)
	goto argument_type_error;

      cp = js_string_to_c_string (vm, &args[1]);
      addstr (cp);
      js_free (cp);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_attron)
    {
      if (args->u.vinteger != 1)
	goto argument_error;
      if (args[1].type != JS_INTEGER)
	goto argument_type_error;

      attron (args[1].u.vinteger);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_attroff)
    {
      if (args->u.vinteger != 1)
	goto argument_error;
      if (args[1].type != JS_INTEGER)
	goto argument_type_error;

      attroff (args[1].u.vinteger);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_beep)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      beep ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_cbreak)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      cbreak ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_clear)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      clear ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_clrtobot)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      clrtobot ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_clrtoeol)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      clrtoeol ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_echo)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      echo ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_endwin)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      endwin ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_getch)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      result_return->type = JS_INTEGER;
      result_return->u.vinteger = getch ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_initscr)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      if (initscr () == (WINDOW *) ERR)
	result_return->u.vboolean = 0;
    }
  /* ********************************************************************** */
  else if (method == ctx->s_keypad)
    {
      if (args->u.vinteger != 1)
	goto argument_error;
      if (args[1].type != JS_BOOLEAN)
	goto argument_type_error;

      keypad (stdscr, args->u.vboolean);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_move)
    {
      if (args->u.vinteger != 2)
	goto argument_error;
      if (args[1].type != JS_INTEGER || args[2].type != JS_INTEGER)
	goto argument_type_error;

      move (args[1].u.vinteger, args[2].u.vinteger);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_mvaddstr)
    {
      if (args->u.vinteger != 3)
	goto argument_error;
      if (args[1].type != JS_INTEGER || args[2].type != JS_INTEGER
	  || args[3].type != JS_STRING)
	goto argument_type_error;

      cp = js_string_to_c_string (vm, &args[3]);
      mvaddstr (args[1].u.vinteger, args[2].u.vinteger, cp);
      js_free (cp);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_mvaddsubstr)
    {
      int start, length;

      if (args->u.vinteger != 4 && args->u.vinteger != 5)
	goto argument_error;
      if (args[1].type != JS_INTEGER || args[2].type != JS_INTEGER
	  || args[3].type != JS_STRING
	  || args[4].type != JS_INTEGER)
	goto argument_type_error;

      start = args[4].u.vinteger;

      if (args->u.vinteger == 5)
	{
	  if (args[5].type != JS_INTEGER)
	    goto argument_type_error;

	  length = args[5].u.vinteger;
	  if (length < 0)
	    length = 0;
	}
      else
	length = args[3].u.vstring->len;

      if (start < 0)
	start += args[3].u.vstring->len;
      if (start < 0)
	start = 0;
      if (start > args[3].u.vstring->len)
	start = args[3].u.vstring->len;

      if (start + length > args[3].u.vstring->len)
	length = args[3].u.vstring->len - start;

      cp = js_malloc (vm, length + 1);
      memcpy (cp, args[3].u.vstring->data + start, length);
      cp[length] = '\0';
      mvaddstr (args[1].u.vinteger, args[2].u.vinteger, cp);
      js_free (cp);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_mvgetch)
    {
      if (args->u.vinteger != 2)
	goto argument_error;
      if (args[1].type != JS_INTEGER || args[2].type != JS_INTEGER)
	goto argument_type_error;

      result_return->type = JS_INTEGER;
      result_return->u.vinteger = mvgetch (args[1].u.vinteger,
					   args[2].u.vinteger);
    }
  /* ********************************************************************** */
  else if (method == ctx->s_nocbreak)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      nocbreak ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_noecho)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      noecho ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_refresh)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      refresh ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_standend)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      standend ();
    }
  /* ********************************************************************** */
  else if (method == ctx->s_standout)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      standout ();
    }
  /* ********************************************************************** */
  else if (method == vm->syms.s_toString)
    {
      if (args->u.vinteger != 0)
	goto argument_error;

      js_vm_make_static_string (vm, result_return, "Curses", 6);
    }
  /* ********************************************************************** */
  else
    return JS_PROPERTY_UNKNOWN;

  return JS_PROPERTY_FOUND;


  /*
   * Error handling.
   */

 argument_error:
  sprintf (vm->error, "Curses.%s(): illegal amount of arguments",
	   js_vm_symname (vm, method));
  js_vm_error (vm);

 argument_type_error:
  sprintf (vm->error, "Curses.%s(): illegal argument",
	   js_vm_symname (vm, method));
  js_vm_error (vm);

  /* NOTREACHED. */
  return 0;
}
示例#7
0
static int
dialog_switch_pos (dialog_t diag, dialog_pos_t new_pos)
{
  if (new_pos != diag->pos)
    {
      switch (diag->pos)
	{
	case DIALOG_POS_OK:
	  move (diag->ok_y, diag->ok_x);
	  addstr (diag->ok);
	  break;
	case DIALOG_POS_NOTOK:
          if (diag->notok)
            {
              move (diag->notok_y, diag->notok_x);
              addstr (diag->notok);
            }
	  break;
	case DIALOG_POS_CANCEL:
          if (diag->cancel)
            {
              move (diag->cancel_y, diag->cancel_x);
              addstr (diag->cancel);
            }
	  break;
	default:
	  break;
	}
      diag->pos = new_pos;
      switch (diag->pos)
	{
	case DIALOG_POS_PIN:
	  move (diag->pin_y, diag->pin_x + diag->pin_loc);
	  set_cursor_state (1);
	  break;
	case DIALOG_POS_OK:
	  set_cursor_state (0);
	  move (diag->ok_y, diag->ok_x);
	  standout ();
	  addstr (diag->ok);
	  standend ();
	  move (diag->ok_y, diag->ok_x);
	  break;
	case DIALOG_POS_NOTOK:
          if (diag->notok)
            {
              set_cursor_state (0);
              move (diag->notok_y, diag->notok_x);
              standout ();
              addstr (diag->notok);
              standend ();
              move (diag->notok_y, diag->notok_x);
            }
	  break;
	case DIALOG_POS_CANCEL:
          if (diag->cancel)
            {
              set_cursor_state (0);
              move (diag->cancel_y, diag->cancel_x);
              standout ();
              addstr (diag->cancel);
              standend ();
              move (diag->cancel_y, diag->cancel_x);
            }
	  break;
	case DIALOG_POS_NONE:
	  set_cursor_state (0);
	  break;
	}
      refresh ();
    }
  return 0;
}
void WDL_CursesEditor::draw(int lineidx)
{
  const int VISIBLE_LINES = getVisibleLines();

  int paney[2], paneh[2];
  const int pane_divy=GetPaneDims(paney, paneh);

#ifdef WDL_IS_FAKE_CURSES
  if (m_cursesCtx)
  {
    CURSES_INSTANCE->offs_y[0]=m_paneoffs_y[0];
    CURSES_INSTANCE->offs_y[1]=m_paneoffs_y[1];
    CURSES_INSTANCE->div_y=pane_divy;
    CURSES_INSTANCE->tot_y=m_text.GetSize();

    CURSES_INSTANCE->scrollbar_topmargin = m_top_margin;
    CURSES_INSTANCE->scrollbar_botmargin = m_bottom_margin;
  }
#endif

  attrset(A_NORMAL);

  if (lineidx >= 0)
  {
    int comment_state = GetCommentStateForLineStart(lineidx);
    WDL_FastString *s=m_text.Get(lineidx);
    if (s)
    {
      int y=lineidx-m_paneoffs_y[0];
      if (y >= 0 && y < paneh[0])
      {
        doDrawString(paney[0]+y, 0, lineidx, s->Get(), COLS, &comment_state, min(s->GetLength(), m_offs_x));
      } 
      y=lineidx-m_paneoffs_y[1];
      if (y >= 0 && y < paneh[1])
      {
        doDrawString(paney[1]+y, 0, lineidx, s->Get(), COLS, &comment_state, min(s->GetLength(), m_offs_x));
      }
    }
    return;
  }

  __curses_invalidatefull((win32CursesCtx*)m_cursesCtx,false);

  draw_top_line();

  attrset(A_NORMAL);
  bkgdset(A_NORMAL);

  move(m_top_margin,0);
  clrtoeol();

  int pane, i;
  for (pane=0; pane < 2; ++pane)
  {
    int ln=m_paneoffs_y[pane];
    int y=paney[pane];
    int h=paneh[pane];

    int comment_state=GetCommentStateForLineStart(ln);
 
    for(i=0; i < h; ++i, ++ln, ++y)
    { 
      WDL_FastString *s=m_text.Get(ln);
      if (!s) 
      {
        move(y,0);
        clrtoeol();
      }
      else
      {
        doDrawString(y,0,ln,s->Get(),COLS,&comment_state,min(m_offs_x,s->GetLength()));
      }
    }
  }

  attrset(m_color_bottomline);
  bkgdset(m_color_bottomline);

  if (m_bottom_margin>0)
  {
    move(LINES-1, 0);
#define BOLD(x) { attrset(m_color_bottomline|A_BOLD); addstr(x); attrset(m_color_bottomline&~A_BOLD); }
    if (m_selecting) 
    {
      mvaddstr(LINES-1,0,"SELECTING  ESC:cancel Ctrl+(");
      BOLD("C"); addstr("opy ");
      BOLD("X"); addstr(":cut ");
      BOLD("V"); addstr(":paste)");
    }
    else 
    {
      mvaddstr(LINES-1, 0, "Ctrl+(");

      if (m_pane_div <= 0.0 || m_pane_div >= 1.0) 
      {
        BOLD("P"); addstr("ane ");
      }
      else
      {
        BOLD("O"); addstr("therpane ");
        addstr("no"); BOLD("P"); addstr("anes ");
      }
      BOLD("F"); addstr("ind ");
      addstr("ma"); BOLD("T"); addstr("ch");
      draw_bottom_line();
      addstr(")");
    }
#undef BOLD
    clrtoeol();
  }

  attrset(0);
  bkgdset(0);

  __curses_invalidatefull((win32CursesCtx*)m_cursesCtx,true);
}
示例#9
0
文件: run.c 项目: ryo/netbsd-src
int
run_program(int flags, const char *cmd, ...)
{
	va_list ap;
	struct winsize win;
	int ret;
	WINDOW *actionwin = NULL;
	char *scmd;
	char **args;
	const char *errstr = NULL;

	va_start(ap, cmd);
	vasprintf(&scmd, cmd, ap);
	va_end(ap);
	if (scmd == NULL)
		err(1, "vasprintf(&scmd, \"%s\", ...)", cmd);

	args = make_argv(scmd);

	/* Make curses save tty settings */
	def_prog_mode();

	(void)ioctl(STDIN_FILENO, TIOCGWINSZ, &win);
	/* Apparently, we sometimes get 0x0 back, and that's not useful */
	if (win.ws_row == 0)
		win.ws_row = 24;
	if (win.ws_col == 0)
		win.ws_col = 80;

	if ((flags & RUN_DISPLAY) != 0) {
		if (flags & RUN_FULLSCREEN) {
			wclear(stdscr);
			clearok(stdscr, 1);
			touchwin(stdscr);
			refresh();
			actionwin = stdscr;
		} else
			actionwin = show_cmd(scmd, &win);
	} else
		win.ws_row -= 4;

	ret = launch_subwin(&actionwin, args, &win, flags, scmd, &errstr);
	fpurge(stdin);

	/* If the command failed, show command name */
	if (actionwin == NULL && ret != 0 && !(flags & RUN_ERROR_OK))
		actionwin = show_cmd(scmd, &win);

	if (actionwin != NULL) {
		int y, x;
		getyx(actionwin, y, x);
		if (actionwin != stdscr)
			mvaddstr(0, 4, msg_string(MSG_Status));
		if (ret != 0) {
			if (actionwin == stdscr && x != 0)
				addstr("\n");
			x = 1;	/* force newline below */
			standout();
			addstr(errstr);
			standend();
		} else {
			if (actionwin != stdscr) {
				standout();
				addstr(msg_string(MSG_Finished));
				standend();
			}
		}
		clrtoeol();
		refresh();
		if ((ret != 0 && !(flags & RUN_ERROR_OK)) ||
		    (y + x != 0 && !(flags & RUN_PROGRESS))) {
			if (actionwin != stdscr)
				move(getbegy(actionwin) - 2, 5);
			else if (x != 0)
				addstr("\n");
			addstr(msg_string(MSG_Hit_enter_to_continue));
			refresh();
			getchar();
		} else {
			if (y + x != 0) {
				/* give user 1 second to see messages */
				refresh();
				sleep(1);
			}
		}
	}

	/* restore tty setting we saved earlier */
	reset_prog_mode();

	/* clean things up */
	if (actionwin != NULL) {
		if (actionwin != stdscr)
			delwin(actionwin);
		if (errstr == 0 || !(flags & RUN_NO_CLEAR)) {
			wclear(stdscr);
			touchwin(stdscr);
			clearok(stdscr, 1);
			refresh();
		}
	}

	free(scmd);
	free_argv(args);

	if (ret != 0 && flags & RUN_FATAL)
		exit(ret);
	return ret;
}
示例#10
0
void AddString(const char *text)
{
	addstr(text);
}
int WDL_CursesEditor::onChar(int c)
{
  if (m_state == -3 || m_state == -4)
  {
    switch (c)
    {
       case '\r': case '\n':
         m_state=0;
         runSearch();
       break;
       case 27: 
         m_state=0; 
         draw();
         setCursor();
         draw_message("Find cancelled.");
       break;
       case KEY_BACKSPACE: if (s_search_string[0]) s_search_string[strlen(s_search_string)-1]=0; m_state=-4; break;
       default: 
         if (VALIDATE_TEXT_CHAR(c)) 
         { 
           int l=m_state == -3 ? 0 : strlen(s_search_string); 
           m_state = -4;
           if (l < (int)sizeof(s_search_string)-1) { s_search_string[l]=c; s_search_string[l+1]=0; } 
         } 
        break;
     }
     if (m_state)
     {
       attrset(m_color_message);
       bkgdset(m_color_message);
       mvaddstr(LINES-1,29,s_search_string);
       clrtoeol(); 
       attrset(0);
       bkgdset(0);
     }
     return 0;
  }
  if (c==KEY_DOWN || c==KEY_UP || c==KEY_PPAGE||c==KEY_NPAGE || c==KEY_RIGHT||c==KEY_LEFT||c==KEY_HOME||c==KEY_END)
  {
    if (SHIFT_KEY_DOWN)      
    {
      if (!m_selecting)
      {
        m_select_x2=m_select_x1=m_curs_x; m_select_y2=m_select_y1=m_curs_y;
        m_selecting=1;
      }
    }
    else if (m_selecting) { m_selecting=0; draw(); }
  }

  switch(c)
  {
    case 'O'-'A'+1:
      if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
      {
        if (m_pane_div <= 0.0 || m_pane_div >= 1.0)
        {
          onChar('P'-'A'+1);
        }
        if (m_pane_div > 0.0 && m_pane_div < 1.0) 
        {
          m_curpane=!m_curpane;
          draw();
          draw_status_state();
          int paney[2], paneh[2];
          GetPaneDims(paney, paneh);
          if (m_curs_y-m_paneoffs_y[m_curpane] < 0) m_curs_y=m_paneoffs_y[m_curpane];
          else if (m_curs_y-m_paneoffs_y[m_curpane] >= paneh[m_curpane]) m_curs_y=paneh[m_curpane]+m_paneoffs_y[m_curpane]-1;
          setCursor();
        }
      }
    break;
    case 'P'-'A'+1:
      if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
      {
        if (m_pane_div <= 0.0 || m_pane_div >= 1.0) 
        {
          m_pane_div=0.5;
          m_paneoffs_y[1]=m_paneoffs_y[0];
        }
        else 
        {
          m_pane_div=1.0;
          if (m_curpane) m_paneoffs_y[0]=m_paneoffs_y[1];
          m_curpane=0;
        }
        draw();
        draw_status_state();

        int paney[2], paneh[2];
        const int pane_divy=GetPaneDims(paney, paneh);
        setCursor();
      }
    break;
    
    case 407:
    case 'Z'-'A'+1:
      if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
      {
        if (m_undoStack_pos > 0)
        {
           m_undoStack_pos--;
           loadUndoState(m_undoStack.Get(m_undoStack_pos));
           draw();
           setCursor();
           char buf[512];
           snprintf(buf,sizeof(buf),"Undid action - %d items in undo buffer",m_undoStack_pos);
           draw_message(buf);
        }
        else 
        {
          draw_message("Can't Undo");
        }   
        break;
      }
    // fall through
    case 'Y'-'A'+1:
      if ((c == 'Z'-'A'+1 || !SHIFT_KEY_DOWN) && !ALT_KEY_DOWN)
      {
        if (m_undoStack_pos < m_undoStack.GetSize()-1)
        {
          m_undoStack_pos++;
          loadUndoState(m_undoStack.Get(m_undoStack_pos));
          draw();
          setCursor();
          char buf[512];
          snprintf(buf,sizeof(buf),"Redid action - %d items in redo buffer",m_undoStack.GetSize()-m_undoStack_pos-1);
          draw_message(buf);
        }
        else 
        {
          draw_message("Can't Redo");  
        }
      }
    break;
    case KEY_IC:
      if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
      {
        s_overwrite=!s_overwrite;
        setCursor();
        break;
      }
      // fqll through
    case 'V'-'A'+1:
      if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
      {
        // generate a m_clipboard using win32 clipboard data
        WDL_PtrList<const char> lines;
        WDL_String buf;
#ifdef WDL_IS_FAKE_CURSES
        if (CURSES_INSTANCE)
        {
          OpenClipboard(CURSES_INSTANCE->m_hwnd);
          HANDLE h=GetClipboardData(CF_TEXT);
          if (h)
          {
            char *t=(char *)GlobalLock(h);
            int s=GlobalSize(h);
            buf.Set(t,s);
            GlobalUnlock(t);        
          }
          CloseClipboard();
        }
        else
#endif
        {
          buf.Set(s_fake_clipboard.Get());
        }

        if (buf.Get() && buf.Get()[0])
        {
          char *src=buf.Get();
          while (*src)
          {
            char *seek=src;
            while (*seek && *seek != '\r' && *seek != '\n') seek++;
            char hadclr=*seek;
            if (*seek) *seek++=0;
            lines.Add(src);

            if (hadclr == '\r' && *seek == '\n') seek++;

            if (hadclr && !*seek)
            {
              lines.Add("");
            }
            src=seek;
          }
        }
        if (lines.GetSize())
        {
          removeSelect();
          // insert lines at m_curs_y,m_curs_x
          if (m_curs_y >= m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
          if (m_curs_y < 0) m_curs_y=0;

          preSaveUndoState();
          WDL_FastString poststr;
          int x;
          int indent_to_pos = -1;
          for (x = 0; x < lines.GetSize(); x ++)
          {
            WDL_FastString *str=m_text.Get(m_curs_y);
            const char *tstr=lines.Get(x);
            if (!tstr) tstr="";
            if (!x)
            {
              if (str)
              {
                if (m_curs_x < 0) m_curs_x=0;
                int tmp=str->GetLength();
                if (m_curs_x > tmp) m_curs_x=tmp;
  
                poststr.Set(str->Get()+m_curs_x);
                str->SetLen(m_curs_x);

                const char *p = str->Get();
                while (*p == ' ' || *p == '\t') p++;
                if (!*p && p > str->Get())
                {
                  if (lines.GetSize()>1)
                  {
                    while (*tstr == ' ' || *tstr == '\t') tstr++;
                  }
                  indent_to_pos = m_curs_x;
                }

                str->Append(tstr);
              }
              else
              {
                m_text.Insert(m_curs_y,(str=new WDL_FastString(tstr)));
              }
              if (lines.GetSize() > 1)
              {
                m_curs_y++;
              }
              else
              {
                m_curs_x = str->GetLength();
                str->Append(poststr.Get());
              }
           }
           else if (x == lines.GetSize()-1)
           {
             WDL_FastString *s=newIndentedFastString(tstr,indent_to_pos);
             m_curs_x = s->GetLength();
             s->Append(poststr.Get());
             m_text.Insert(m_curs_y,s);
           }
           else
           {
             m_text.Insert(m_curs_y,newIndentedFastString(tstr,indent_to_pos));
             m_curs_y++;
           }
         }
         draw();
         setCursor();
         draw_message("Pasted");
         saveUndoState();
       }
       else 
       {
         setCursor();
         draw_message("Clipboard empty");
       }
     }
  break;

  case KEY_DC:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
    {
      WDL_FastString *s;
      if (m_selecting)
      {
        preSaveUndoState();
        removeSelect();
        draw();
        saveUndoState();
        setCursor();
      }
      else if ((s=m_text.Get(m_curs_y)))
      {
        if (m_curs_x < s->GetLength())
        {
          preSaveUndoState();

          bool hadCom = LineCanAffectOtherLines(s->Get(),m_curs_x,1); 
          s->DeleteSub(m_curs_x,1);
          if (!hadCom) hadCom = LineCanAffectOtherLines(s->Get(),-1,-1);
          draw(hadCom ? -1 : m_curs_y);
          saveUndoState();
          setCursor();
        }
        else // append next line to us
        {
          if (m_curs_y < m_text.GetSize()-1)
          {
            preSaveUndoState();

            WDL_FastString *nl=m_text.Get(m_curs_y+1);
            if (nl)
            {
              s->Append(nl->Get());
            }
            m_text.Delete(m_curs_y+1,true);

            draw();
            saveUndoState();
            setCursor();
          }
        }
      }
      break;
    }
  case 'C'-'A'+1:
  case 'X'-'A'+1:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN && m_selecting)
    {
      if (c!= 'C'-'A'+1) m_selecting=0;
      int miny,maxy,minx,maxx;
      int x;
      getselectregion(minx,miny,maxx,maxy);
      const char *status="";
      char statusbuf[512];

      if (minx != maxx|| miny != maxy) 
      {
        int bytescopied=0;
        s_fake_clipboard.Set("");

        int lht=0,fht=0;
        if (c != 'C'-'A'+1) preSaveUndoState();

        for (x = miny; x <= maxy; x ++)
        {
          WDL_FastString *s=m_text.Get(x);
          if (s) 
          {
            const char *str=s->Get();
            int sx,ex;
            if (x == miny) sx=max(minx,0);
            else sx=0;
            int tmp=s->GetLength();
            if (sx > tmp) sx=tmp;
      
            if (x == maxy) ex=min(maxx,tmp);
            else ex=tmp;
      
            bytescopied += ex-sx + (x!=maxy);
            if (s_fake_clipboard.Get() && s_fake_clipboard.Get()[0]) s_fake_clipboard.Append("\r\n");
            s_fake_clipboard.Append(ex-sx?str+sx:"",ex-sx);

            if (c != 'C'-'A'+1)
            {
              if (sx == 0 && ex == tmp) // remove entire line
              {
                m_text.Delete(x,true);
                if (x==miny) miny--;
                x--;
                maxy--;
              }
              else { if (x==miny) fht=1; if (x == maxy) lht=1; s->DeleteSub(sx,ex-sx); }
            }
          }
        }
        if (fht && lht && miny+1 == maxy)
        {
          m_text.Get(miny)->Append(m_text.Get(maxy)->Get());
          m_text.Delete(maxy,true);
        }
        if (c != 'C'-'A'+1)
        {
          m_curs_y=miny;
          if (m_curs_y < 0) m_curs_y=0;
          m_curs_x=minx;
          saveUndoState();
          snprintf(statusbuf,sizeof(statusbuf),"Cut %d bytes",bytescopied);
        }
        else
          snprintf(statusbuf,sizeof(statusbuf),"Copied %d bytes",bytescopied);

#ifdef WDL_IS_FAKE_CURSES
        if (CURSES_INSTANCE)
        {
          int l=s_fake_clipboard.GetLength()+1;
          HANDLE h=GlobalAlloc(GMEM_MOVEABLE,l);
          void *t=GlobalLock(h);
          memcpy(t,s_fake_clipboard.Get(),l);
          GlobalUnlock(h);
          OpenClipboard(CURSES_INSTANCE->m_hwnd);
          EmptyClipboard();
          SetClipboardData(CF_TEXT,h);
          CloseClipboard();
        }
#endif

        status=statusbuf;
      }
      else status="No selection";

      draw();
      setCursor();
      draw_message(status);
    }
  break;
  case 'A'-'A'+1:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
    {
      m_selecting=1;
      m_select_x1=0;
      m_select_y1=0;
      m_select_y2=m_text.GetSize()-1;
      m_select_x2=0;
      if (m_text.Get(m_select_y2))
        m_select_x2=m_text.Get(m_select_y2)->GetLength();
      draw();
      setCursor();
    }
  break;
  case 27:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN && m_selecting)
    {
      m_selecting=0;
      draw();
      setCursor();
      break;
    }
  break;
  case KEY_F3:
  case 'G'-'A'+1:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN && s_search_string[0])
    {
      runSearch();
      return 0;
    }
  // fall through
  case 'F'-'A'+1:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
    {
      draw_message("");
      attrset(m_color_message);
      bkgdset(m_color_message);
      mvaddstr(LINES-1,0,"Find string (ESC to cancel): ");
      if (m_selecting && m_select_y1==m_select_y2)
      {
        WDL_FastString* s=m_text.Get(m_select_y1);
        if (s)
        {
          const char* p=s->Get();
          int xlo=min(m_select_x1, m_select_x2);
          int xhi=max(m_select_x1, m_select_x2);
          int i;
          for (i=xlo; i < xhi; ++i)
          {
            if (!isalnum(p[i]) && p[i] != '_') break;
          }
          if (i == xhi && xhi > xlo && xhi-xlo < sizeof(s_search_string))
          {
            lstrcpyn(s_search_string, p+xlo, xhi-xlo+1);
          }
        }
      }
      addstr(s_search_string);
      clrtoeol();
      attrset(0);
      bkgdset(0);
      m_state=-3; // find, initial (m_state=4 when we've typed something)
    }
  break;
  case KEY_DOWN:
    {
      if (CTRL_KEY_DOWN)
      {
        int paney[2], paneh[2];
        GetPaneDims(paney, paneh);
        int maxscroll=m_text.GetSize()-paneh[m_curpane]+4;
        if (m_paneoffs_y[m_curpane] < maxscroll-1)
        {
          m_paneoffs_y[m_curpane]++;
          if (m_curs_y < m_paneoffs_y[m_curpane]) m_curs_y=m_paneoffs_y[m_curpane];
          draw();
        }
      }
      else
      {
        m_curs_y++;
        if (m_curs_y>=m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
        if (m_curs_y < 0) m_curs_y=0;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor(1);
    }
  break;
  case KEY_UP:
    {
      if (CTRL_KEY_DOWN)
      {
        if (m_paneoffs_y[m_curpane] > 0)
        {
          int paney[2], paneh[2];
          GetPaneDims(paney, paneh);
          m_paneoffs_y[m_curpane]--;
          if (m_curs_y >  m_paneoffs_y[m_curpane]+paneh[m_curpane]-1) m_curs_y = m_paneoffs_y[m_curpane]+paneh[m_curpane]-1;
          if (m_curs_y < 0) m_curs_y=0;
          draw();
        }
      }
      else
      {
        if(m_curs_y>0) m_curs_y--;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor(1);
    }
  break;
  case KEY_PPAGE:
    {
      if (m_curs_y > m_paneoffs_y[m_curpane])
      {
        m_curs_y=m_paneoffs_y[m_curpane];
        if (m_curs_y < 0) m_curs_y=0;
      }
      else 
      {
        int paney[2], paneh[2];
        GetPaneDims(paney, paneh);
        m_curs_y -= paneh[m_curpane];
        if (m_curs_y < 0) m_curs_y=0;
        m_paneoffs_y[m_curpane]=m_curs_y;
      }
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; }
      draw();
      setCursor(1);
    }
  break; 
  case KEY_NPAGE:
    {
      int paney[2], paneh[2]; 
      GetPaneDims(paney, paneh);
      if (m_curs_y >= m_paneoffs_y[m_curpane]+paneh[m_curpane]-1) m_paneoffs_y[m_curpane]=m_curs_y-1;
      m_curs_y = m_paneoffs_y[m_curpane]+paneh[m_curpane]-1;
      if (m_curs_y >= m_text.GetSize()) m_curs_y=m_text.GetSize()-1;
      if (m_curs_y < 0) m_curs_y=0;
      if (m_selecting) { setCursor(1); m_select_x2=m_curs_x; m_select_y2=m_curs_y; }
      draw();
      setCursor(1);
    }
  break;
  case KEY_RIGHT:
    {
      if (1) // wrap across lines
      {
        WDL_FastString *s = m_text.Get(m_curs_y);
        if (s && m_curs_x >= s->GetLength() && m_curs_y < m_text.GetSize()) { m_curs_y++; m_curs_x = -1; }
      }

      if(m_curs_x<0) 
      {
        m_curs_x=0;
      }
      else
      {
        if (CTRL_KEY_DOWN)
        {
          WDL_FastString *s = m_text.Get(m_curs_y);
          if (!s||m_curs_x >= s->GetLength()) break;
          int lastType = categorizeCharForWordNess(s->Get()[m_curs_x++]);
          while (m_curs_x < s->GetLength())
          {
            int thisType = categorizeCharForWordNess(s->Get()[m_curs_x]);
            if (thisType != lastType && thisType != 0) break;
            lastType=thisType;
            m_curs_x++;
          }
        }
        else 
        {
          m_curs_x++;
        }
      }
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_LEFT:
    {
      bool doMove=true;
      if (1) // wrap across lines
      {
        WDL_FastString *s = m_text.Get(m_curs_y);
        if (s && m_curs_y>0 && m_curs_x == 0) 
        { 
          s = m_text.Get(--m_curs_y);
          if (s) 
          {
            m_curs_x = s->GetLength(); 
            doMove=false;
          }
        }
      }

      if(m_curs_x>0 && doMove) 
      {
        if (CTRL_KEY_DOWN)
        {
          WDL_FastString *s = m_text.Get(m_curs_y);
          if (!s) break;
          if (m_curs_x > s->GetLength()) m_curs_x = s->GetLength();
          m_curs_x--;

          int lastType = categorizeCharForWordNess(s->Get()[m_curs_x--]);
          while (m_curs_x >= 0)
          {
            int thisType = categorizeCharForWordNess(s->Get()[m_curs_x]);
            if (thisType != lastType && lastType != 0) break;
            lastType=thisType;
            m_curs_x--;
          }
          m_curs_x++;
        }
        else 
        {
          m_curs_x--;
        }
      }
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_HOME:
    {
      m_curs_x=0;
      if (CTRL_KEY_DOWN) m_curs_y=0;
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_END:
    {
      if (m_text.Get(m_curs_y)) m_curs_x=m_text.Get(m_curs_y)->GetLength();
      if (CTRL_KEY_DOWN) m_curs_y=m_text.GetSize();
      if (m_selecting) { setCursor(); m_select_x2=m_curs_x; m_select_y2=m_curs_y; draw(); }
      setCursor();
    }
  break;
  case KEY_BACKSPACE: // backspace, baby
    if (m_selecting)
    {
      preSaveUndoState();
      removeSelect();
      draw();
      saveUndoState();
      setCursor();
    }
    else if (m_curs_x > 0)
    {
      WDL_FastString *tl=m_text.Get(m_curs_y);
      if (tl)
      {
        preSaveUndoState();

        bool hadCom = LineCanAffectOtherLines(tl->Get(), m_curs_x-1,1);
        tl->DeleteSub(--m_curs_x,1);
        if (!hadCom) hadCom = LineCanAffectOtherLines(tl->Get(),-1,-1);
        draw(hadCom?-1:m_curs_y);
        saveUndoState();
        setCursor();
      }
    }
    else // append current line to previous line
    {
      WDL_FastString *fl=m_text.Get(m_curs_y-1), *tl=m_text.Get(m_curs_y);
      if (!tl) 
      {
        m_curs_y--;
        if (fl) m_curs_x=fl->GetLength();
        draw();
        saveUndoState();
        setCursor();
      }
      else if (fl)
      {
        preSaveUndoState();
        m_curs_x=fl->GetLength();
        fl->Append(tl->Get());

        m_text.Delete(m_curs_y--,true);
        draw();
        saveUndoState();
        setCursor();
      }
    }
  break;
  case 'L'-'A'+1:
    if (!SHIFT_KEY_DOWN && !ALT_KEY_DOWN)
    {
      draw();
      setCursor();
    }
  break;
  case 13: //KEY_ENTER:
    //insert newline
    preSaveUndoState();

    if (m_selecting) { removeSelect(); draw(); setCursor(); }
    if (m_curs_y >= m_text.GetSize())
    {
      m_curs_y=m_text.GetSize();
      m_text.Add(new WDL_FastString);
    }
    if (s_overwrite)
    {
      WDL_FastString *s = m_text.Get(m_curs_y);
      int plen=0;
      const char *pb=NULL;
      if (s)
      {
        pb = s->Get();
        while (plen < m_curs_x && (pb[plen]== ' ' || pb[plen] == '\t')) plen++;
      }
      if (++m_curs_y >= m_text.GetSize())
      {
        m_curs_y = m_text.GetSize();
        WDL_FastString *ns=new WDL_FastString;
        if (plen>0) ns->Set(pb,plen);
        m_text.Insert(m_curs_y,ns);
      }
      s = m_text.Get(m_curs_y);
      if (s && plen > s->GetLength()) plen=s->GetLength();
      m_curs_x=plen;
    }
    else 
    {
      WDL_FastString *s = m_text.Get(m_curs_y);
      if (s)
      {
        if (m_curs_x > s->GetLength()) m_curs_x = s->GetLength();
        WDL_FastString *nl = new WDL_FastString();
        int plen=0;
        const char *pb = s->Get();
        while (plen < m_curs_x && (pb[plen]== ' ' || pb[plen] == '\t')) plen++;

        if (plen>0) nl->Set(pb,plen);

        nl->Append(pb+m_curs_x);
        m_text.Insert(++m_curs_y,nl);
        s->SetLen(m_curs_x);
        m_curs_x=plen;
      }
    }
    m_offs_x=0;

    draw();
    saveUndoState();
    setCursor();
  break;
  case '\t':
    if (m_selecting)
    {
      preSaveUndoState();

      bool isRev = !!(GetAsyncKeyState(VK_SHIFT)&0x8000);
      indentSelect(isRev?-m_indent_size:m_indent_size);
      // indent selection:
      draw();
      setCursor();
      saveUndoState();
      break;
    }
  default:
    //insert char
    if(VALIDATE_TEXT_CHAR(c))
    { 
      preSaveUndoState();

      if (m_selecting) { removeSelect(); draw(); setCursor(); }
      if (!m_text.Get(m_curs_y)) m_text.Insert(m_curs_y,new WDL_FastString);

      WDL_FastString *ss;
      if ((ss=m_text.Get(m_curs_y)))
      {
        char str[64];
        int slen ;
        if (c == '\t') 
        {
          slen = min(m_indent_size,64);
          if (slen<1) slen=1;
          int x; 
          for(x=0;x<slen;x++) str[x]=' ';
        }
        else
        {
          str[0]=c;
          slen = 1;
        }


        bool hadCom = LineCanAffectOtherLines(ss->Get(),-1,-1);
        if (s_overwrite)
        {
          if (!hadCom) hadCom = LineCanAffectOtherLines(ss->Get(),m_curs_x,slen);
          ss->DeleteSub(m_curs_x,slen);
        }
        ss->Insert(str,m_curs_x,slen);
        if (!hadCom) hadCom = LineCanAffectOtherLines(ss->Get(),m_curs_x,slen);

        m_curs_x += slen;

        draw(hadCom ? -1 : m_curs_y);
      }
      saveUndoState();
      setCursor();
    }
    break;
  }
  return 0;
}
/* base - liberal agenda */
bool liberalagenda(signed char won)
{
   int page=0, y;

   while(true)
   {
      erase();
      if(won==1)
      {
         set_color(COLOR_GREEN,COLOR_BLACK,1);
         move(0,0);
         addstr("The Triumph of the Liberal Agenda");
         music.play(MUSIC_VICTORY);
      }
      else if(won==-1||won==-2)
      {
         set_color(COLOR_RED,COLOR_BLACK,1);
         move(0,0);
         addstr("The Abject Failure of the Liberal Agenda");
         if(won==-1) music.play(MUSIC_REAGANIFIED);
         if(won==-2) music.play(MUSIC_STALINIZED);
      }
      else
      {
         set_color(COLOR_WHITE,COLOR_BLACK,1);
         move(0,0);
         addstr("The Status of the Liberal Agenda");
         music.play(MUSIC_LIBERALAGENDA);
      }

      if(page<0) page=PAGENUM-1;
      if(page>=PAGENUM) page=0;

      switch(page)
      {
      case PAGE_LEADERS:
      {

         move(1,0);
         addstr("ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»ÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄ¿");
         move(2,0);
         addstr("º GENERAL SUMMARY º ISSUES A ³ ISSUES B ³");
         move(3,0);
         addstr("¼                 ÈÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ");

         signed char align=exec[EXEC_PRESIDENT];
         set_alignment_color(align,true);
         move(5,0);
         if(won==-1) addstr("King: ");
         else if(won==-2) addstr("General Secretary: ");
         else
         {
            addstr("President ");
            if(execterm==1)addstr("(1st Term):");
            else addstr("(2nd Term):");
         }
         if(won==-2) move(5,30);
         else move(5,25);
         addstr(execname[EXEC_PRESIDENT]);

         align=exec[EXEC_VP];
         set_alignment_color(align,true);
         move(6,0);
         if(won==-1) addstr("Minister of Love: ");
         else if(won==-2) addstr("Premier: ");
         else addstr("Vice President: ");
         if(won==-2) move(6,30);
         else move(6,25);
         addstr(execname[EXEC_VP]);

         align=exec[EXEC_STATE];
         set_alignment_color(align,true);
         move(7,0);
         if(won==-1) addstr("Minister of Peace: ");
         else if(won==-2) addstr("Foreign Affairs Commissar: ");
         else addstr("Secretary of State: ");
         if(won==-2) move(7,30);
         else move(7,25);
         addstr(execname[EXEC_STATE]);

         align=exec[EXEC_ATTORNEY];
         set_alignment_color(align,true);
         move(8,0);
         if(won==-1) addstr("Minister of Truth: ");
         else if(won==-2) addstr("Internal Affairs Commissar: ");
         else addstr("Attorney General: ");
         if(won==-2) move(8,30);
         else move(8,25);
         addstr(execname[EXEC_ATTORNEY]);

         if(won==-1)
         {
            set_color(COLOR_RED,COLOR_BLACK,1);
            move(10,0);
            addstr("The Congress consists of CEOs and televangelists.");
         }
         else if(won==-2)
         {
            set_color(COLOR_RED,COLOR_BLACK,1);
            move(10,0);
            addstr("The Congress consists of Stalinist Party loyalists.");
         }
         else
         {
            int housemake[6]={0,0,0,0,0,0};
            for(int h=0;h<HOUSENUM;h++) housemake[house[h]+2]++;
            if(housemake[5]+MIN(housemake[0],housemake[4])>=HOUSEMAJORITY) align=ALIGN_STALINIST; // Stalinists have a majority (perhaps with help from extremists on both sides)
            else if(housemake[0]>=HOUSEMAJORITY) align=ALIGN_ARCHCONSERVATIVE; // Arch-Conservatives have a majority
            else if(housemake[4]>=HOUSEMAJORITY) align=ALIGN_ELITELIBERAL; // Elite Liberals have a majority
            else if(housemake[0]+housemake[1]>=HOUSEMAJORITY) align=ALIGN_CONSERVATIVE; // Conservatives plus Arch-Conservatives have a majority
            else if(housemake[3]+housemake[4]>=HOUSEMAJORITY) align=ALIGN_LIBERAL; // Liberals plus Elite Liberals have a majority
            else align=ALIGN_MODERATE; // nobody has a majority
            set_alignment_color(align,true);
            mvaddstr(10,0,"House: ");
            if(stalinmode) addstr(tostring(housemake[5])+"Sta, ");
            addstr(tostring(housemake[4])+"Lib+, ");
            addstr(tostring(housemake[3])+"Lib, ");
            addstr(tostring(housemake[2])+"Mod, ");
            addstr(tostring(housemake[1])+"Cons, ");
            addstr(tostring(housemake[0])+"Cons+");

            int senatemake[6]={0,0,0,0,0,0};
            for(int s=0;s<SENATENUM;s++) senatemake[senate[s]+2]++;
            senatemake[exec[EXEC_VP]+2]++; // Vice President is tie-breaking vote in the Senate
            if(senatemake[5]+MIN(senatemake[0],senatemake[4])>=SENATEMAJORITY) align=ALIGN_STALINIST; // Stalinists have a majority (perhaps with help from extremists on both sides)
            else if(senatemake[0]>=SENATEMAJORITY) align=ALIGN_ARCHCONSERVATIVE; // Arch-Conservatives have a majority
            else if(senatemake[4]>=SENATEMAJORITY) align=ALIGN_ELITELIBERAL; // Elite Liberals have a majority
            else if(senatemake[0]+senatemake[1]>=SENATEMAJORITY) align=ALIGN_CONSERVATIVE; // Conservatives plus Arch-Conservatives have a majority
            else if(senatemake[3]+senatemake[4]>=SENATEMAJORITY) align=ALIGN_LIBERAL; // Liberals plus Elite Liberals have a majority
            else align=ALIGN_MODERATE; // nobody has a majority
            set_alignment_color(align,true);
            senatemake[exec[EXEC_VP]+2]--; // Vice President isn't actually a Senator though
            mvaddstr(11,0,"Senate: ");
            if(stalinmode) addstr(tostring(senatemake[5])+"Sta, ");
            addstr(tostring(senatemake[4])+"Lib+, ");
            addstr(tostring(senatemake[3])+"Lib, ");
            addstr(tostring(senatemake[2])+"Mod, ");
            addstr(tostring(senatemake[1])+"Cons, ");
            addstr(tostring(senatemake[0])+"Cons+");
         }

         if(won==-1||won==-2) set_color(COLOR_RED,COLOR_BLACK,1);
         else if(won==1) set_color(COLOR_GREEN,COLOR_BLACK,1);
         else
         {
            int courtmake[6]={0,0,0,0,0,0};
            for(int s=0;s<COURTNUM;s++) courtmake[court[s]+2]++;
            if(courtmake[5]+MIN(courtmake[0],courtmake[4])>=COURTMAJORITY) align=ALIGN_STALINIST; // Stalinists have a majority (perhaps with help from extremists on both sides)
            else if(courtmake[0]>=COURTMAJORITY) align=ALIGN_ARCHCONSERVATIVE; // Arch-Conservatives have a majority
            else if(courtmake[4]>=COURTMAJORITY) align=ALIGN_ELITELIBERAL; // Elite Liberals have a majority
            else if(courtmake[0]+courtmake[1]>=COURTMAJORITY) align=ALIGN_CONSERVATIVE; // Conservatives plus Arch-Conservatives have a majority
            else if(courtmake[3]+courtmake[4]>=COURTMAJORITY) align=ALIGN_LIBERAL; // Liberals plus Elite Liberals have a majority
            else align=ALIGN_MODERATE; // nobody has a majority
            set_alignment_color(align,true);
         }

         mvaddchar(5,56,'S');
         mvaddchar(6,56,'U');
         mvaddchar(7,56,'P');
         mvaddchar(8,56,'R');
         mvaddchar(9,56,'E');
         mvaddchar(10,56,'M');
         mvaddchar(11,56,'E');

         mvaddchar(6,58,'C');
         mvaddchar(7,58,'O');
         mvaddchar(8,58,'U');
         mvaddchar(9,58,'R');
         mvaddchar(10,58,'T');

         if(won==-1)
         {
            mvaddstr(7,65,   "Replaced");
            mvaddstr(8,63, "By Corporate");
            mvaddstr(9,62,"Ethics Officers");
         }
         else if(won==-2)
         {
            mvaddstr(7,63, "Replaced By");
            mvaddstr(8,62,"Stalinist Show");
            mvaddstr(9,63, "Trial Judges");
         }
         else
         {
            y=4;
            for(int c=0;c<COURTNUM;c++,y++)
            {
               set_alignment_color(court[c],true);
               mvaddstr(y,60,courtname[c]);
            }
         }
         for(int l=0;l<LAWNUM;l++)
         {
            if(won==-1||won==-2)
               set_alignment_color(ALIGN_ARCHCONSERVATIVE,true);
            else if(won==1&&wincondition==WINCONDITION_ELITE)
               set_alignment_color(ALIGN_ELITELIBERAL,true);
            else set_color(COLOR_BLACK,COLOR_BLACK,1);
            mvaddstr(14+l/3,l%3*26,"\x11ÄÄÄÄÄ\x10");
            if(won==-1||won==-2)
               set_alignment_color(ALIGN_ARCHCONSERVATIVE,true);
            else set_alignment_color(law[l],true);
            addstr(getlaw(l));
            mvaddchar(14+l/3,l%3*26 + 3 - law[l],'O');
         }
         break;
      }

      case PAGE_ISSUES_A:
      case PAGE_ISSUES_B:
      {
         if(page==PAGE_ISSUES_A)
         {
            move(1,0);
            addstr("ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÉÍÍÍÍÍÍÍÍÍÍ»ÄÄÄÄÄÄÄÄÄÄ¿");
            move(2,0);
            addstr("³ GENERAL SUMMARY º ISSUES A º ISSUES B ³");
            move(3,0);
            addstr("ÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ          ÈÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ");
         }
         else
         {
            move(1,0);
            addstr("ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÉÍÍÍÍÍÍÍÍÍÍ»");
            move(2,0);
            addstr("³ GENERAL SUMMARY ³ ISSUES A º ISSUES B º");
            move(3,0);
            addstr("ÏÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÏÍÍÍÍÍÍÍÍÍͼ          ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ");
         }

         int y=4,startinglaw=0;
         if(page==PAGE_ISSUES_B) startinglaw=18;
         for(int l=startinglaw;l<startinglaw+18&&l<LAWNUM;l++,y++)
         {
            if(won==-1||won==-2)
               set_alignment_color(ALIGN_ARCHCONSERVATIVE,true);
            else set_alignment_color(law[l],true);

            move(y,0);

            switch(l)
            {
               case LAW_WOMEN:
                  if(won==-2)addstr("Women are usually drafted into the armed forces to fight in place of men.");
                  else if(won==-1)addstr("Women are considered property, and rape has been legalized.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Women are second-class citizens.");
                  else if(law[l]==-1)addstr("Non-discrimination laws do not apply to gender.");
                  else if(law[l]==0)addstr("Women are nominally equal under law, but this is not enforced.");
                  else if(law[l]==1)addstr("Women have substantial recourse against discrimination.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Gender equality is universally respected.");
                  else addstr("Binary gender identities no longer exist, and gender segregation has ended.");
                  break;
               case LAW_CIVILRIGHTS:
                  if(won==-2)addstr("Entire ethnic groups are branded \"enemies of the state\".");
                  else if(won==-1)addstr("Slavery has been reintroduced, along with an apartheid system.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Civil rights laws have been repealed, ostensibly to promote \"states' rights\".");
                  else if(law[l]==-1)addstr("Racial discrimination is prohibited in name only.");
                  else if(law[l]==0)addstr("Pervasive racial inequality exists, although overt discrimination is illegal.");
                  else if(law[l]==1)addstr("Affirmative action is in place to counteract racial discrimination.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Racial equality is guaranteed and vigorously enforced.");
                  else addstr("The very idea of \"race\" has been universally discarded as pseudoscience.");
                  break;
               case LAW_DRUGS:
                  if(won==-2)addstr("Vodka is the only legal recreational drug in the People's Republic of America.");
                  else if(won==-1)addstr("Talking about recreational drugs is punishable by death.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Violent criminals are released to make room for drug offenders.");
                  else if(law[l]==-1)addstr("Prisons are filled with the targets of a war on drugs.");
                  else if(law[l]==0)addstr("Recreational drugs are prohibited unless medically prescribed.");
                  else if(law[l]==1)addstr("Marijuana is regulated and taxed, but harder drugs are illegal.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Recreational drugs all are regulated and taxed like alcohol and tobacco.");
                  else addstr("The government distributes free recreational drugs to anyone who wants them.");
                  break;
               case LAW_IMMIGRATION:
                  if(won==-2)addstr("All Americans must carry around an internal passport, or be shot on sight.");
                  else if(won==-1)addstr("Private border militiamen shoot suspected foreigners on sight.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Immigration is illegal, and noncitizens are shipped to Mexico at gunpoint.");
                  else if(law[l]==-1)addstr("The National Guard has been deployed to the borders to slow immigration.");
                  else if(law[l]==0)addstr("Great expense is taken to slow immigration, without success.");
                  else if(law[l]==1)addstr("The government works to accommodate potential immigrants but deports criminals.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Immigration is unregulated, and new immigrants are welcomed warmly.");
                  else addstr("There are open borders, and no distinctions between citizens and non-citizens.");
                  break;
               case LAW_ELECTIONS:
                  if(won==-2)addstr("Only Stalinist Party members may run in elections, and they all run unopposed.");
                  else if(won==-1)addstr("Instead of elections, political offices are auctioned off to the highest bidder.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                  addstr("Virtually no ethics restrictions exist on political officeholders.");
                  else if(law[l]==-1)addstr("Elections are mostly unregulated, but basic ethics restrictions are in place.");
                  else if(law[l]==0)addstr("Moderate campaign finance reform is implemented.");
                  else if(law[l]==1)addstr("Election financing is transparent and well-regulated.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Election expenses are publicly funded, and voting is by ranked list.");
                  else addstr("There is proportional representation, and over a dozen major political parties.");
                  break;
               case LAW_MILITARY:
                  if(won==-2)addstr("The military promotes Stalinism throughout the world by using force.");
                  else if(won==-1)addstr("The massive military kills dissenters at home and conquers poor nations abroad.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                  addstr("Out-of-control military spending funds several ongoing wars around the world.");
                  else if(law[l]==-1)addstr("Massive investment is put into the military, which always seems to be at war.");
                  else if(law[l]==0)addstr("Military spending is growing each year to fund overseas military adventures.");
                  else if(law[l]==1)addstr("The military is not a major priority, and mostly does peacekeeping missions.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The military has been weakened significantly, as there is little need for it.");
                  else addstr("The military has been abolished, and the entire world is at peace.");
                  break;
               case LAW_TORTURE:
                  if(won==-2)addstr("The Internal Affairs Commissariat constantly invents new methods of torture.");
                  else if(won==-1)addstr("The new Inquisition tortures heretics, blasphemers, and non-Christians to death.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Military and intelligence interrogators regularly engage in torture.");
                  else if(law[l]==-1)addstr("The line between standard interrogation and torture is severely blurred.");
                  else if(law[l]==0)addstr("Torture allegations still occasionally crop up, despite an official ban.");
                  else if(law[l]==1)addstr("The government strongly enforces a ban on torture.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The nation is a respected international leader on Moral Interrogation Practices.");
                  else addstr("Terrorism ended after the government formally apologized to terrorist leaders.");
                  break;
               case LAW_PRISONS:
                  if(won==-2)addstr("The former nation of Canada has been annexed and filled with Stalinist gulags.");
                  else if(won==-1)addstr("Prisoners must fight to the death in corporate-sponsored gladiatorial bouts.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Prisoners are often subject to torture and slave labor.");
                  else if(law[l]==-1)addstr("Prisoners suffer from horrible conditions and lack of basic rights.");
                  else if(law[l]==0)addstr("Prisoners receive basic rights and services, but reports of abuse are common.");
                  else if(law[l]==1)addstr("The prisons are regulated to protect prisoners' rights and safety.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The prisons are targeted at rehabilitation, rather than punishment.");
                  else addstr("Instead of prison, criminals voluntarily attend free support groups.");
                  break;
	           case LAW_TAX:
                  if(won==-2)addstr("Having any money whatsoever is punishable by 20 years in a gulag.");
                  else if(won==-1)addstr("There are no taxes, yet most people have no money.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("The tax code is a nightmare designed to maintain class structure.");
                  else if(law[l]==-1)addstr("A flat tax is in effect, and there is no capital gains or inheritance tax.");
                  else if(law[l]==0)addstr("Taxes are moderate, but the code is full of loopholes.");
                  else if(law[l]==1)addstr("The wealthy are heavily taxed under a progressive taxation system.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Rich people are virtually unheard of, due to taxation.");
                  else addstr("Money no longer exists, everything is free, and everyone enjoys lives of luxury.");
                  break;
               case LAW_ABORTION:
                  if(won==-2)addstr("Mandatory abortions are carried out for population control.");
                  else if(won==-1)addstr("Abortion, contraception, and consensual sex are all capital offenses.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Abortion is a felony equal to murder, not allowed under any circumstance.");
                  else if(law[l]==-1)addstr("Abortion is prohibited except in cases of rape, incest, or health of the mother.");
                  else if(law[l]==0)addstr("Abortion is limited to the first trimester, and is very expensive.");
                  else if(law[l]==1)addstr("Abortion is legal, but taxpayer funding of abortion is prohibited.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The right to an abortion is strongly protected, and subsidized for poor women.");
                  else addstr("Free abortions are easily available at any time during pregnancy.");
                  break;
               case LAW_ANIMALRESEARCH:
                  if(won==-2)addstr("All forms of human experimentation on \"class enemies\" are encouraged.");
                  else if(won==-1)addstr("All forms of human experimentation on the poor are encouraged.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Animals are property that can be experimented upon freely.");
                  else if(law[l]==-1)addstr("Animal testing is self-regulated by the scientific community.");
                  else if(law[l]==0)addstr("Animal research is regulated with a system of licenses and certificates.");
                  else if(law[l]==1)addstr("Animal research is strictly regulated by purpose and suffering caused.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Animals are people, too, and have full citizenship rights.");
                  else addstr("All species of life have equal rights as people, even bacteria.");
                  break;
               case LAW_POLICEBEHAVIOR:
                  if(won==-2)addstr("Everyone lives in constant fear of the Stalinist Party's Secret Police.");
                  else if(won==-1)addstr("Privatized police get bonuses on their paychecks for every person they kill.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Law enforcement is given free reign.");
                  else if(law[l]==-1)addstr("Even the worst police misconduct only earns slap-on-the-wrist punishments.");
                  else if(law[l]==0)addstr("Law enforcement is regulated to prevent extreme misconduct.");
                  else if(law[l]==1)addstr("Law enforcement has heavy oversight and freedom-of-information requirements.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("All law enforcement positions are subject to election and recall.");
                  else addstr("With no police, criminals follow the honor system and turn themselves in.");
                  break;
               case LAW_PRIVACY:
                  if(won==-2)addstr("Citizens have to spy on each other and report to the Stalinist Party.");
                  else if(won==-1)addstr("Very detailed reports on each citizen are easily accessible to corporations.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Any corporation requesting private information is granted unrestricted access.");
                  else if(law[l]==-1)addstr("Privacy laws are full of loopholes and security backdoors are in everything.");
                  else if(law[l]==0)addstr("Basic safeguards for medical and financial privacy are in place but ineffective.");
                  else if(law[l]==1)addstr("All areas of privacy are protected with strong, effective safeguards.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Individual privacy is sacred, and state-of-the-art safeguards are mandatory.");
                  else addstr("All large organizations are prohibited from keeping any data about anyone.");
                  break;
               case LAW_DEATHPENALTY:
                  if(won==-2)addstr("Class enemies receive mandatory death sentences.");
                  else if(won==-1)addstr("Poor and minority criminals receive mandatory death sentences.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("People can be put to death for minor offenses.");
                  else if(law[l]==-1)addstr("The death penalty is actively enforced in many states.");
                  else if(law[l]==0)addstr("The death penalty is in effect but under scrutiny.");
                  else if(law[l]==1)addstr("The death penalty is only permitted in extreme cases.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The death penalty is considered barbaric and never practiced.");
                  else addstr("The death penalty, like all other harsh punishments, has been abolished.");
                  break;
               case LAW_NUCLEARPOWER:
                  if(won==-2)addstr("Nuclear power plants routinely have meltdowns but keep getting built.");
                  else if(won==-1)addstr("Nuclear power plants are ubiquitous and cancer rates are astronomical.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Nuclear power is wildly proliferating with no controls or regulation at all.");
                  else if(law[l]==-1)addstr("Nuclear power is a preferred energy source and the industry self-regulates.");
                  else if(law[l]==0)addstr("Nuclear power is often an energy source and only moderately regulated.");
                  else if(law[l]==1)addstr("Nuclear power is intensely regulated and rarely used anymore.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Nuclear power is illegal and the leftover nuclear waste is being cleaned up.");
                  else addstr("A global ban on nuclear power and nuclear weapons is enforced by UN inspectors.");
                  break;
               case LAW_POLLUTION:
                  if(won==-2)addstr("State-run industries pollute so much, the workers all have cancer.");
                  else if(won==-1)addstr("Deformed children are the norm in the vast industrial wastelands.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Industry may pollute as much as they like.");
                  else if(law[l]==-1)addstr("Industry voluntarily regulates pollution.");
                  else if(law[l]==0)addstr("Industry is subject to moderate pollution regulations.");
                  else if(law[l]==1)addstr("Industry is subject to strict pollution regulations.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Industry is subject to zero-tolerance pollution regulations.");
                  else addstr("Pollution is unheard of, and nature has reclaimed much of the land.");
                  break;
               case LAW_LABOR:
                  if(won==-2)addstr("The state has nationalized all industries and assigns everyone jobs.");
                  else if(won==-1)addstr("People are bred in pens to be farmed out to corporations like beasts.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("There is no weekend, children are forced to work, and workers can't afford food.");
                  else if(law[l]==-1)addstr("Working conditions are deplorable and there is no minimum wage.");
                  else if(law[l]==0)addstr("Workers are underpaid, have lousy benefits, and get fired if they complain.");
                  else if(law[l]==1)addstr("Workers are fairly compensated, have good benefits, and are difficult to fire.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("There are universal workers' rights and a high guaranteed minimum income.");
                  else addstr("Wage slavery has been abolished, and robots have been built to do all the work.");
                  break;
               case LAW_GAY:
                  if(won==-2)addstr("Homosexuals are executed regularly for their \"bourgeoisie decadence\".");
                  else if(won==-1)addstr("Homosexuals are executed regularly for \"promoting the Gay Agenda\".");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Homosexuals are routinely persecuted with no recourse.");
                  else if(law[l]==-1)addstr("Homosexuals are not tolerated.");
                  else if(law[l]==0)addstr("Homosexuals are grudgingly tolerated but have few equal rights.");
                  else if(law[l]==1)addstr("Homosexuals have many rights shared by heterosexuals.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Homosexuals have equal rights that are vigorously protected.");
                  else addstr("All sexual orientations are accepted, and most people are polyamorous.");
                  break;
               case LAW_CORPORATE:
                  if(won==-2)addstr("All forms of private enterprise are punishable by death.");
                  else if(won==-1)addstr("Corporations under the King run the country in a feudal system.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Corporations essentially run the country in a feudal system.");
                  else if(law[l]==-1)addstr("Corporate culture is corrupt and there is a great disparity in wages.");
                  else if(law[l]==0)addstr("Corporations are moderately regulated, although wages are still unfair.");
                  else if(law[l]==1)addstr("Corporations are stiffly regulated, and executive compensation is reasonable.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Corporations are subject to intense regulation, and there is a maximum wage law.");
                  else addstr("Corporations have been abolished, along with the rest of capitalism.");
                  break;
               case LAW_FREESPEECH:
                  if(won==-2)addstr("Counterrevolutionary speech is a capital crime.");
                  else if(won==-1)addstr("Even *THINKING* about saying something unacceptable is a capital crime.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Armored squads are tasked with suppressing unacceptable speech.");
                  else if(law[l]==-1)addstr("People who express unpopular opinions are often harassed and mistreated.");
                  else if(law[l]==0)addstr("Free speech is legal, with minor exceptions, and is usually tolerated.");
                  else if(law[l]==1)addstr("Free speech is legally protected and publicly encouraged.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("Free speech is strongly protected and universally supported.");
                  else addstr("Free speech is sacrosanct and diverse points of view are celebrated.");
                  break;
               case LAW_FLAGBURNING:
                  if(won==-2)addstr("Flags of the old American regime are burnt primarily as fuel.");
                  else if(won==-1)addstr("Images or words describing flag burning are punished by death.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Burning the flag is a serious crime on par with murder.");
                  else if(law[l]==-1)addstr("Burning the flag is a felony and vigorously prosecuted.");
                  else if(law[l]==0)addstr("Flag-burning is a misdemeanor, but not a serious crime.");
                  else if(law[l]==1)addstr("Flag-burning is technically legal but stigmatized as unpatriotic.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("The right of flag-burning is upheld even by its critics.");
                  else addstr("Flag-burning is traditionally done on July 4th to celebrate freedom.");
                  break;
               case LAW_GUNCONTROL:
                  if(won==-2)addstr("Anyone owning a gun is executed by firing squad.");
                  else if(won==-1)addstr("Gangs of young children carrying AK-47s roam the streets.");
                  else if(law[l]==ALIGN_ARCHCONSERVATIVE)
                     addstr("Machine guns, tanks, and missiles can be bought and sold freely.");
                  else if(law[l]==-1)addstr("Military weapons are banned, but similar-looking guns are available.");
                  else if(law[l]==0)addstr("A comprehensive ban on military-style weapons is in effect.");
                  else if(law[l]==1)addstr("Most guns cannot be sold to anyone outside of law enforcement.");
                  else if(won!=1||wincondition!=WINCONDITION_ELITE)addstr("It is illegal to buy or sell a gun, or carry one in public.");//XXX: Should guns be legal in private, too? -- LK
                  else addstr("All gun manufacturers have been shut down and all existing guns destroyed."); //They are illegal in private under Elite Liberal victory conditions - yetisyny
                  break;
            }
         }
         break;
      }
      }

      if(won==1)
      {
         set_color(COLOR_GREEN,COLOR_BLACK,1);
         if(wincondition==WINCONDITION_EASY)
            mvaddstr(23,0,"The country has achieved Liberal status!");
         else mvaddstr(23,0,"The country has achieved Elite Liberal status!");
         mvaddstr(24,0,"Press 'L' to view the high score list.");

         int c=getkey();

         if(c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT) page++;
         else if(c==interface_pgup||c==KEY_UP||c==KEY_LEFT) page--;
         else if(c=='l') break;
      }
      else if(won==-1)
      {
         set_color(COLOR_RED,COLOR_BLACK,1);
         mvaddstr(23,0,"The country has been Reaganified.");
         mvaddstr(24,0,"Press 'L' to view the high score list.");

         int c=getkey();

         if(c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT) page++;
         else if(c==interface_pgup||c==KEY_UP||c==KEY_LEFT) page--;
         else if(c=='l') break;
      }
      else if(won==-2)
      {
         set_color(COLOR_RED,COLOR_BLACK,1);
         mvaddstr(23,0,"The country has been Stalinized.");
         mvaddstr(24,0,"Press 'L' to view the high score list.");

         int c=getkey();

         if(c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT) page++;
         else if(c==interface_pgup||c==KEY_UP||c==KEY_LEFT) page--;
         else if(c=='l') break;
      }
      else
      {
         move(23,0);
         if(stalinmode)
         {
            set_color(COLOR_RED,COLOR_BLACK,1);
            addstr("Stalinist  ");
         }
         set_color(COLOR_GREEN,COLOR_BLACK,1);
         addstr("Elite Liberal  ");
         if(!stalinmode)
         {
            set_color(COLOR_WHITE,COLOR_BLACK,0);
            addstr("-  ");
         }
         set_color(COLOR_CYAN,COLOR_BLACK,1);
         addstr("Liberal  ");
         if(!stalinmode)
         {
            set_color(COLOR_WHITE,COLOR_BLACK,0);
            addstr("-  ");
         }
         set_color(COLOR_YELLOW,COLOR_BLACK,1);
         addstr("moderate  ");
         if(!stalinmode)
         {
            set_color(COLOR_WHITE,COLOR_BLACK,0);
            addstr("-  ");
         }
         set_color(COLOR_MAGENTA,COLOR_BLACK,1);
         addstr("Conservative  ");
         if(!stalinmode)
         {
            set_color(COLOR_WHITE,COLOR_BLACK,0);
            addstr("-  ");
         }
         set_color(COLOR_RED,COLOR_BLACK,1);
         addstr("Arch-Conservative");
         set_color(COLOR_WHITE,COLOR_BLACK,0);
         //mvaddstr(23,0,"Once these are Green, the country will have achieved Elite Liberal status.");
         mvaddstr(24,0,"Press D to disband and wait. Use cursors for other pages. Any other key to exit.");

         int c=getkey();

         if(c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT) page++;
         else if(c==interface_pgup||c==KEY_UP||c==KEY_LEFT) page--;
         else if(c=='d') return confirmdisband();
         else break;
      }
   }
   return false;
}
示例#13
0
// Prints the map graphics in the bottom right of the screen
void printsitemap(int x,int y,int z)
{
   int xscreen, xsite;
   int yscreen, ysite;

   // Build the frame
   set_color(COLOR_WHITE,COLOR_BLACK,0);
   for(xscreen=53;xscreen<80;xscreen++)
   {
      move(24,xscreen);
      addch('-');
   }
   for(yscreen=9;yscreen<24;yscreen++)
   {
      move(yscreen,53);
      addstr("|                         |");
   }

   // Display the map
   for(xsite=x-2,xscreen=79-5*5;xsite<x+3;xscreen+=5,xsite++)
   {
      for(ysite=y-2,yscreen=24-3*5;ysite<y+3;yscreen+=3,ysite++)
      {
         printblock(xsite,ysite,z,xscreen,yscreen);
      }
   }

   //PRINT SPECIAL
   char str[200];
   switch(levelmap[locx][locy][locz].special)
   {
      case SPECIAL_LAB_COSMETICS_CAGEDANIMALS:strcpy(str,"Caged Animals");break;
      case SPECIAL_NUCLEAR_ONOFF:strcpy(str,"Reactor Control Room");break;
      case SPECIAL_LAB_GENETIC_CAGEDANIMALS:strcpy(str,"Caged \"Animals\"");break;
      case SPECIAL_POLICESTATION_LOCKUP:strcpy(str,"Police Detention Room");break;
      case SPECIAL_COURTHOUSE_LOCKUP:strcpy(str,"Court House Jail");break;
      case SPECIAL_COURTHOUSE_JURYROOM:strcpy(str,"Jury Room");break;
      case SPECIAL_PRISON_CONTROL:
      case SPECIAL_PRISON_CONTROL_LOW:
      case SPECIAL_PRISON_CONTROL_MEDIUM:
      case SPECIAL_PRISON_CONTROL_HIGH:strcpy(str,"Prison Control Room");break;
      case SPECIAL_INTEL_SUPERCOMPUTER:strcpy(str,"Supercomputer");break;
      case SPECIAL_SWEATSHOP_EQUIPMENT:strcpy(str,"Textile Equipment");break;
      case SPECIAL_POLLUTER_EQUIPMENT:strcpy(str,"Factory Equipment");break;
      case SPECIAL_HOUSE_PHOTOS:strcpy(str,"Safe");break;
      case SPECIAL_ARMORY:strcpy(str,"Armory");break;
      case SPECIAL_HOUSE_CEO:strcpy(str,"CEO's Study");break;
      case SPECIAL_CORPORATE_FILES:strcpy(str,"Safe");break;
      case SPECIAL_RADIO_BROADCASTSTUDIO:strcpy(str,"Radio Broadcast Room");break;
      case SPECIAL_NEWS_BROADCASTSTUDIO:strcpy(str,"News Broadcast Studio");break;
      case SPECIAL_APARTMENT_LANDLORD:strcpy(str,"Landlord's Office");break;
      case SPECIAL_SIGN_ONE:strcpy(str,"Sign");break;
      case SPECIAL_SIGN_TWO:strcpy(str,"Sign");break;
      case SPECIAL_SIGN_THREE:strcpy(str,"Sign");break;
      case SPECIAL_DISPLAY_CASE:strcpy(str,"Display Case");break;
      case SPECIAL_STAIRS_UP:strcpy(str,"Stairs Up");break;
      case SPECIAL_STAIRS_DOWN:strcpy(str,"Stairs Down");break;
      case SPECIAL_RESTAURANT_TABLE:strcpy(str,"Table");break;
      case SPECIAL_CAFE_COMPUTER:strcpy(str,"Computer");break;
      case SPECIAL_PARK_BENCH:strcpy(str,"Bench");break;
      case SPECIAL_BANK_VAULT:strcpy(str,"Bank Vault");break;
      case SPECIAL_BANK_TELLER:strcpy(str,"Bank Teller");break;
      case SPECIAL_BANK_MONEY:strcpy(str,"Oh Wow So Much Money");break;
      case SPECIAL_CCS_BOSS:strcpy(str,"CCS Boss");break;
      default:strcpy(str,"");break;
   }
   if(levelmap[locx][locy][locz].special!=-1)
   {
      set_color(COLOR_WHITE,COLOR_BLACK,1);
      move(24,67-(strlen(str)>>1));
      addstr(str);
   }
示例#14
0
/*
 * quit:
 *	Handle the end of the game when the player dies
 */
int
quit(int old_status)
{
	bool explain;
	int ch;

	if (Last_player)
		return Q_QUIT;
#ifdef OTTO
	if (Otto_mode)
		return Q_CLOAK;
#endif
	move(HEIGHT, 0);
	addstr("Re-enter game [ynwo]? ");
	clrtoeol();
	explain = false;
	for (;;) {
		refresh();
		if (isupper(ch = getchar()))
			ch = tolower(ch);
		if (ch == 'y')
			return old_status;
		else if (ch == 'o')
			break;
		else if (ch == 'n') {
#ifndef INTERNET
			return Q_QUIT;
#else
			move(HEIGHT, 0);
			addstr("Write a parting message [yn]? ");
			clrtoeol();
			refresh();
			for (;;) {
				if (isupper(ch = getchar()))
					ch = tolower(ch);
				if (ch == 'y')
					goto get_message;
				if (ch == 'n')
					return Q_QUIT;
			}
#endif
		}
#ifdef INTERNET
		else if (ch == 'w') {
			static char buf[WIDTH + WIDTH % 2];
			char *cp, c;

get_message:
			c = ch;		/* save how we got here */
			move(HEIGHT, 0);
			addstr("Message: ");
			clrtoeol();
			refresh();
			cp = buf;
			for (;;) {
				refresh();
				if ((ch = getchar()) == '\n' || ch == '\r')
					break;
				if (ch == erasechar()) {
					if (cp > buf) {
						int y, x;
						getyx(stdscr, y, x);
						move(y, x - 1);
						cp -= 1;
						clrtoeol();
					}
					continue;
				}
				else if (ch == killchar()) {
					int y, x;
					getyx(stdscr, y, x);
					move(y, x - (cp - buf));
					cp = buf;
					clrtoeol();
					continue;
				} else if (!isprint(ch)) {
					beep();
					continue;
				}
				addch(ch);
				*cp++ = ch;
				if (cp + 1 >= buf + sizeof buf)
					break;
			}
			*cp = '\0';
			Send_message = buf;
			return (c == 'w') ? old_status : Q_MESSAGE;
		}
#endif
		beep();
		if (!explain) {
			addstr("(Yes, No, Write message, or Options) ");
			explain = true;
		}
	}

	move(HEIGHT, 0);
#ifdef FLY
	addstr("Scan, Cloak, Flying, or Quit? ");
#else
	addstr("Scan, Cloak, or Quit? ");
#endif
	clrtoeol();
	refresh();
	explain = false;
	for (;;) {
		if (isupper(ch = getchar()))
			ch = tolower(ch);
		if (ch == 's')
			return Q_SCAN;
		else if (ch == 'c')
			return Q_CLOAK;
#ifdef FLY
		else if (ch == 'f')
			return Q_FLY;
#endif
		else if (ch == 'q')
			return Q_QUIT;
		beep();
		if (!explain) {
#ifdef FLY
			addstr("[SCFQ] ");
#else
			addstr("[SCQ] ");
#endif
			explain = true;
		}
		refresh();
	}
}
示例#15
0
/* Among other things,  'newtest' demonstrates how to make a Win32a
PDCurses app that is a for-real,  "pure Windows" version (instead of
a console application).  Doing this is quite easy,  and has certain
advantages.  If the app is invoked from a command prompt,  the only
difference you'll see is that the app runs separately (that is,  you
can continue to use the command prompt,  switching between it,  your
PDCurses/Win32a app,  and other processes).  Which is the main reason
I did it;  it meant that I could invoke a PDCurses-based text editor,
for example,  and still have use of the command line.

   (NOTE that,  for reasons I don't actually understand,  this happens
when the Visual C++ compiler is used.  With MinGW or OpenWatcom,  it's
still "really" a console app.)

   To do it,  we ensure that the usual main() function has an alternative
dummy_main() form,  taking the same arguments as main().  We add a
WinMain() function,  whose sole purpose is to reformulate lpszCmdLine
into argc/argv form,  and pass it on to dummy_main().  And,  of course,
we can switch back to a "normal" console app by removing the above
#define PURE_WINDOWS_VERSION line.             */

#ifdef PURE_WINDOWS_VERSION
#undef MOUSE_MOVED
#include <windows.h>

int dummy_main( int argc, char **argv);

int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPSTR lpszCmdLine, int nCmdShow)
{
   char *argv[30];
   int i, argc = 1;

   argv[0] = "newtest";
   for( i = 0; lpszCmdLine[i]; i++)
       if( lpszCmdLine[i] != ' ' && (!i || lpszCmdLine[i - 1] == ' '))
          argv[argc++] = lpszCmdLine + i;

   for( i = 0; lpszCmdLine[i]; i++)
       if( lpszCmdLine[i] == ' ')
          lpszCmdLine[i] = '\0';

   return dummy_main( argc, (char **)argv);
}

int dummy_main( int argc, char **argv)
#else       /* "usual",  console-app version: */
int main( int argc, char **argv)
#endif
{
    int quit = 0, i,  use_slk = 1;
    int fmt = 0xa;
    bool blink_state = FALSE;
    int cursor_state_1 = 2, cursor_state_2 = 3;
    int show_slk_index_line = 0;
    int redraw = 1;
    unsigned extra_character_to_show = 0;
#ifdef PDC_WIDE
    unsigned unicode_offset = 0x80;
#endif

/*  setlocale(LC_ALL, ".utf8");     */
    ttytype[0] = 25;   ttytype[1] = 90;         /* Allow 25 to 90 lines... */
    ttytype[2] = 80;   ttytype[3] = (char)200;  /* ...and 80 to 200 columns */
         /* (This program gets weird artifacts when smaller than 25x80.) */
    for( i = 1; i < argc; i++)
        if( argv[i][0] == '-')
            switch( argv[i][1])
            {
                case 's':
                    use_slk = 0;
                    break;
                case 'l':
                    setlocale( LC_ALL, argv[i] + 2);
                    break;
                case 'e':
                    sscanf( argv[i] + 2, "%x", &extra_character_to_show);
                    break;
                case 'f':
                    sscanf( argv[i] + 2, "%x", (unsigned *)&fmt);
                    break;
                case 'i':
                    show_slk_index_line = 1;
                    break;
                case 'r':     /* allow user-resizable windows */
                    {
                        int min_lines, max_lines, min_cols, max_cols;

                        if( sscanf( argv[i] + 2, "%d,%d,%d,%d",
                                       &min_lines, &max_lines,
                                       &min_cols, &max_cols) == 4)
                        {
                            ttytype[0] = min_lines;
                            ttytype[1] = max_lines;
                            ttytype[2] = min_cols;
                            ttytype[3] = max_cols;
                        }
                    }
                    break;
                case 'd':     /* set window size before initscr */
                    {
                        int n_lines, n_cols;

                        if( sscanf( argv[i] + 2, "%d,%d", &n_lines,
                                    &n_cols) == 2)
                            resize_term( n_lines, n_cols);
                    }
                    break;
#ifdef PDC_WIDE
                case 'u':
                    sscanf( argv[i] + 2, "%x", &unicode_offset);
                    break;
#endif
                default:
                    printf( "Option '%s' unrecognized\n", argv[i]);
                    break;
            }
    if( use_slk)
       slk_init( show_slk_index_line ? 3 : 0);
    Xinitscr(argc, argv);
    if( use_slk)
       slk_setup( show_slk_index_line ? -fmt : fmt);

    start_color();

# if defined(NCURSES_VERSION) || (defined(PDC_BUILD) && PDC_BUILD > 3000)
    use_default_colors();
# endif
    cbreak();
    noecho();
    clear();
    refresh();
#ifdef __PDCURSES__
    PDC_set_title( "NewTest: tests various PDCurses features");
#endif
    keypad( stdscr, TRUE);
    init_pair( 1, 15, COLOR_BLACK);
    init_pair( 2, COLOR_BLACK, COLOR_YELLOW);

    mousemask( ALL_MOUSE_EVENTS, NULL);
    attrset( COLOR_PAIR( 1));
    while( !quit)
    {
        char buff[40];
        const int xmax = getmaxx( stdscr);
        const int ymax = getmaxy( stdscr);
        int color_block_start = 54, c;
        int color_block_cols = (xmax - color_block_start) / 2;
        const int color_block_lines = 19;
        const char *cursor_state_text[N_CURSORS] = {
                  "Invisible (click to change) ",
                  "Underscore (click to change)",
                  "Block (click to change)     ",
                  "Outline (click to change)   ",
                  "Caret (click to change)     ",
                  "Half-block (click to change)",
                  "Central (click to change)   ",
                  "Cross (click to change)     ",
                  "Heavy box (click to change) " };

        if( color_block_cols < 0)
            color_block_cols = 0;
        if( redraw)
        {
            mvaddstr( 1, COL1, "'Normal' white-on-black");
#if(CHTYPE_LONG >= 2)       /* "non-standard" 64-bit chtypes     */
            attron( A_DIM);
            mvaddstr( 2, COL1, "Dimmed text");
            attroff( A_DIM);
#endif
#ifdef PDC_WIDE
            mvaddwstr( 3, COL1, L"'Normal' text,  but wide");
#endif
            attron( A_BLINK);
            mvaddstr( 6, 40, "Blinking");
            attron( A_BOLD);
            mvaddstr( 8, 40, "BlinkBold");
            attron( A_ITALIC);
            mvaddstr( 0, COL2, "BlinkBoldItalic");
            attrset( COLOR_PAIR( 3));
            attron( A_UNDERLINE);
#ifdef PDC_WIDE
            mvaddstr( 1, COL2, "Underlined");
            addwstr( L"WideUnder");
#endif
            attrset( COLOR_PAIR( 1));
            attron( A_UNDERLINE | A_ITALIC);
            mvaddstr( 2, COL2, "UnderlinedItalic");
            attrset( COLOR_PAIR( 2));
            attron( A_BLINK);
            mvaddstr( 4, COL1, "Black-on-yellow blinking");

            attrset( COLOR_PAIR( 1));
            move( 4, COL2);
            text_in_a_box( "Text in a box");

#ifdef CHTYPE_LONG
            attrset( COLOR_PAIR( 6));
            attron( A_STRIKEOUT);
            mvaddstr( 10, 40, "Strikeout");
            attrset( COLOR_PAIR( 1));
#endif

#ifdef PDC_WIDE
            move( 11, 40);
            text_in_a_box( "Next Ucode pg");
            if( unicode_offset)
               {
               move( 12, 40);
               text_in_a_box( "Prev Ucode pg");
               }
            mvprintw( 13, 40, "U+%04x ", unicode_offset);

#endif

            for( i = 0; i < 128; i++)
            {                 /* Show extended characters: */
#ifdef PDC_WIDE
                wchar_t buff[20];

                swprintf( buff, 20, L"%02x ",
                           (unsigned)( i + unicode_offset) & 0xff);
                mvaddwstr( 5 + i % 16, (i / 16) * 5, buff);
                if( i + unicode_offset > ' ')
                   addch( (chtype)( i + unicode_offset));
                else
                   addch( ' ');
                addch( ' ');
#else
                char buff[6];

                sprintf( buff, "%02x %c", i + 128, (char)(i + 128));
                mvaddstr( 5 + i % 16, (i / 16) * 5, buff);
#endif
            }

#if(CHTYPE_LONG >= 2)       /* "non-standard" 64-bit chtypes     */
            for( i = 0; i < 3 && i + 21 < ymax; i++)
            {                 /* Demonstrate full RGB color control: */
                int j;
                const char *output_text[3] = {
                    "Red on green to white on black   | (you can get full RGB colors when desired,",
                    "Blue on yellow to black on red | with palette coloring still being available)",
                    "White on red to green on blue,  underlined and italic" };
                const int len = (int)strlen( output_text[i]);

                move( 21 + i, 1);
                for( j = 0; j < len && j + 1 < xmax; j++)
                {
                    attr_t output_color;
                    const int oval = j * 31 / len;
                    const int reverse = 31 - oval;

                    if( !i)
                        output_color = A_RGB( 31, oval, oval, 0, reverse, 0);
                    else if( i == 1)
                        output_color = A_RGB( 0, 0, reverse, 31, reverse, 0);
                    else
                    {
                        output_color = A_RGB( reverse, 31, reverse,
                               reverse, 0, oval);
                        output_color |= A_UNDERLINE | A_ITALIC;
                    }
                    attrset( output_color);
                    addch( output_text[i][j]);
                }
            }
#endif         /* #if(CHTYPE_LONG >= 2) */
            redraw = 0;
            attrset( COLOR_PAIR( 1));
            if( extra_character_to_show && ymax > 23)
                mvaddch( 23, 63, (chtype)extra_character_to_show);

#ifdef PDC_WIDE
            for( i = 0; i < 6; i++)
            {
                static const wchar_t spanish[] = L"Espa\xf1ol";
                const int line = 24 + i / 3;
                const int col = 5 + 25 * (i % 3);

                static const wchar_t russian[] = {0x0420, 0x0443, 0x0441, 0x0441,
                   0x043a, 0x0438, 0x0439, L' ', 0x044f, 0x0437, 0x044b, 0x043a, 0};

                static const wchar_t greek[] = {0x0395, 0x03bb, 0x03bb, 0x03b7,
                   0x03bd, 0x03b9, 0x03ba, 0x03ac, 0};

                static const wchar_t georgian[] = {0x10e5, 0x10d0, 0x10e0, 0x10d7,
                   0x10e3, 0x10da, 0x10d8, L' ', 0x10d4, 0x10dc, 0x10d0, 0};

                static const wchar_t fullwidth[] = { 0xff26, 0xff55, 0xff4c, 0xff4c,
                   0xff57, 0xff49, 0xff44, 0xff54, 0xff48, 0 };  /* "Fullwidth" */

                static const wchar_t combining_marks[] = { L'C', L'o', 0x35c, L'm',
                   L'b', 0x30a, L'i', L'n', L'i', 0x304, L'n', 0x30b, 0x329,
                   L'g', 0x310,
                   L' ', L'C', 0x338, L'h', 0x306,  L'a', 0x361, L'r', L's',
                   0x30e, 0x348, 0 };

                static const wchar_t *texts[6] = { spanish, russian, greek,
                                georgian, fullwidth, combining_marks};

                if( line < ymax && col < xmax)
                   mvaddnwstr( line, 5 + 25 * (i % 3), texts[i], xmax - col);
            }
#endif

#ifdef MAYBE_TRY_THIS_SOMEWHERE_ELSE
        mvaddstr(  1, COL3, "Click on cursor descriptions to");
        mvaddstr(  2, COL3, "cycle through possible cursors");
        mvaddstr(  3, COL3, "Click on colors at left to change");
        mvaddstr(  4, COL3, "colors used for under/over/outlining");
        mvaddstr(  5, COL3, "Click 'Blink' at bottom to toggle");
        mvaddstr(  6, COL3, "'real' blinking vs. 'highlit' blink");
#endif
        }

        mvaddnstr( 19, color_block_start, cursor_state_text[cursor_state_1],
                                 xmax - color_block_start);
        mvaddnstr( 20, color_block_start, cursor_state_text[cursor_state_2],
                                 xmax - color_block_start);
        curs_set( (cursor_state_1 << 8) | cursor_state_2);
        for( i = 0; i < color_block_cols * color_block_lines; i++)
        {
            const int n_color_blocks = 256;

            attrset( COLOR_PAIR( i >= n_color_blocks ? 2 : i));
            if( i > 2 && i < n_color_blocks)
               init_pair((short)i, (short)i, COLOR_BLACK);
            if( !(i % color_block_cols))
               move( i / color_block_cols, color_block_start);
            attron( A_REVERSE);
            addstr( "  ");
        }
        move( 19, color_block_start - 3);
        refresh();
        c = getch( );
        attrset( COLOR_PAIR( 1));
        if( c == KEY_RESIZE)
        {
            redraw = 1;
            resize_term( 0, 0);
        }
        else if( c == KEY_F(1) || c == 27)
            quit = 1;
        else if( c == KEY_F(2))
        {
            blink_state ^= 1;
            PDC_set_blink( blink_state);
        }
        else if( c == KEY_F(3))   /* toggle SLKs */
        {
            use_slk ^= 1;
            if( use_slk)
                slk_restore( );
            else
                slk_clear( );
        }
        else if( c >= KEY_F(4) && c < KEY_F(12))
        {
            sscanf( labels[c - KEY_F(1)], "%x", (unsigned *)&fmt);
            if( use_slk)
                slk_setup( show_slk_index_line ? -fmt : fmt);
        }
//      else if( c == 'w')
//          PDC_write_screen_to_file( "scrdump.htm", curscr);
        if( c != KEY_MOUSE)
        {
            sprintf( buff, "Key %s hit          ", keyname( c));
            mvaddstr( 0, COL1, buff);
        }
        else
        {
            MEVENT mouse_event;
#ifdef __PDCURSES__
            nc_getmouse( &mouse_event);
#else
            getmouse( &mouse_event);
#endif
            sprintf( buff, "Mouse at %d x %d: %x  ", mouse_event.x,
                              mouse_event.y, (unsigned)mouse_event.bstate);
            mvaddstr( 0, COL1, buff);
            if( mouse_event.x >= color_block_start
                            && mouse_event.y < color_block_lines)
            {
                int new_color = (mouse_event.x - color_block_start) / 2
                              + mouse_event.y * color_block_cols;

                if( new_color >= 256)
                    new_color = -1;
                PDC_set_line_color( (short)new_color);
            }
            else if( mouse_event.x >= color_block_start)
            {
                int shift = ((mouse_event.bstate & BUTTON_MODIFIER_SHIFT) ?
                           N_CURSORS - 1 : 1);

                if( mouse_event.y == 19)  /* blink/non-blink toggle */
                    cursor_state_1 = (cursor_state_1 + shift) % N_CURSORS;
                else if( mouse_event.y == 20)  /* cycle cursor state */
                    cursor_state_2 = (cursor_state_2 + shift) % N_CURSORS;
            }
#ifdef PDC_WIDE
            else if( mouse_event.x >= 40 && mouse_event.x < 40 + 10)
               {
               if( mouse_event.y == 11)
                  {
                  redraw = 1;
                  unicode_offset += 0x80;
                  }
               else if( mouse_event.y == 12 && unicode_offset)
                  {
                  redraw = 1;
                  unicode_offset -= 0x80;
                  }
               }
#endif
        }
    }

    endwin();

    return 0;
}
示例#16
0
文件: command.c 项目: flipk/pfkutils
/* execute the command */
BOOL
command(int commandc)
{
    char filename[PATHLEN + 1];	/* file path name */
    MOUSE *p;			/* mouse data */
    int	c, i;
    FILE *file;
    struct cmd *curritem, *item;	/* command history */
    char *s;

    switch (commandc) {
    case ctrl('C'):	/* toggle caseless mode */
	if (caseless == NO) {
	    caseless = YES;
	    postmsg2("Caseless mode is now ON");
	} else {
	    caseless = NO;
	    postmsg2("Caseless mode is now OFF");
	}
	egrepcaseless(caseless);	/* turn on/off -i flag */
	return(NO);

    case ctrl('R'):	/* rebuild the cross reference */
	if (isuptodate == YES) {
	    postmsg("The -d option prevents rebuilding the symbol database");
	    return(NO);
	}
	exitcurses();
	freefilelist();		/* remake the source file list */
	makefilelist();
	rebuild();
	if (errorsfound == YES) {
	    errorsfound = NO;
	    askforreturn();
	}		
	entercurses();
	clearmsg();		/* clear any previous message */
	totallines = 0;
	disprefs = 0;	
	topline = nextline = 1;
	selecting = 0;
	break;

#if UNIXPC
    case ESC:	/* possible unixpc mouse selection */
#endif
    case ctrl('X'):	/* mouse selection */
	if ((p = getmouseaction(DUMMYCHAR)) == NULL) {
	    return(NO);	/* unknown control sequence */
	}
	/* if the button number is a scrollbar tag */
	if (p->button == '0') {
	    scrollbar(p);
	    break;
	} 
	/* ignore a sweep */
	if (p->x2 >= 0) {
	    return(NO);
	}
	/* if this is a line selection */
	if (p->y1 < FLDLINE) {

	    /* find the selected line */
	    /* note: the selection is forced into range */
	    for (i = disprefs - 1; i > 0; --i) {
		if (p->y1 >= displine[i]) {
		    break;
		}
	    }
	    /* display it in the file with the editor */
	    editref(i);
	} else {	/* this is an input field selection */
	    field = p->y1 - FLDLINE;
	    /* force it into range */
	    if (field >= FIELDS) {
		field = FIELDS - 1;
	    }
	    setfield();
	    resetcmd();
	    return(NO);
	}
	break;

    case '\t':	/* go to next input field */
	if (disprefs) {
	    selecting = !selecting;
	    if (selecting) {
		move(displine[curdispline], 0);
		refresh();
	    } else {
		atfield();
		resetcmd();
	    }
	}
	return(NO);

#ifdef KEY_ENTER
    case KEY_ENTER:
#endif
    case '\r':
    case '\n':	/* go to reference */
	if (selecting) {
	    editref(curdispline);
	    return(YES);
	}
	/* FALLTHROUGH */

    case ctrl('N'):
#ifdef KEY_DOWN
    case KEY_DOWN:
#endif		
#ifdef KEY_RIGHT
    case KEY_RIGHT:
#endif
	if (selecting) {
	    if ((curdispline + 1) < disprefs) {
		move(displine[++curdispline], 0);
		refresh();
	    }
	} else {
	    field = (field + 1) % FIELDS;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);

    case ctrl('P'):	/* go to previous input field */
#ifdef KEY_UP
    case KEY_UP:
#endif
#ifdef KEY_LEFT		
    case KEY_LEFT:
#endif
	if (selecting) {
	    if (curdispline) {
		move(displine[--curdispline], 0);
		refresh();
	    }
	} else {
	    field = (field + (FIELDS - 1)) % FIELDS;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#ifdef KEY_HOME
    case KEY_HOME:	/* go to first input field */
	if (selecting) {
	    curdispline = 0;
	    move(REFLINE, 0);
	    refresh();
	} else {
	    field = 0;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#endif

#ifdef KEY_LL
    case KEY_LL:	/* go to last input field */
	if (selecting) {
	    move(displine[disprefs - 1], 0);
	    refresh();
	} else {
	    field = FIELDS - 1;
	    setfield();
	    atfield();
	    resetcmd();
	}
	return(NO);
#endif /* def(KEY_LL) */

    case ' ':	/* display next page */
    case '+':
    case ctrl('V'):
#ifdef KEY_NPAGE
    case KEY_NPAGE:
#endif
	/* don't redisplay if there are no lines */
	if (totallines == 0) {
	    return(NO);
	}
	/* note: seekline() is not used to move to the next 
	 * page because display() leaves the file pointer at
	 * the next page to optimize paging forward
	 */
	curdispline = 0;
	break;

    case ctrl('H'):
    case '-':	/* display previous page */
#ifdef KEY_PPAGE
    case KEY_PPAGE:
#endif
	/* don't redisplay if there are no lines */
	if (totallines == 0) {
	    return(NO);
	}

	curdispline = 0;

	/* if there are only two pages, just go to the other one */
	if (totallines <= 2 * mdisprefs) {
	    break;
	}
	/* if on first page but not at beginning, go to beginning */
	nextline -= mdisprefs;	/* already at next page */
	if (nextline > 1 && nextline <= mdisprefs) {
	    nextline = 1;
	} else {
	    nextline -= mdisprefs;
	    if (nextline < 1) {
		nextline = totallines - mdisprefs + 1;
		if (nextline < 1) {
		    nextline = 1;
		}
	    }
	}
	seekline(nextline);
	break;

    case '>':	/* write or append the lines to a file */
	if (totallines == 0) {
	    postmsg("There are no lines to write to a file");
	} else {	/* get the file name */
	    move(PRLINE, 0);
	    addstr("Write to file: ");
	    s = "w";
	    if ((c = mygetch()) == '>') {
		move(PRLINE, 0);
		addstr(appendprompt);
		c = '\0';
		s = "a";
	    }
	    if (c != '\r' && 
		mygetline("", newpat,
			  COLS - sizeof(appendprompt), c, NO) > 0
		) {
		shellpath(filename, sizeof(filename), newpat);
		if ((file = myfopen(filename, s)) == NULL) {
		    cannotopen(filename);
		} else {
		    seekline(1);
		    while ((c = getc(refsfound)) != EOF) {
			putc(c, file);
		    }
		    seekline(topline);
		    fclose(file);
		}
	    }
	    clearprompt();
	}
	return(NO);	/* return to the previous field */

    case '<':	/* read lines from a file */
	move(PRLINE, 0);
	addstr(readprompt);
	if (mygetline("", newpat, COLS - sizeof(readprompt),
		      '\0', NO) > 0) {
	    clearprompt();
	    shellpath(filename, sizeof(filename), newpat);
	    if (readrefs(filename) == NO) {
		postmsg2("Ignoring an empty file");
		return(NO);
	    }
	    return(YES);
	}
	clearprompt();
	return(NO);

    case '^':	/* pipe the lines through a shell command */
    case '|':	/* pipe the lines to a shell command */
	if (totallines == 0) {
	    postmsg("There are no lines to pipe to a shell command");
	    return(NO);
	}
	/* get the shell command */
	move(PRLINE, 0);
	addstr(pipeprompt);
	if (mygetline("", newpat, COLS - sizeof(pipeprompt), '\0', NO)
	    == 0) {
	    clearprompt();
	    return(NO);
	}
	/* if the ^ command, redirect output to a temp file */
	if (commandc == '^') {
	    strcat(strcat(newpat, " >"), temp2);
	    /* HBB 20020708: somebody might have even
	     * their non-interactive default shells
	     * complain about clobbering
	     * redirections... --> delete before
	     * overwriting */
	    remove(temp2);
	}
	exitcurses();
	if ((file = mypopen(newpat, "w")) == NULL) {
	    fprintf(stderr, "\
cscope: cannot open pipe to shell command: %s\n", newpat);
	} else {
示例#17
0
文件: cmatrix.c 项目: Treri/cmatrix
int main(int argc, char *argv[]) {
    int i, y, z, optchr, keypress;
    int j = 0;
    int count = 0;
    int screensaver = 0;
    int asynch = 0;
    int bold = 0;
    int force = 0;
    int firstcoldone = 0;
    int oldstyle = 0;
    int random = 0;
    int update = 4;
    int highnum = 0;
    int mcolor = COLOR_GREEN;
    int rainbow = 0;
    int lambda = 0;
    int randnum = 0;
    int randmin = 0;
    int pause = 0;
    int classic = 0;

    srand((unsigned) time(NULL));
    setlocale(LC_ALL, "");

    /* Many thanks to morph- ([email protected]) for this getopt patch */
    opterr = 0;
    while ((optchr = getopt(argc, argv, "abBcfhlLnrosmxVu:C:")) != EOF) {
        switch (optchr) {
        case 's':
            screensaver = 1;
            break;
        case 'a':
            asynch = 1;
            break;
        case 'b':
            if (bold != 2) {
                bold = 1;
            }
            break;
        case 'B':
            bold = 2;
            break;
        case 'C':
            if (!strcasecmp(optarg, "green")) {
                mcolor = COLOR_GREEN;
            } else if (!strcasecmp(optarg, "red")) {
                mcolor = COLOR_RED;
            } else if (!strcasecmp(optarg, "blue")) {
                mcolor = COLOR_BLUE;
            } else if (!strcasecmp(optarg, "white")) {
                mcolor = COLOR_WHITE;
            } else if (!strcasecmp(optarg, "yellow")) {
                mcolor = COLOR_YELLOW;
            } else if (!strcasecmp(optarg, "cyan")) {
                mcolor = COLOR_CYAN;
            } else if (!strcasecmp(optarg, "magenta")) {
                mcolor = COLOR_MAGENTA;
            } else if (!strcasecmp(optarg, "black")) {
                mcolor = COLOR_BLACK;
            } else {
                c_die(" Invalid color selection\n Valid "
                       "colors are green, red, blue, "
                       "white, yellow, cyan, magenta " "and black.\n");
            }
            break;
        case 'c':
            classic = 1;
            break;
        case 'f':
            force = 1;
            break;
        case 'l':
            console = 1;
            break;
        case 'L':
            lock = 1;
            break;
        case 'n':
            bold = -1;
            break;
        case 'h':
        case '?':
            usage();
            exit(0);
        case 'o':
            oldstyle = 1;
            break;
        case 'u':
            update = atoi(optarg);
            break;
        case 'x':
            xwindow = 1;
            break;
        case 'V':
            version();
            exit(0);
        case 'r':
             rainbow = 1;
             break;
        case 'm':
             lambda = 1;
             break;
        }
    }

    if (force && strcmp("linux", getenv("TERM"))) {
        /* setenv is much more safe to use than putenv */
        setenv("TERM", "linux", 1);
    }
    initscr();
    savetty();
    nonl();
    cbreak();
    noecho();
    timeout(0);
    leaveok(stdscr, TRUE);
    curs_set(0);
    signal(SIGINT, sighandler);
    signal(SIGQUIT, sighandler);
    signal(SIGWINCH, sighandler);
    signal(SIGTSTP, sighandler);

if (console) {
#ifdef HAVE_CONSOLECHARS
        if (va_system("consolechars -f matrix") != 0) {
            c_die
                (" There was an error running consolechars. Please make sure the\n"
                 " consolechars program is in your $PATH.  Try running \"consolechars -f matrix\" by hand.\n");
        }
#elif defined(HAVE_SETFONT)
        if (va_system("setfont matrix") != 0) {
            c_die
                (" There was an error running setfont. Please make sure the\n"
                 " setfont program is in your $PATH.  Try running \"setfont matrix\" by hand.\n");
        }
#else
        c_die(" Unable to use both \"setfont\" and \"consolechars\".\n");
#endif
}
    if (has_colors()) {
        start_color();
        /* Add in colors, if available */
#ifdef HAVE_USE_DEFAULT_COLORS
        if (use_default_colors() != ERR) {
            init_pair(COLOR_BLACK, -1, -1);
            init_pair(COLOR_GREEN, COLOR_GREEN, -1);
            init_pair(COLOR_WHITE, COLOR_WHITE, -1);
            init_pair(COLOR_RED, COLOR_RED, -1);
            init_pair(COLOR_CYAN, COLOR_CYAN, -1);
            init_pair(COLOR_MAGENTA, COLOR_MAGENTA, -1);
            init_pair(COLOR_BLUE, COLOR_BLUE, -1);
            init_pair(COLOR_YELLOW, COLOR_YELLOW, -1);
        } else {
#else
        { /* Hack to deal the after effects of else in HAVE_USE_DEFAULT_COLOURS*/
#endif
            init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
            init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
            init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
            init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
            init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
            init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
            init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
            init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
        }
    }

    /* Set up values for random number generation */
    if(classic) {
        /* Japanese character unicode range [they are seen in the original cmatrix] */
        randmin = 12288;
        highnum = 12351;
    } else if (console || xwindow) {
        randmin = 166;
        highnum = 217;
    } else {
        randmin = 33;
        highnum = 123;
    }
    randnum = highnum - randmin;

    var_init();

    while (1) {
        /* Check for signals */
        if (signal_status == SIGINT || signal_status == SIGQUIT) {
            if(lock != 1)
                finish();
            /* exits */
        }
        if (signal_status == SIGWINCH) {
            resize_screen();
            signal_status = 0;
        }

        if(signal_status == SIGTSTP){
            if(lock != 1)
                    finish();
        }

        count++;
        if (count > 4) {
            count = 1;
        }

        if ((keypress = wgetch(stdscr)) != ERR) {
            if (screensaver == 1) {
#ifdef USE_TIOCSTI
                char *str = malloc(0);
                size_t str_len = 0;
                do {
                    str = realloc(str, str_len + 1);
                    str[str_len++] = keypress;
                } while ((keypress = wgetch(stdscr)) != ERR);
                size_t i;
                for (i = 0; i < str_len; i++)
                    ioctl(STDIN_FILENO, TIOCSTI, (char*)(str + i));
                free(str);
#endif
                finish();
            } else {
                switch (keypress) {
                case 'q':
                    if(lock != 1)
                        finish();
                    break;
                case 'a':
                    asynch = 1 - asynch;
                    break;
                case 'b':
                    bold = 1;
                    break;
                case 'B':
                    bold = 2;
                    break;
                case 'L':
                    lock = 1;
                    break;
                case 'n':
                    bold = 0;
                    break;
                case '0': /* Fall through */
                case '1': /* Fall through */
                case '2': /* Fall through */
                case '3': /* Fall through */
                case '4': /* Fall through */
                case '5': /* Fall through */
                case '6': /* Fall through */
                case '7': /* Fall through */
                case '8': /* Fall through */
                case '9':
                    update = keypress - 48;
                    break;
                case '!':
                    mcolor = COLOR_RED;
                    rainbow = 0;
                    break;
                case '@':
                    mcolor = COLOR_GREEN;
                    rainbow = 0;
                    break;
                case '#':
                    mcolor = COLOR_YELLOW;
                    rainbow = 0;
                    break;
                case '$':
                    mcolor = COLOR_BLUE;
                    rainbow = 0;
                    break;
                case '%':
                    mcolor = COLOR_MAGENTA;
                    rainbow = 0;
                    break;
                case 'r':
                     rainbow = 1;
                     break;
                case 'm':
                     lambda = !lambda;
                     break;
                case '^':
                    mcolor = COLOR_CYAN;
                    rainbow = 0;
                    break;
                case '&':
                    mcolor = COLOR_WHITE;
                    rainbow = 0;
                    break;
                case 'p':
                case 'P':
                    pause = (pause == 0)?1:0;
                    break;

                }
            }
        }
        for (j = 0; j <= COLS - 1; j += 2) {
            if ((count > updates[j] || asynch == 0) && pause == 0) {

                /* I dont like old-style scrolling, yuck */
                if (oldstyle) {
                    for (i = LINES - 1; i >= 1; i--) {
                        matrix[i][j].val = matrix[i - 1][j].val;
                    }
                    random = (int) rand() % (randnum + 8) + randmin;

                    if (matrix[1][j].val == 0) {
                        matrix[0][j].val = 1;
                    } else if (matrix[1][j].val == ' '
                             || matrix[1][j].val == -1) {
                        if (spaces[j] > 0) {
                            matrix[0][j].val = ' ';
                            spaces[j]--;
                        } else {

                            /* Random number to determine whether head of next collumn
                               of chars has a white 'head' on it. */

                            if (((int) rand() % 3) == 1) {
                                matrix[0][j].val = 0;
                            } else {
                                matrix[0][j].val = (int) rand() % randnum + randmin;
                            }
                            spaces[j] = (int) rand() % LINES + 1;
                        }
                    } else if (random > highnum && matrix[1][j].val != 1) {
                        matrix[0][j].val = ' ';
                    } else {
                        matrix[0][j].val = (int) rand() % randnum + randmin;
                    }

                } else { /* New style scrolling (default) */
                    if (matrix[0][j].val == -1 && matrix[1][j].val == ' '
                        && spaces[j] > 0) {
                        matrix[0][j].val = -1;
                        spaces[j]--;
                    } else if (matrix[0][j].val == -1
                        && matrix[1][j].val == ' ') {
                        length[j] = (int) rand() % (LINES - 3) + 3;
                        matrix[0][j].val = (int) rand() % randnum + randmin;

                        spaces[j] = (int) rand() % LINES + 1;
                    }
                    i = 0;
                    y = 0;
                    firstcoldone = 0;
                    while (i <= LINES) {

                        /* Skip over spaces */
                        while (i <= LINES && (matrix[i][j].val == ' ' ||
                               matrix[i][j].val == -1)) {
                            i++;
                        }

                        if (i > LINES) {
                            break;
                        }

                        /* Go to the head of this collumn */
                        z = i;
                        y = 0;
                        while (i <= LINES && (matrix[i][j].val != ' ' &&
                               matrix[i][j].val != -1)) {
                            matrix[i][j].is_head = false;
                            i++;
                            y++;
                        }

                        if (i > LINES) {
                            matrix[z][j].val = ' ';
                            continue;
                        }

                        matrix[i][j].val = (int) rand() % randnum + randmin;
                        matrix[i][j].is_head = true;

                        /* If we're at the top of the collumn and it's reached its
                           full length (about to start moving down), we do this
                           to get it moving.  This is also how we keep segments not
                           already growing from growing accidentally =>
                         */
                        if (y > length[j] || firstcoldone) {
                            matrix[z][j].val = ' ';
                            matrix[0][j].val = -1;
                        }
                        firstcoldone = 1;
                        i++;
                    }
                }
            }
            /* A simple hack */
            if (!oldstyle) {
                y = 1;
                z = LINES;
            } else {
                y = 0;
                z = LINES - 1;
            }
            for (i = y; i <= z; i++) {
                move(i - y, j);

                if (matrix[i][j].val == 0 || (matrix[i][j].is_head && !rainbow)) {
                    if (console || xwindow) {
                        attron(A_ALTCHARSET);
                    }
                    attron(COLOR_PAIR(COLOR_WHITE));
                    if (bold) {
                        attron(A_BOLD);
                    }
                    if (matrix[i][j].val == 0) {
                        if (console || xwindow) {
                            addch(183);
                        } else {
                            addch('&');
                        }
                    } else {
                        addch(matrix[i][j].val);
                    }

                    attroff(COLOR_PAIR(COLOR_WHITE));
                    if (bold) {
                        attroff(A_BOLD);
                    }
                    if (console || xwindow) {
                        attroff(A_ALTCHARSET);
                    }
                } else {
                    if(rainbow) {
                        int randomColor = rand() % 6;

                        switch(randomColor){
                            case 0:
                                mcolor = COLOR_GREEN;
                                break;
                            case 1:
                                mcolor = COLOR_BLUE;
                                break;
                            case 2:
                                mcolor = COLOR_BLACK;
                                break;
                            case 3:
                                mcolor = COLOR_YELLOW;
                                break;
                            case 4:
                                mcolor = COLOR_CYAN;
                                break;
                            case 5:
                                mcolor = COLOR_MAGENTA;
                                break;
                       }
                    }
                    attron(COLOR_PAIR(mcolor));
                    if (matrix[i][j].val == 1) {
                        if (bold) {
                            attron(A_BOLD);
                        }
                        addch('|');
                        if (bold) {
                            attroff(A_BOLD);
                        }
                    } else {
                        if (console || xwindow) {
                            attron(A_ALTCHARSET);
                        }
                        if (bold == 2 ||
                            (bold == 1 && matrix[i][j].val % 2 == 0)) {
                            attron(A_BOLD);
                        }
                        if (matrix[i][j].val == -1) {
                            addch(' ');
                        } else if (lambda && matrix[i][j].val != ' ') {
                            addstr("λ");
                        } else {
                            addch(matrix[i][j].val);
                        }
                        if (bold == 2 ||
                            (bold == 1 && matrix[i][j].val % 2 == 0)) {
                            attroff(A_BOLD);
                        }
                        if (console || xwindow) {
                            attroff(A_ALTCHARSET);
                        }
                    }
                    attroff(COLOR_PAIR(mcolor));
                }
            }
        }

        //Check if computer is locked
        if(lock == 1){

            //Add our message to the screen
            char *msg = "Computer locked.";
            int msg_x = LINES/2;
            int msg_y = COLS/2 - strlen(msg)/2;
            int i = 0;

            //Add space before message
            move(msg_x-1, msg_y-2);
            for(i = 0; i < strlen(msg)+4; i++)
                addch(' ');

            //Write message
            move(msg_x, msg_y-2);
            addch(' ');
            addch(' ');
            addstr(msg);
            addch(' ');
            addch(' ');

            //Add space after message
            move(msg_x+1, msg_y-2);
            for(i = 0; i < strlen(msg)+4; i++)
                addch(' ');
        }

        napms(update * 10);
    }
    finish();
}
示例#18
0
文件: linein.c 项目: Nirlendu/mona
char *
inputLineHistSearch(char *prompt, char *def_str, int flag, Hist *hist,
		    int (*incrfunc) (int ch, Str str, Lineprop *prop))
{
    int opos, x, y, lpos, rpos, epos;
    unsigned char c;
    char *p;
#ifdef USE_M17N
    Str tmp;
#endif

    is_passwd = FALSE;
    move_word = TRUE;

    CurrentHist = hist;
    if (hist != NULL) {
	use_hist = TRUE;
	strCurrentBuf = NULL;
    }
    else {
	use_hist = FALSE;
    }
    if (flag & IN_URL) {
	cm_mode = CPL_ALWAYS | CPL_URL;
    }
    else if (flag & IN_FILENAME) {
	cm_mode = CPL_ALWAYS;
    }
    else if (flag & IN_PASSWORD) {
	cm_mode = CPL_NEVER;
	is_passwd = TRUE;
	move_word = FALSE;
    }
    else if (flag & IN_COMMAND)
	cm_mode = CPL_ON;
    else
	cm_mode = CPL_OFF;
    opos = get_strwidth(prompt);
    epos = CLEN - opos;
    if (epos < 0)
	epos = 0;
    lpos = epos / 3;
    rpos = epos * 2 / 3;
    offset = 0;

    if (def_str) {
	strBuf = Strnew_charp(def_str);
	CLen = CPos = setStrType(strBuf, strProp);
    }
    else {
	strBuf = Strnew();
	CLen = CPos = 0;
    }

#ifdef SUPPORT_WIN9X_CONSOLE_MBCS
    enable_win9x_console_input();
#endif
    i_cont = TRUE;
    i_broken = FALSE;
    i_quote = FALSE;
    cm_next = FALSE;
    cm_disp_next = -1;
    need_redraw = FALSE;

#ifdef USE_M17N
    wc_char_conv_init(wc_guess_8bit_charset(DisplayCharset), InnerCharset);
#endif
    do {
	x = calcPosition(strBuf->ptr, strProp, CLen, CPos, 0, CP_FORCE);
	if (x - rpos > offset) {
	    y = calcPosition(strBuf->ptr, strProp, CLen, CLen, 0, CP_AUTO);
	    if (y - epos > x - rpos)
		offset = x - rpos;
	    else if (y - epos > 0)
		offset = y - epos;
	}
	else if (x - lpos < offset) {
	    if (x - lpos > 0)
		offset = x - lpos;
	    else
		offset = 0;
	}
	move(LASTLINE, 0);
	addstr(prompt);
	if (is_passwd)
	    addPasswd(strBuf->ptr, strProp, CLen, offset, COLS - opos);
	else
	    addStr(strBuf->ptr, strProp, CLen, offset, COLS - opos);
	clrtoeolx();
	move(LASTLINE, opos + x - offset);
	refresh();

      next_char:
	c = getch();
#ifdef __EMX__
	if (c == 0) {
	    if (!(c = getcntrl()))
		goto next_char;
	}
#endif
	cm_clear = TRUE;
	cm_disp_clear = TRUE;
	if (!i_quote &&
	    (((cm_mode & CPL_ALWAYS) && (c == CTRL_I || c == ' ')) ||
	     ((cm_mode & CPL_ON) && (c == CTRL_I)))) {
	    if (emacs_like_lineedit && cm_next) {
		_dcompl();
		need_redraw = TRUE;
	    }
	    else {
		_compl();
		cm_disp_next = -1;
	    }
	}
	else if (!i_quote && CLen == CPos &&
		 (cm_mode & CPL_ALWAYS || cm_mode & CPL_ON) && c == CTRL_D) {
	    if (!emacs_like_lineedit) {
		_dcompl();
		need_redraw = TRUE;
	    }
	}
	else if (!i_quote && c == DEL_CODE) {
	    _bs();
	    cm_next = FALSE;
	    cm_disp_next = -1;
	}
	else if (!i_quote && c < 0x20) {	/* Control code */
	    if (incrfunc == NULL
		|| (c = incrfunc((int)c, strBuf, strProp)) < 0x20)
		(*InputKeymap[(int)c]) (c);
	    if (incrfunc && c != (unsigned char)-1 && c != CTRL_J)
		incrfunc(-1, strBuf, strProp);
	    if (cm_clear)
		cm_next = FALSE;
	    if (cm_disp_clear)
		cm_disp_next = -1;
	}
#ifdef USE_M17N
	else {
	    tmp = wc_char_conv(c);
	    if (tmp == NULL) {
		i_quote = TRUE;
		goto next_char;
	    }
	    i_quote = FALSE;
	    cm_next = FALSE;
	    cm_disp_next = -1;
	    if (CLen + tmp->length > STR_LEN || !tmp->length)
		goto next_char;
	    ins_char(tmp);
	    if (incrfunc)
		incrfunc(-1, strBuf, strProp);
	}
#else
	else {
	    i_quote = FALSE;
	    cm_next = FALSE;
	    cm_disp_next = -1;
	    if (CLen >= STR_LEN)
		goto next_char;
	    insC();
	    strBuf->ptr[CPos] = c;
	    if (!is_passwd && get_mctype(&c) == PC_CTRL)
		strProp[CPos] = PC_CTRL;
	    else
		strProp[CPos] = PC_ASCII;
	    CPos++;
	    if (incrfunc)
		incrfunc(-1, strBuf, strProp);
	}
#endif
	if (CLen && (flag & IN_CHAR))
	    break;
    } while (i_cont);
示例#19
0
static int
dialog_create (pinentry_t pinentry, dialog_t dialog)
{
  int err = 0;
  int size_y;
  int size_x;
  int y;
  int x;
  int ypos;
  int xpos;
  int description_x = 0;
  int error_x = 0;
  char *description = NULL;
  char *error = NULL;
  char *prompt = NULL;

#define COPY_OUT(what)							\
  do									\
    if (pinentry->what)							\
      {									\
        what = pinentry_utf8_to_local (pinentry->lc_ctype,		\
				       pinentry->what);			\
        if (!what)							\
	  {								\
	    err = 1;							\
	    goto out;							\
	  }								\
      }									\
  while (0)
    
  COPY_OUT (description);
  COPY_OUT (error);
  COPY_OUT (prompt);

#define MAKE_BUTTON(which,default)					\
  do									\
    {									\
      char *new = NULL;							\
      if (pinentry->which)						\
        {								\
          int len = strlen (pinentry->which);				\
          new = malloc (len + 3);				       	\
	  if (!new)							\
	    {								\
	      err = 1;							\
	      goto out;							\
	    }								\
	  new[0] = '<';							\
	  memcpy (&new[1], pinentry->which, len);			\
          new[len + 1] = '>';						\
	  new[len + 2] = '\0';						\
        }								\
      dialog->which = pinentry_utf8_to_local (pinentry->lc_ctype,	\
					      new ? new : default);	\
      if (!dialog->which)						\
        {								\
	  err = 1;							\
	  goto out;							\
	}								\
    }									\
  while (0)

  MAKE_BUTTON (ok, STRING_OK);
  if (!pinentry->one_button)
    MAKE_BUTTON (cancel, STRING_CANCEL);
  else
    dialog->cancel = NULL;
  if (!pinentry->one_button && pinentry->notok)
    MAKE_BUTTON (notok, STRING_NOTOK);
  else
    dialog->notok = NULL;

  getmaxyx (stdscr, size_y, size_x);

  /* Check if all required lines fit on the screen.  */
  y = 1;		/* Top frame.  */
  if (description)
    {
      char *start = description;
      int len = 0;

      do
	{
	  collect_line (size_x - 4, &start, &len);
	  if (len > description_x)
	    description_x = len;
	  y++;
	}
      while (start[len - 1]);
      y++;
    }
      
  if (pinentry->pin)
    {
      if (error)
	{
	  char *p = error;
	  int err_x = 0;

	  while (*p)
	    {
	      if (*(p++) == '\n')
		{
		  if (err_x > error_x)
		    error_x = err_x;
		  y++;
		  err_x = 0;
		}
	      else
		err_x++;
	    }
	  if (err_x > error_x)
	    error_x = err_x;
	  y += 2;	/* Error message.  */
	}
      y += 2;		/* Pin entry field.  */
    }
  y += 2;		/* OK/Cancel and bottom frame.  */
  
  if (y > size_y)
    {
      err = 1;
      goto out;
    }

  /* Check if all required columns fit on the screen.  */
  x = 0;
  if (description)
    {
      int new_x = description_x;
      if (new_x > size_x - 4)
	new_x = size_x - 4;
      if (new_x > x)
	x = new_x;
    }
  if (pinentry->pin)
    {
#define MIN_PINENTRY_LENGTH 40
      int new_x;

      if (error)
	{
	  new_x = error_x;
	  if (new_x > size_x - 4)
	    new_x = size_x - 4;
	  if (new_x > x)
	    x = new_x;
	}

      new_x = MIN_PINENTRY_LENGTH;
      if (prompt)
	new_x += strlen (prompt) + 1;	/* One space after prompt.  */
      if (new_x > size_x - 4)
	new_x = size_x - 4;
      if (new_x > x)
	x = new_x;
    }
  /* We position the buttons after the first, second and third fourth
     of the width.  Account for rounding.  */
  if (x < 3 * strlen (dialog->ok))
    x = 3 * strlen (dialog->ok);
  if (dialog->cancel)
    if (x < 3 * strlen (dialog->cancel))
      x = 3 * strlen (dialog->cancel);
  if (dialog->notok)
    if (x < 3 * strlen (dialog->notok))
      x = 3 * strlen (dialog->notok);

  /* Add the frame.  */
  x += 4;

  if (x > size_x)
    {
      err = 1;
      goto out;
    }

  dialog->pos = DIALOG_POS_NONE;
  dialog->pin = pinentry->pin;
  dialog->pin_max = pinentry->pin_len;
  dialog->pin_loc = 0;
  dialog->pin_len = 0;
  ypos = (size_y - y) / 2;
  xpos = (size_x - x) / 2;
  move (ypos, xpos);
  addch (ACS_ULCORNER);
  hline (0, x - 2);
  move (ypos, xpos + x - 1);
  addch (ACS_URCORNER);
  move (ypos + 1, xpos + x - 1);
  vline (0, y - 2);
  move (ypos + y - 1, xpos);
  addch (ACS_LLCORNER);
  hline (0, x - 2);
  move (ypos + y - 1, xpos + x - 1);
  addch (ACS_LRCORNER);
  ypos++;
  if (description)
    {
      char *start = description;
      int len = 0;

      do
	{
	  int i;

	  move (ypos, xpos);
	  addch (ACS_VLINE);
	  addch (' ');
	  collect_line (size_x - 4, &start, &len);
	  for (i = 0; i < len - 1; i++)
	    addch ((unsigned char) start[i]);
	  if (start[len - 1] && start[len - 1] != '\n')
	    addch ((unsigned char) start[len - 1]);
	  ypos++;
	}
      while (start[len - 1]);
      move (ypos, xpos);
      addch (ACS_VLINE);
      ypos++;
    }
  if (pinentry->pin)
    {
      int i;

      if (error)
	{
	  char *p = error;
	  i = 0;

	  while (*p)
	    {
	      move (ypos, xpos);
	      addch (ACS_VLINE);
	      addch (' ');
	      if (USE_COLORS && pinentry->color_so != PINENTRY_COLOR_NONE)
		{
		  attroff (COLOR_PAIR (1) | (pinentry->color_fg_bright ? A_BOLD : 0));
		  attron (COLOR_PAIR (2) | (pinentry->color_so_bright ? A_BOLD : 0));
		}
	      else
		standout ();
	      for (;*p && *p != '\n'; p++)
		if (i < x - 4)
		  {
		    i++;
		    addch ((unsigned char) *p);
		  }
	      if (USE_COLORS && pinentry->color_so != PINENTRY_COLOR_NONE)
		{
		  attroff (COLOR_PAIR (2) | (pinentry->color_so_bright ? A_BOLD : 0));
		  attron (COLOR_PAIR (1) | (pinentry->color_fg_bright ? A_BOLD : 0));
		}
	      else
		standend ();
	      if (*p == '\n')
		p++;
	      i = 0;
	      ypos++;
	    }
	  move (ypos, xpos);
	  addch (ACS_VLINE);
	  ypos++;
	}

      move (ypos, xpos);
      addch (ACS_VLINE);
      addch (' ');

      dialog->pin_y = ypos;
      dialog->pin_x = xpos + 2;
      dialog->pin_size = x - 4;
      if (prompt)
	{
	  char *p = prompt;
	  i = strlen (prompt);
	  if (i > x - 4 - MIN_PINENTRY_LENGTH)
	    i = x - 4 - MIN_PINENTRY_LENGTH;
	  dialog->pin_x += i + 1;
	  dialog->pin_size -= i + 1;
	  while (i-- > 0)
	    addch ((unsigned char) *(p++));
	  addch (' ');
	}
      for (i = 0; i < dialog->pin_size; i++)
	addch ('_');
      ypos++;
      move (ypos, xpos);
      addch (ACS_VLINE);
      ypos++;
    }
  move (ypos, xpos);
  addch (ACS_VLINE);

  if (dialog->cancel || dialog->notok)
    {
      dialog->ok_y = ypos;
      /* Calculating the left edge of the left button, rounding down.  */
      dialog->ok_x = xpos + 2 + ((x - 4) / 3 - strlen (dialog->ok)) / 2;
      move (dialog->ok_y, dialog->ok_x);
      addstr (dialog->ok);

      if (dialog->notok)
	{
	  dialog->notok_y = ypos;
	  /* Calculating the left edge of the middle button, rounding up.  */
	  dialog->notok_x = xpos + x / 2 - strlen (dialog->notok) / 2;
	  move (dialog->notok_y, dialog->notok_x);
	  addstr (dialog->notok);
	}
      if (dialog->cancel)
	{
	  dialog->cancel_y = ypos;
	  /* Calculating the left edge of the right button, rounding up.  */
	  dialog->cancel_x = xpos + x - 2 - ((x - 4) / 3 + strlen (dialog->cancel)) / 2;
	  move (dialog->cancel_y, dialog->cancel_x);
	  addstr (dialog->cancel);
	}
    }
  else
    {
      dialog->ok_y = ypos;
      /* Calculating the left edge of the OK button, rounding down.  */
      dialog->ok_x = xpos + x / 2 - strlen (dialog->ok) / 2;
      move (dialog->ok_y, dialog->ok_x);
      addstr (dialog->ok);
    }

 out:
  if (description)
    free (description);
  if (error)
    free (error);
  if (prompt)
    free (prompt);
  return err;
}
示例#20
0
/* redraw nick */
static void statusbar_nick(SBAR_ITEM_REC *item, int ypos)
{
	CHANNEL_REC *channel;
	SERVER_REC *server;
	IRC_SERVER_REC *ircserver;
	NICK_REC *nickrec;
	int size_needed;
	int umode_size;
	char nick[10];

	server = active_win == NULL ? NULL : active_win->active_server;
	ircserver = IRC_SERVER(server);

	umode_size = ircserver == NULL || ircserver->usermode == NULL ||
		ircserver->usermode[0] == '\0' ? 0 :
		strlen(ircserver->usermode)+3;

	/* nick */
	if (server == NULL || server->nick == NULL) {
		nick[0] = '\0';
		nickrec = NULL;
	} else {
		strncpy(nick, server->nick, 9);
		nick[9] = '\0';

		channel = CHANNEL(active_win->active);
		nickrec = channel == NULL ? NULL :
			nicklist_find(channel, server->nick);
	}

	size_needed = 2 + strlen(nick) + umode_size +
		(server != NULL && server->usermode_away ? 7 : 0) +
		(nickrec != NULL && (nickrec->op || nickrec->voice) ? 1 : 0); /* @ + */

	if (item->size != size_needed) {
		/* we need more (or less..) space! */
		statusbar_item_resize(item, size_needed);
		return;
	}

	/* size ok, draw the nick */
	move(ypos, item->xpos);

	set_color(stdscr, sbar_color_dim); addch('[');
	if (nickrec != NULL && (nickrec->op || nickrec->voice)) {
		set_color(stdscr, sbar_color_bold);
		addch(nickrec->op ? '@' : '+');
	}
	set_color(stdscr, sbar_color_normal); addstr(nick);
	if (umode_size) {
		set_color(stdscr, sbar_color_bold); addch('(');
		set_color(stdscr, sbar_color_dim); addch('+');
		set_color(stdscr, sbar_color_normal); addstr(ircserver->usermode);
		set_color(stdscr, sbar_color_bold); addch(')');
	}
	if (server != NULL && server->usermode_away) {
		set_color(stdscr, sbar_color_normal); addstr(" (");
		set_color(stdscr, sbar_color_away); addstr("zZzZ");
		set_color(stdscr, sbar_color_normal); addch(')');
	}
	set_color(stdscr, sbar_color_dim); addch(']');
	screen_refresh(NULL);
}
示例#21
0
value curses_addstr(value s)
{
  CAMLparam1 (s);
  addstr(String_val(s));
  CAMLreturn (Val_unit);
}
示例#22
0
/* redraw channel */
static void statusbar_channel(SBAR_ITEM_REC *item, int ypos)
{
    WINDOW_REC *window;
    WI_ITEM_REC *witem;
    CHANNEL_REC *channel;
    SERVER_REC *server;
    gchar channame[21], winnum[MAX_INT_STRLEN], *tmpname;
    int size_needed;
    int mode_size;

    window = item->bar->pos != STATUSBAR_POS_MIDDLE ? active_win :
            mainwindow_find_sbar(item);
    server = window == NULL ? NULL : window->active_server;

    ltoa(winnum, window == NULL ? 0 : window->refnum);

    witem = window != NULL && (IS_CHANNEL(window->active) || IS_QUERY(window->active)) ?
	    window->active : NULL;
    if (witem == NULL)
    {
	/* display server tag */
        channame[0] = '\0';
	mode_size = 0;
	channel = NULL;

	size_needed = 3 + strlen(winnum) + (server == NULL ? 0 : (17+strlen(server->tag)));
    }
    else
    {
	/* display channel + mode */
        tmpname = show_lowascii(witem->name);
        strncpy(channame, tmpname, 20); channame[20] = '\0';
        g_free(tmpname);

	channel = CHANNEL(witem);
	if (channel == NULL) {
                mode_size = 0;
	} else {
		mode_size = strlen(channel->mode);
		if (mode_size > 0) mode_size += 3; /* (+) */
	}

	size_needed = 3 + strlen(winnum) + strlen(channame) + mode_size;
    }

    if (item->size != size_needed)
    {
        /* we need more (or less..) space! */
        statusbar_item_resize(item, size_needed);
        return;
    }

    move(ypos, item->xpos);
    set_color(stdscr, sbar_color_dim); addch('[');

    /* window number */
    set_color(stdscr, sbar_color_normal); addstr(winnum);
    set_color(stdscr, sbar_color_dim); addch(':');

    if (channame[0] == '\0' && server != NULL)
    {
	/* server tag */
	set_color(stdscr, sbar_color_normal); addstr(server->tag);
        addstr(" (change with ^X)");
    }
    else if (channame[0] != '\0')
    {
	/* channel + mode */
	set_color(stdscr, sbar_color_normal); addstr(channame);
	if (mode_size)
	{
	    set_color(stdscr, sbar_color_bold); addch('(');
	    set_color(stdscr, sbar_color_dim); addch('+');
	    set_color(stdscr, sbar_color_normal); addstr(channel->mode);
	    set_color(stdscr, sbar_color_bold); addch(')');
	}
    }
    set_color(stdscr, sbar_color_dim); addch(']');
    screen_refresh(NULL);
}
示例#23
0
static void screen(FILE *fp) {
    int cmd = 0, columns, lines, x, y;
	WINDOW *std;
	bool endOfFile = false;

	std = initscr();
	columns = std->endx - std->begx;
	if (columns >= MAX_SCREEN_WIDTH - 1) {
		columns = MAX_SCREEN_WIDTH - 1;
	}
	lines	= std->endy - std->begy;
	refresh();
	cbreak();
	noecho();

	while (1){
		if (!endOfFile) {
			for (x = 0; x < lines - 1; x++) {
				for (y = 0; y < columns; y++) {
					buff[y] = !endOfFile ? getc(fp) : ' ';

					switch ((int)buff[y]) {
						case EOF:
							buff[y] = ' ';
							endOfFile = true;
							break;
						case '\n':
							/*	End of the line, filling the rest of buffer */
							memset(buff + y, ' ', columns - y);
							y = columns;
							break;
						case '\t':
							/*	Perform tab instert	*/
							memset(buff + y, ' ', TAB_SIZE);
							y += TAB_SIZE - 1;
							break;
					}
				}
				/*	In case if we got out of the actual line size	*/
				buff[columns]= '\n';
				addstr(buff);
			}
			memset(info, '\0', columns);
			memcpy(info, "---More---", 10);
			memset(buff, ' ', columns);
			if (endOfFile) {
				strcat(info, " End of the file! Press 'q' to quit.");
			}
			memcpy(buff, info, strlen(info));
			attron(A_REVERSE);
			addstr(buff);
			attron(A_NORMAL);
			refresh();
		}

		cmd = getch();
		if (cmd == 'q') {
			endwin();
			return;
		}
	}
	endwin();
	return;
}
示例#24
0
static char *parse(const char *command, struct interface_defn_t *ifd)
{
	size_t old_pos[MAX_OPT_DEPTH] = { 0 };
	int okay[MAX_OPT_DEPTH] = { 1 };
	int opt_depth = 1;
	char *result = NULL;

	while (*command) {
		switch (*command) {
		default:
			addstr(&result, command, 1);
			command++;
			break;
		case '\\':
			if (command[1]) {
				addstr(&result, command + 1, 1);
				command += 2;
			} else {
				addstr(&result, command, 1);
				command++;
			}
			break;
		case '[':
			if (command[1] == '[' && opt_depth < MAX_OPT_DEPTH) {
				old_pos[opt_depth] = result ? strlen(result) : 0;
				okay[opt_depth] = 1;
				opt_depth++;
				command += 2;
			} else {
				addstr(&result, "[", 1);
				command++;
			}
			break;
		case ']':
			if (command[1] == ']' && opt_depth > 1) {
				opt_depth--;
				if (!okay[opt_depth]) {
					result[old_pos[opt_depth]] = '\0';
				}
				command += 2;
			} else {
				addstr(&result, "]", 1);
				command++;
			}
			break;
		case '%':
			{
				char *nextpercent;
				char *varvalue;

				command++;
				nextpercent = strchr(command, '%');
				if (!nextpercent) {
					errno = EUNBALPER;
					free(result);
					return NULL;
				}

				varvalue = get_var(command, nextpercent - command, ifd);

				if (varvalue) {
					addstr(&result, varvalue, strlen(varvalue));
				} else {
#if ENABLE_FEATURE_IFUPDOWN_IP
					/* Sigh...  Add a special case for 'ip' to convert from
					 * dotted quad to bit count style netmasks.  */
					if (strncmp(command, "bnmask", 6) == 0) {
						unsigned res;
						varvalue = get_var("netmask", 7, ifd);
						if (varvalue) {
							res = count_netmask_bits(varvalue);
							if (res > 0) {
								const char *argument = utoa(res);
								addstr(&result, argument, strlen(argument));
								command = nextpercent + 1;
								break;
							}
						}
					}
#endif
					okay[opt_depth - 1] = 0;
				}

				command = nextpercent + 1;
			}
			break;
		}
	}

	if (opt_depth > 1) {
		errno = EUNBALBRACK;
		free(result);
		return NULL;
	}

	if (!okay[0]) {
		errno = EUNDEFVAR;
		free(result);
		return NULL;
	}

	return result;
}
示例#25
0
static void
print_content(void)
{
	int required_lines = 0, disable_detailed = 0, disabled_graphical = 0;

	if (NULL == get_current_node())
		return;

	if (c_list_in_list) {
		NEXT_ROW;
		putl("");

		if (c_use_colors)
			attrset(COLOR_PAIR(LAYOUT_HEADER) | layout[LAYOUT_HEADER].attr);
	
		NEXT_ROW;
		putl("  #   Interface                RX Rate         RX #   " \
			"  TX Rate         TX #");
	
		NEXT_ROW;
		hline(ACS_HLINE, cols);

		if (c_combined_node_list)
			foreach_node(draw_node, NULL);
		else
			draw_node(get_current_node(), NULL);
	} else {
		NEXT_ROW;
		hline(ACS_HLINE, cols);
		move(row, 24);
		addstr(" Press l to enable list view ");
		move(row, 0);
	}

	/*
	 * calculate lines required for graphical and detailed stats unfolded
	 */
	if (c_graphical_in_list)
		required_lines += lines_required_for_graphical();
	else
		required_lines++;

	if (c_detailed_in_list)
		required_lines += lines_required_for_detailed();
	else
		required_lines++;

	if ((rows - row) <= (required_lines + 1)) {
		/*
		 * not enough lines, start over with detailed stats disabled
		 */
		required_lines = 0;
		disable_detailed = 1;

		/*
		 * 1 line for folded detailed stats display
		 */
		required_lines++;

		if (c_graphical_in_list)
			required_lines += lines_required_for_graphical();
		else
			required_lines++;

		if ((rows - row) <= (required_lines + 1)) {
			/*
			 * bad luck, not even enough space for graphical stats
			 * reserve 2 lines for displaying folded detailed and
			 * graphical stats
			 */
			required_lines = 2;
			disabled_graphical = 1;
		}
	}

	/*
	 * Clear out spare space
	 */
	while (row < (rows - (required_lines + 2))) {
		NEXT_ROW; putl("");
	}

	NEXT_ROW;
	hline(ACS_HLINE, cols);

	if (c_graphical_in_list) {
		if (disabled_graphical) {
			move(row, 15);
			addstr(" Increase screen size to see graphical statistics ");
			move(row, 0);
		} else
			draw_graphic();
	} else {
		move(row, 20);
		addstr(" Press g to enable graphical statistics ");
		move(row, 0);
	}

	NEXT_ROW;
	hline(ACS_HLINE, cols);

	if (c_detailed_in_list) {
		if (disable_detailed) {
			move(row, 15);
			addstr(" Increase screen size to see detailed statistics ");
			move(row, 0);
		} else
			draw_detailed();
	} else {
		move(row, 20);
		addstr(" Press d to enable detailed statistics ");
		move(row, 0);
	}
}
示例#26
0
文件: tui.c 项目: neoneye/aeditor
VALUE tui_print(VALUE self, VALUE text) {
	const char *str;
	str = STR2CSTR(text);
	addstr(str);
	return Qnil;
}
示例#27
0
void drawline( int x, int y )
{
	move( x, y );
	addstr( FILL_LINE );
}
示例#28
0
文件: xentop.c 项目: Ultra-Seven/gxen
/* Print a string with the given attributes set. */
static void attr_addstr(int attr, const char *str)
{
	xentop_attron(attr);
	addstr((curses_str_t)str);
	xentop_attroff(attr);
}
示例#29
0
void
display_put_str(const char *s)
{
	addstr(s);
}
/* loads the game from save.dat */
char load(const string& filename)
{
   //LOAD FILE
   int loadversion;
   int l;
   bool dummy_b;
   int dummy;
   long dummy_l;
   FILE *h;

   h=LCSOpenFile(filename.c_str(), "rb", LCSIO_PRE_HOME);
   if(h!=NULL)
   {
      fread(&loadversion,sizeof(int),1,h);

      //NUKE INVALID SAVE GAMES
      if(loadversion<lowestloadversion)
      {
            LCSCloseFile(h);

            reset();

            return 0;
         }

         fread(seed,sizeof(unsigned long),RNG_SIZE,h);

         fread(&mode,sizeof(short),1,h);
         fread(&wincondition,sizeof(short),1,h);
         fread(&fieldskillrate,sizeof(short),1,h);

         fread(&day,sizeof(int),1,h);
         fread(&month,sizeof(int),1,h);
         fread(&year,sizeof(int),1,h);
         fread(&execterm,sizeof(short),1,h);
         fread(&presparty,sizeof(short),1,h);
         fread(&amendnum,sizeof(int),1,h);

         fread(&multipleCityMode,sizeof(bool),1,h);
         fread(&termlimits,sizeof(bool),1,h);
         fread(&deagle,sizeof(bool),1,h);
         fread(&m249,sizeof(bool),1,h);
         fread(&notermlimit,sizeof(bool),1,h);
         fread(&nocourtpurge,sizeof(bool),1,h);
         fread(&stalinmode,sizeof(bool),1,h);

         fread(&stat_recruits,sizeof(int),1,h);
         fread(&stat_dead,sizeof(int),1,h);
         fread(&stat_kills,sizeof(int),1,h);
         fread(&stat_kidnappings,sizeof(int),1,h);
         fread(&stat_buys,sizeof(int),1,h);
         fread(&stat_burns,sizeof(int),1,h);

         fread(&endgamestate,sizeof(char),1,h);
         fread(&ccsexposure,sizeof(char),1,h);
         fread(&ccs_kills,sizeof(char),1,h);

         fread(&Vehicle::curcarid,sizeof(long),1,h);
         fread(&curcreatureid,sizeof(long),1,h);
         fread(&cursquadid,sizeof(long),1,h);
         fread(&police_heat,sizeof(int),1,h);
         fread(&offended_corps,sizeof(short),1,h);
         fread(&offended_cia,sizeof(short),1,h);
         fread(&offended_amradio,sizeof(short),1,h);
         fread(&offended_cablenews,sizeof(short),1,h);
         fread(&offended_firemen,sizeof(short),1,h);
         fread(attorneyseed,sizeof(unsigned long),RNG_SIZE,h);
         //fread(&selectedsiege,sizeof(long),1,h);
         fread(lcityname,sizeof(char),CITY_NAMELEN,h);
         fread(&newscherrybusted,sizeof(char),1,h);

         fread(slogan,sizeof(char),SLOGAN_LEN,h);
         fread(&ledger,sizeof(class Ledger),1,h);
         fread(&party_status,sizeof(short),1,h);

         fread(attitude,sizeof(short),VIEWNUM,h);
         fread(law,sizeof(short),LAWNUM,h);
         fread(house,sizeof(short),HOUSENUM,h);
         fread(senate,sizeof(short),SENATENUM,h);
         fread(court,sizeof(short),COURTNUM,h);
         fread(courtname,sizeof(char)*POLITICIAN_NAMELEN,COURTNUM,h);
         fread(exec,sizeof(char),EXECNUM,h);
         fread(execname,sizeof(char)*POLITICIAN_NAMELEN,EXECNUM,h);
         fread(oldPresidentName,sizeof(char),POLITICIAN_NAMELEN,h);

         //LOCATIONS
         fread(&dummy,sizeof(int),1,h);
         location.resize(dummy);
         for(l=0;l<len(location);l++)
         {
            location[l]=new Location;

            fread(&dummy,sizeof(int),1,h);
            location[l]->loot.resize(dummy);
            for(int l2=0;l2<len(location[l]->loot);l2++)
            {
               int itemLen;
               fread(&itemLen, sizeof(int), 1, h);
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Item* it = create_item(&vec[0]);
               if(it!=NULL)
                  location[l]->loot[l2] = it;
            }
            //Remove items of unknown type.
            for(int l2=len(location[l]->loot)-1; l2>=0; l2--)
            {
               bool del = false;
               if(location[l]->loot[l2]->is_loot())
                  del = (getloottype(location[l]->loot[l2]->get_itemtypename()) == -1);
               else if(location[l]->loot[l2]->is_clip())
                  del = (getcliptype(location[l]->loot[l2]->get_itemtypename()) == -1);
               else if(location[l]->loot[l2]->is_weapon())
                  del = (getweapontype(location[l]->loot[l2]->get_itemtypename()) == -1);
               else if(location[l]->loot[l2]->is_armor())
                  del = (getarmortype(location[l]->loot[l2]->get_itemtypename()) == -1);

               if(del)
               {
                  addstr("Item type ");
                  addstr(location[l]->loot[l2]->get_itemtypename());
                  addstr(" does not exist. Deleting item.");
                  delete_and_remove(location[l]->loot,l2);
               }
            }
            consolidateloot(location[l]->loot); // consolidate loot after loading

            fread(&dummy,sizeof(int),1,h);
            location[l]->changes.resize(dummy);
            for(int l2=0;l2<len(location[l]->changes);l2++)
               fread(&location[l]->changes[l2],sizeof(sitechangest),1,h);

            fread(location[l]->name,sizeof(char),LOCATION_NAMELEN,h);
            fread(location[l]->shortname,sizeof(char),LOCATION_SHORTNAMELEN,h);
            fread(&location[l]->type,sizeof(char),1,h);
            fread(&location[l]->city,sizeof(int),1,h);
            fread(&location[l]->area,sizeof(int),1,h);
            fread(&location[l]->parent,sizeof(int),1,h);
            fread(&location[l]->id,sizeof(int),1,h);

            fread(&location[l]->renting,sizeof(int),1,h);
            fread(&location[l]->newrental,sizeof(char),1,h);
            fread(&location[l]->needcar,sizeof(char),1,h);
            fread(&location[l]->closed,sizeof(int),1,h);
            fread(&location[l]->hidden,sizeof(bool),1,h);
            fread(&location[l]->mapped,sizeof(bool),1,h);
            fread(&location[l]->upgradable,sizeof(bool),1,h);
            fread(&location[l]->highsecurity,sizeof(int),1,h);
            fread(&location[l]->siege,sizeof(siegest),1,h);
            fread(&location[l]->heat,sizeof(int),1,h);
            fread(&location[l]->heat_protection,sizeof(int),1,h);
            fread(&location[l]->compound_walls,sizeof(int),1,h);
            fread(&location[l]->compound_stores,sizeof(int),1,h);
            fread(&location[l]->front_business,sizeof(char),1,h);
            fread(location[l]->front_name,sizeof(char),LOCATION_NAMELEN,h);
            fread(location[l]->front_shortname,sizeof(char),LOCATION_SHORTNAMELEN,h);
            fread(&location[l]->haveflag,sizeof(bool),1,h);

            fread(location[l]->mapseed,sizeof(unsigned long),RNG_SIZE,h);
         }

         //VEHICLES
         fread(&dummy,sizeof(int),1,h);
         vehicle.resize(dummy);
         for(l=0;l<len(vehicle);l++)
         {
            int vehicleLen;
            fread (&vehicleLen, sizeof(int), 1, h);
            vector<char> vec = vector<char> (vehicleLen + 1);
            fread (&vec[0], vehicleLen, 1, h);
            vec[vehicleLen] = '\0';
            vehicle[l] = new Vehicle (&vec[0]);
         }

         //POOL
         fread(&dummy,sizeof(int),1,h);
         pool.resize(dummy);
         for(int pl=0;pl<len(pool);pl++)
         {
            int creatureLen;
            fread (&creatureLen, sizeof(int), 1, h);
            vector<char> vec = vector<char> (creatureLen + 1);
            fread (&vec[0], creatureLen, 1, h);
            vec[creatureLen] = '\0';
            pool[pl] = new Creature(&vec[0]);
            //pool[pl]=new Creature;
            //fread(pool[pl],sizeof(Creature),1,h);
            //read extra interrogation data if applicable
            if(pool[pl]->align==-1 && pool[pl]->alive)
            {
               interrogation* &intr = pool[pl]->activity.intr();
               intr = new interrogation;
               fread(intr->techniques,sizeof(bool[6]),1,h);
               fread(&intr->druguse,sizeof(int),1,h);

               intr->rapport.clear();
               int size;
               fread(&size,sizeof(int),1,h);
               for(int i=0;i<size;i++)
               {
                  long id;
                  float_zero value;
                  fread(&id,sizeof(long),1,h);
                  fread(&value,sizeof(float_zero),1,h);
                  intr->rapport[id]=value;
               }
            }
            /*
            //read equipment
            vector<Item*> dump; //Used to catch invalid pointers from creature so they aren't deleted.
            pool[pl]->drop_weapon(&dump);
            pool[pl]->strip(&dump);
            pool[pl]->clips = deque<Clip*>();
            pool[pl]->extra_throwing_weapons = deque<Weapon*>();
            int itemLen;
            fread(&itemLen, sizeof(int), 1, h);
            if(itemLen != 0)
            {
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Weapon w(&vec[0]);
               if(getweapontype(w.get_itemtypename())!=-1) //Check it is a valid weapon type.
                  pool[pl]->give_weapon(w,&dump);
            }
            //pool[pl]->clips.clear();
            fread(&dummy,sizeof(int),1,h);
            for(int nc=0; nc<dummy; nc++)
            {
               fread(&itemLen, sizeof(itemLen), 1, h);
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Clip c(&vec[0]);
               if(getcliptype(c.get_itemtypename())!=-1) //Check it is a valid clip type.
                  pool[pl]->take_clips(c,len(c));
            }
            //pool[pl]->extra_throwing_weapons.clear();
            fread(&dummy,sizeof(int),1,h);
            for(int ne=0; ne<dummy; ne++)
            {
               fread(&itemLen, sizeof(itemLen), 1, h);
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Weapon w(&vec[0]);
               if(getweapontype(w.get_itemtypename())!=-1) //Check it is a valid weapon type.
                  pool[pl]->give_weapon(w,NULL);
            }
            fread(&itemLen, sizeof(itemLen), 1, h);
            if(itemLen != 0)
            {
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Armor a(&vec[0]);
               if(getarmortype(a.get_itemtypename())!=-1) //Check it is a valid armor type.
                  pool[pl]->give_armor(a,&dump);
            }*/
         }

         //Unique Creatures
         {
            int uniquecreaturesLen;
            fread (&uniquecreaturesLen, sizeof(int), 1, h);
            vector<char> vec = vector<char> (uniquecreaturesLen + 1);
            fread (&vec[0], uniquecreaturesLen, 1, h);
            vec[uniquecreaturesLen] = '\0';
            uniqueCreatures = UniqueCreatures(&vec[0]);
            //fread(&uniqueCreatures,sizeof(UniqueCreatures),1,h);
         }

         //SQUADS
         fread(&dummy,sizeof(int),1,h);
         squad.resize(dummy);
         for(int sq=0;sq<len(squad);sq++)
         {
            squad[sq]=new squadst;

            fread(squad[sq]->name,sizeof(char),SQUAD_NAMELEN,h);
            fread(&squad[sq]->activity,sizeof(activityst),1,h);
            fread(&squad[sq]->id,sizeof(int),1,h);

            for(int pos=0;pos<6;pos++)
            {
               //REBUILD SQUAD FROM POOL
               squad[sq]->squad[pos]=NULL;
               fread(&dummy_b,sizeof(bool),1,h);
               if(dummy_b)
               {
                  int dummy_i;
                  fread(&dummy_i,sizeof(int),1,h);
                  for(int pl=0;pl<len(pool);pl++)
                     if(pool[pl]->id==dummy_i)
                        squad[sq]->squad[pos]=pool[pl];
               }
            }

            fread(&dummy,sizeof(int),1,h);
            squad[sq]->loot.resize(dummy);
            for(int l2=0;l2<len(squad[sq]->loot);l2++)
            {
               int itemLen;
               fread(&itemLen, sizeof(int), 1, h);
               vector<char> vec = vector<char>(itemLen + 1);
               fread(&vec[0], itemLen, 1, h);
               vec[itemLen] = '\0';

               Item* it = create_item(&vec[0]);
               //if(it!=NULL) //Assume save file is correct? -XML
                  squad[sq]->loot[l2] = it;
               /*else
                  squad[sq]->loot.erase(loot.begin()+l2--);*/
            }
            //Remove items of unknown type.
            for(int l2=len(squad[sq]->loot)-1; l2>=0; l2--)
            {
               bool del = false;
               if(squad[sq]->loot[l2]->is_loot())
                  del = (getloottype(squad[sq]->loot[l2]->get_itemtypename()) == -1);
               else if(squad[sq]->loot[l2]->is_clip())
                  del = (getcliptype(squad[sq]->loot[l2]->get_itemtypename()) == -1);
               else if(squad[sq]->loot[l2]->is_weapon())
                  del = (getweapontype(squad[sq]->loot[l2]->get_itemtypename()) == -1);
               else if(squad[sq]->loot[l2]->is_armor())
                  del = (getarmortype(squad[sq]->loot[l2]->get_itemtypename()) == -1);

               if(del)
               {
                  addstr("Item type ");
                  addstr(squad[sq]->loot[l2]->get_itemtypename());
                  addstr(" does not exist. Deleting item.");
                  delete_and_remove(squad[sq]->loot,l2);
               }
            }
            consolidateloot(squad[sq]->loot); // consolidate loot after loading
         }

         activesquad=NULL;
         fread(&dummy_b,sizeof(bool),1,h);
         if(dummy_b)
         {
            int dummy_i;
            fread(&dummy_i,sizeof(int),1,h);
            for(int sq=0;sq<len(squad);sq++)
               if(squad[sq]->id==dummy_i)
               {
                  activesquad=squad[sq];
                  break;
               }
         }

         //DATES
         fread(&dummy,sizeof(int),1,h);
         date.resize(dummy);
         for(int dt=0;dt<len(date);dt++)
         {
            date[dt]=new datest;

            fread(&date[dt]->mac_id,sizeof(long),1,h);
            fread(&date[dt]->timeleft,sizeof(short),1,h);
            fread(&date[dt]->city,sizeof(int),1,h);

            fread(&dummy,sizeof(int),1,h);
            date[dt]->date.resize(dummy);
            for(int dt2=0;dt2<len(date[dt]->date);dt2++)
            {
               int creatureLen;
               fread (&creatureLen, sizeof(int), 1, h);
               vector<char> vec = vector<char> (creatureLen + 1);
               fread (&vec[0], creatureLen, 1, h);
               vec[creatureLen] = '\0';
               date[dt]->date[dt2] = new Creature(&vec[0]);

               //date[dt]->date[dt2]=new Creature;
               //fread(date[dt]->date[dt2],sizeof(Creature),1,h);
            }
         }

         //RECRUITS
         fread(&dummy,sizeof(int),1,h);
         recruit.resize(dummy);
         for(int rt=0;rt<len(recruit);rt++)
         {
            recruit[rt]=new recruitst;
            fread(&recruit[rt]->recruiter_id,sizeof(long),1,h);
            fread(&recruit[rt]->timeleft,sizeof(short),1,h);
            fread(&recruit[rt]->level,sizeof(char),1,h);
            fread(&recruit[rt]->eagerness1,sizeof(char),1,h);
            fread(&recruit[rt]->task,sizeof(char),1,h);

            int creatureLen;
            fread (&creatureLen, sizeof(int), 1, h);
            vector<char> vec = vector<char> (creatureLen + 1);
            fread (&vec[0], creatureLen, 1, h);
            vec[creatureLen] = '\0';
            recruit[rt]->recruit = new Creature(&vec[0]);
            //recruit[rt]->recruit = new Creature;
            //fread(recruit[rt]->recruit,sizeof(Creature),1,h);
         }

         //NEWS STORIES
         fread(&dummy,sizeof(int),1,h);
         newsstory.resize(dummy);
         for(int ns=0;ns<len(newsstory);ns++)
         {
            newsstory[ns]=new newsstoryst;

            fread(&newsstory[ns]->type,sizeof(short),1,h);
            fread(&newsstory[ns]->view,sizeof(short),1,h);

            fread(&newsstory[ns]->loc,sizeof(long),1,h);
            fread(&newsstory[ns]->priority,sizeof(long),1,h);
            fread(&newsstory[ns]->page,sizeof(long),1,h);
            fread(&newsstory[ns]->positive,sizeof(char),1,h);
            fread(&newsstory[ns]->siegetype,sizeof(short),1,h);

            newsstory[ns]->cr=NULL;
            fread(&dummy_b,sizeof(bool),1,h);
            if(dummy_b)
            {
               fread(&dummy_l,sizeof(long),1,h);
               for(int pl=0;pl<len(pool);pl++)
                  if(pool[pl]->id==dummy_l)
                  {
                     newsstory[ns]->cr=pool[pl];
                     break;
                  }
            }

            fread(&dummy,sizeof(int),1,h);
            newsstory[ns]->crime.resize(dummy);
            for(int dt2=0;dt2<len(newsstory[ns]->crime);dt2++)
               fread(&newsstory[ns]->crime[dt2],sizeof(int),1,h);
         }

         // Liberal Media
         fread(public_interest,sizeof(public_interest),1,h);
         fread(background_liberal_influence,sizeof(background_liberal_influence),1,h);

         // Site mode options
         fread(&encounterwarnings,sizeof(bool),1,h);
         bool musicenabled;
         fread(&musicenabled,sizeof(bool),1,h);
         music.enableIf(musicenabled);

         LCSCloseFile(h);

         // Check that vehicles are of existing types.
         for(int v=0;v<len(vehicle);v++)
         {
            if(getvehicletype(vehicle[v]->vtypeidname())==-1)
            { //Remove vehicle of non-existing type.
               addstr("Vehicle type "+vehicle[v]->vtypeidname()+" does not exist. Deleting vehicle.");
               delete_and_remove(vehicle,v--);
            }
         }

         return 1;
      }

   gamelog.log("Could not load");
   return 0;
}