コード例 #1
0
ファイル: m_help.c プロジェクト: BackupTheBerlios/shadowircd
/*
 * m_help - HELP message handler
 *      parv[0] = sender prefix
 */
static void
m_help(struct Client *client_p, struct Client *source_p, int parc, char *parv[])
{
	static time_t last_used = 0;

	if(ConfigFileEntry.use_help)
	{
		/* HELP is always local */
		if((last_used + ConfigFileEntry.pace_wait_simple) > CurrentTime)
		{
			/* safe enough to give this on a local connect only */
			sendto_one(source_p, form_str(RPL_LOAD2HI),
				   me.name, parv[0], "HELP");
			sendto_one(source_p, form_str(RPL_ENDOFHELP), 
				   me.name, source_p->name,
				   (parc > 1 && !EmptyString(parv[1])) ? parv[1] : "index");
			return;
		}
		else
		{
			last_used = CurrentTime;
		}

		if(parc > 1)
			dohelp(source_p, UHPATH, parv[1], parv[0]);
		else
			dohelp(source_p, UHPATH, NULL, parv[0]);
	}
	else
	{
		list_commands(source_p);
	}
}
コード例 #2
0
ファイル: m_help.c プロジェクト: BackupTheBerlios/shadowircd
static void
mo_uhelp(struct Client *client_p, struct Client *source_p, int parc, char *parv[])
{
	if(parc > 1)
		dohelp(source_p, UHPATH, parv[1], parv[0]);
	else
		dohelp(source_p, UHPATH, NULL, parv[0]);
}
コード例 #3
0
ファイル: getoptionsBP.c プロジェクト: rlp1938/gengetopt
options_t
process_options(int argc, char **argv)
{

//</endoptions>
//<golongwshortpre>

    int opt;

    while (1) {
        int this_option_optind = optind ? optind : 1;
        int option_index = 0;
        static struct option long_options[] = {
            {"help", 0,	0,	'h' },
//</golongwshortpre>
//<golongwshortpost>
            {0,	0,	0,	0 }
        };

        opt = getopt_long(argc, argv, optstr, long_options,
                          &option_index);
        if (opt == -1)
            break;
//</golongwshortpost>
//<glongonlypre>
        switch (opt) {
        case 0:
            switch (option_index) {
//</glongonlypre>
//<glongonlypost>
            } // switch(option_index)
            break;
//</glongonlypost>
//<glshortspre>
        case 'h':
            dohelp(0);
            break;
//</glshortspre>
//<glshortspost>
        case ':':
            fprintf(stderr, "Option %s requires an argument\n",
                    argv[this_option_optind]);
            dohelp(1);
            break;
        case '?':
            fprintf(stderr, "Unknown option: %s\n",
                    argv[this_option_optind]);
            dohelp(1);
            break;
        }

    } // while(1)
    return opts;
} // process_options()
コード例 #4
0
ファイル: getoptions.c プロジェクト: rlp1938/autosd
options_t
process_options(int argc, char **argv)
{

	static const char optstr[] = ":hm";

	options_t opts = { 0 };

	int opt;

	while (1) {
		int this_option_optind = optind ? optind : 1;
		int option_index = 0;
		static struct option long_options[] = {
			{"help", 0,	0,	'h' },
			{"monitor",	0,	0,	'm'},
			{0,	0,	0,	0 }
		};

		opt = getopt_long(argc, argv, optstr, long_options,
							&option_index);
		if (opt == -1)
			break;
		switch (opt) {
			case 0:
				switch (option_index) {
				} // switch(option_index)
				break;
			case 'h':
				dohelp(0);
				break;
			case 'm':
				opts.monitor = 1;
				break;
			case ':':
				fprintf(stderr, "Option %s requires an argument\n",
							argv[this_option_optind]);
				dohelp(1);
				break;
			case '?':
				fprintf(stderr, "Unknown option: %s\n",
								argv[this_option_optind]);
				dohelp(1);
				break;
		}

	} // while(1)
	return opts;
} // process_options()
コード例 #5
0
ファイル: m_help.c プロジェクト: mdharris/ircd
/*
 * m_help - HELP message handler
 *      parv[0] = sender prefix
 */
static void
m_help(struct Client *client_p, struct Client *source_p,
       int parc, char *parv[])
{
  static time_t last_used = 0;

  /* HELP is always local */
  if ((last_used + ConfigFileEntry.pace_wait_simple) > CurrentTime)
  {
    /* safe enough to give this on a local connect only */
    sendto_one(source_p,form_str(RPL_LOAD2HI),
               me.name, source_p->name);
    return;
  }

  last_used = CurrentTime;

  dohelp(source_p, UHPATH, parv[1]);
}
コード例 #6
0
ファイル: aoi.c プロジェクト: lhw/wargame
int
handlecommand(int c, char *buf)
{
	char *msg = "unknown command\n";
	switch(whatcmd(buf)) {
	case CMD_LIST:
		dolist(c);
		break;
	case CMD_VIEW:
		doview(c, buf);
		break;
	case CMD_HELP:
		dohelp(c, buf);
		break;
	case CMD_NONE:
		send(c, msg, strlen(msg), 0);
		break;
	}
}
コード例 #7
0
ファイル: vulture_win.cpp プロジェクト: DanielT/Vulture
/* show a main menu with common options when the user presses esc */
void vulture_show_mainmenu()
{
	int winid, n;
	anything any;
	menu_item *selected;

	winid = vulture_create_nhwindow(NHW_MENU);
	vulture_start_menu(winid);
	
	any.a_int = 1;
	vulture_add_menu(winid, NO_GLYPH, &any, 'h', 0, ATR_BOLD,
					"Help", MENU_UNSELECTED);
	any.a_int = 2;
	vulture_add_menu(winid, NO_GLYPH, &any, 'O', 0, ATR_BOLD,
					"Options", MENU_UNSELECTED);
	any.a_int = 3;
	vulture_add_menu(winid, NO_GLYPH, &any, 'I', 0, ATR_BOLD,
					"Interface options", MENU_UNSELECTED);
	any.a_int = 4;
	vulture_add_menu(winid, NO_GLYPH, &any, 'S', 0, ATR_BOLD,
					"Save & Quit", MENU_UNSELECTED);
	any.a_int = 5;
	vulture_add_menu(winid, NO_GLYPH, &any, 'Q', 0, ATR_BOLD,
					"Quit", MENU_UNSELECTED);

	vulture_end_menu(winid, "Main menu");
	n = vulture_select_menu(winid, PICK_ONE, &selected);
	vulture_destroy_nhwindow(winid);

	if (n < 1)
		return;

	switch(selected[0].item.a_int)
	{
		case 1: dohelp(); break;
		case 2: doset(); break;
		case 3: vulture_iface_opts(); break;
		case 4: dosave(); break;
		case 5: done2(); break;
	}
}
コード例 #8
0
ファイル: appconsole.c プロジェクト: LucasBe/sendd
static void
docmd(char *buf)
{
	int i;

	if (*buf == 0 || *buf == '\n') {
		return;
	}
	if (*buf == '?' || strncasecmp(buf, "help", 4) == 0) {
		dohelp();
		return;
	}

	for (i = 0; i < cmd_cnt; i++) {
		if (strncasecmp(cmds[i].cmdstr, buf, cmds[i].cmdlen) == 0) {
			cmds[i].cmd_handler(buf);
			return;
		}
	}

	fprintf(outfile, "Unknown command\n");
	return;
}
コード例 #9
0
ファイル: alarm.c プロジェクト: rlp1938/Alarm
int main(int argc, char **argv)
{
	int opt, numcolon;
	int totsec, seconds, minutes, hours;
	fdata sfd;
	time_t now;
	char *user, *start, *end, *prog2run, *mov2show, *timespec;
	char userbuf[FILENAME_MAX];
	char *fmt = "/home/%s/.config/alarm/alarm.txt";
	int cookingmode;
	int ampm = 0;
	// defaults
	cookingmode = 1;
	while((opt = getopt(argc, argv, ":ha")) != -1) {
		switch(opt) {
		case 'h':
			dohelp(0);
		break;
		case 'a':
			// absolute time of day ie alarm clock mode;
			cookingmode = 0;
		break;
		case ':':
			fprintf(stderr, "Option %c requires an argument\n",optopt);
			dohelp(1);
		break;
		case '?':
			fprintf(stderr, "Unknown option: %c\n",optopt);
			dohelp(1);
		break;
		} //switch()
	}//while()
	// now process the non-option arguments

	now = time(NULL);

	// 1.Check that argv[???] exists.
	if (!(argv[optind])) {
		fprintf(stderr, "No time specifier provided.\n");
		dohelp(1);
	}
	timespec = argv[optind];
	optind++;
	// go look for am or pm
	if (argv[optind]) {
		char *cp = argv[optind];
		if (*cp == 'P' || *cp == 'p') ampm = 1;
		// and it just doesn't matter if there is a following M|m or not
	}
	// Read my config file
	user = getenv("USER");
	sprintf(userbuf,  fmt, user);
	sfd = readfile(userbuf, 0, 0);
	if(sfd.from) {
		start = sfd.from;
		end = sfd.to;
	} else {
		firstrun("alarm", "alarm.txt");
		user = getenv("HOME");
		char advice[NAME_MAX];
		sprintf(advice, "Installed alarm.txt at %s.config/alarm/\n",
				user);
		fputs(advice, stderr);
		fputs("Please edit that file to suit your needs.\n", stderr);
		exit(EXIT_SUCCESS);
	}

	prog2run = getactdata(start, end, "program");
	mov2show = getactdata(start, end, "data");

	// now deal with the users timespec
	numcolon = countchars(timespec, ':');
	hours = minutes = seconds = 0;
	char *wstr = strdup(timespec);
	char *tofree = wstr;	// wstr gets altered.
	switch(numcolon) {
		char *cp;
		case 0:
		// the number is minutes;
		if (strlen(wstr)) minutes = strtol(wstr, NULL, 10);
		break;
		case 1:
		// have mm:ss or :ss or mm:
		cp = strchr(wstr, ':');
		*cp = '\0';
		if (strlen(wstr)) minutes = strtol(wstr, NULL, 10);
		cp++; // look at the second half
		wstr = cp;
		if (strlen(wstr)) seconds = strtol(wstr, NULL, 10);
		break;
		case 2:
		// have hh:mm:ss or hh:mm:
		cp = strchr(wstr, ':');
		*cp = '\0';
		if (strlen(wstr)) hours = strtol(wstr, NULL, 10);
		cp++; // next part
		wstr = cp;
		cp = strchr(wstr, ':');
		*cp = '\0';
		if (strlen(wstr)) minutes = strtol(wstr, NULL, 10);
		cp++;
		wstr = cp;
		if (strlen(wstr)) seconds = strtol(wstr, NULL, 10);
		break;
		default:
		fprintf(stderr,
				"Badly formed time specification: %s\n", timespec);
		exit(EXIT_FAILURE);
		break;
	}
	free(tofree);
	// total seconds to elapse before alarm
	if (ampm) {
		if (!(cookingmode)) {
			if (hours < 12) hours += 12;
		}
	}
	if(!(cookingmode)) { // used as an alarm clock, not cooking timer
		totsec = addclocktime(now, hours, minutes, seconds);
	} else {
		totsec = seconds + 60 * minutes + 3600 * hours;
	}
	printf("Total seconds: %d\n", totsec);
	// report every 60 seconds
	int aminute = 60;	// seconds
	while (aminute < totsec) {
		sleep(aminute);
		totsec -= aminute;
		if (cookingmode) {
			fprintf(stdout, "Remaining: %d seconds.\n", totsec);
		}
	}
	sleep(totsec);
	runit(prog2run, mov2show);
	return 0;
}//main()
コード例 #10
0
ファイル: mhmain.c プロジェクト: Elronnd/nethack-360-nao
LRESULT
onWMCommand(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PNHMainWindow data;

    data = (PNHMainWindow) GetWindowLong(hWnd, GWL_USERDATA);
    wmId = LOWORD(wParam);
    wmEvent = HIWORD(wParam);

    // process the menu selections:
    switch (wmId) {
    case IDM_ABOUT:
        DialogBox(GetNHApp()->hApp, (LPCTSTR) IDD_ABOUTBOX, hWnd,
                  (DLGPROC) About);
        break;

    case IDM_EXIT:
        done2();
        break;

    case IDM_SAVE:
        dosave();
        break;

    case IDM_MAP_TILES:
    case IDM_MAP_ASCII4X6:
    case IDM_MAP_ASCII6X8:
    case IDM_MAP_ASCII8X8:
    case IDM_MAP_ASCII16X8:
    case IDM_MAP_ASCII7X12:
    case IDM_MAP_ASCII8X12:
    case IDM_MAP_ASCII12X16:
    case IDM_MAP_ASCII16X12:
    case IDM_MAP_ASCII10X18:
        mswin_select_map_mode(menuid2mapmode(wmId));
        break;

    case IDM_MAP_FIT_TO_SCREEN:
        if (IS_MAP_FIT_TO_SCREEN(iflags.wc_map_mode)) {
            mswin_select_map_mode(IS_MAP_ASCII(iflags.wc_map_mode)
                                      ? data->mapAcsiiModeSave
                                      : MAP_MODE_TILES);
        } else {
            mswin_select_map_mode(IS_MAP_ASCII(iflags.wc_map_mode)
                                      ? MAP_MODE_ASCII_FIT_TO_SCREEN
                                      : MAP_MODE_TILES_FIT_TO_SCREEN);
        }
        break;

    case IDM_VIEW_KEYPAD:
        GetNHApp()->bCmdPad = !GetNHApp()->bCmdPad;
        CheckMenuItem(
            _get_main_menu(ID_VIEW), IDM_VIEW_KEYPAD,
            MF_BYCOMMAND | (GetNHApp()->bCmdPad ? MF_CHECKED : MF_UNCHECKED));
        mswin_layout_main_window(GetNHApp()->hCmdWnd);
        break;

    case IDM_VIEW_OPTIONS:
        doset();
        break;

    case IDM_DIRECT_COMMAND: /* SmartPhone: display dialog to type in arbitary
                                command text */
        mswin_direct_command();
        break;

    case IDM_HELP_LONG:
        display_file(HELP, TRUE);
        break;

    case IDM_HELP_COMMANDS:
        display_file(SHELP, TRUE);
        break;

    case IDM_HELP_HISTORY:
        (void) dohistory();
        break;

    case IDM_HELP_INFO_CHAR:
        (void) dowhatis();
        break;

    case IDM_HELP_INFO_KEY:
        (void) dowhatdoes();
        break;

    case IDM_HELP_OPTIONS:
        option_help();
        break;

    case IDM_HELP_OPTIONS_LONG:
        display_file(OPTIONFILE, TRUE);
        break;

    case IDM_HELP_EXTCMD:
        (void) doextlist();
        break;

    case IDM_HELP_LICENSE:
        display_file(LICENSE, TRUE);
        break;

    case IDM_HELP_MENU:
        dohelp();
        break;

    default:
        return 1;
    }
    return 0;
}
コード例 #11
0
ファイル: util.c プロジェクト: scotte/pcp
void
dohelp(int command, int full)
{
    if (command < 0) {
	puts("help [ command ]\n");
	dohelp(ATTR, HELP_USAGE);
	dohelp(PMNS_CHILDREN, HELP_USAGE);
	dohelp(CLOSE, HELP_USAGE);
	dohelp(DBG, HELP_USAGE);
	dohelp(DESC, HELP_USAGE);
	dohelp(FETCH, HELP_USAGE);
	dohelp(GETDESC, HELP_USAGE);
	dohelp(INSTANCE, HELP_USAGE);
	dohelp(LABEL, HELP_USAGE);
	dohelp(PMNS_NAME, HELP_USAGE);
	dohelp(NAMESPACE, HELP_USAGE);
	dohelp(OPEN, HELP_USAGE);
	dohelp(PMNS_PMID, HELP_USAGE);
	dohelp(PROFILE, HELP_USAGE);
	dohelp(QUIT, HELP_USAGE);
	dohelp(STATUS, HELP_USAGE);
	dohelp(STORE, HELP_USAGE);
	dohelp(INFO, HELP_USAGE);
	dohelp(TIMER, HELP_USAGE);
	dohelp(PMNS_TRAVERSE, HELP_USAGE);
	dohelp(WAIT, HELP_USAGE);
	dohelp(WATCH, HELP_USAGE);
	putchar('\n');
    }
    else {
	if (full == HELP_FULL)
	    putchar('\n');

	switch (command) {
	case ATTR:
	    puts("attr name [value]");
	    puts("attr attr# [value]");
	    break;
	case CLOSE:
	    puts("close");
	    break;
	case DBG:
	    puts("debug all | none");
	    puts("debug option [ option ... ] (option is a symbolic name or a decimal number)");
	    break;
	case DESC:
	    puts("desc metric");
	    break;
	case FETCH:
	    puts("fetch metric [ metric ... ]");
	    break;
	case GETDESC:
	    puts("getdesc on | off");
	    break;
	case INFO:
	    puts("text metric");
	    puts("text indom indom#");
	    break;
	case INSTANCE:
	    puts("instance indom# [ number | name | \"name\" ]");
	    break;
	case LABEL:
	    puts("label context");
	    puts("label domain");
	    puts("label indom indom#");
	    puts("label cluster cluster#");
	    puts("label item metric");
	    puts("label instances indom#");
	    break;
	case NAMESPACE:
	    puts("namespace fname");
	    break;
	case OPEN:
	    puts("open dso dsoname init_routine [ domain# ]");
	    puts("open pipe execname [ arg ... ]");
	    puts("open socket unix sockname");
	    puts("open socket inet port#|service");
	    puts("open socket ipv6 port#|service");
	    break;
	case PMNS_CHILDREN:
	    puts("children metric-name");
	    break;
	case PMNS_NAME:
	    puts("name pmid#");
	    break;
	case PMNS_PMID:
	    puts("pmid metric-name");
	    break;
	case PMNS_TRAVERSE:
	    puts("traverse metric-name");
	    break;
	case PROFILE:
	    puts("profile indom# [ all | none ]");
	    puts("profile indom# [ add | delete ] number");
	    break;
	case QUIT:
	    puts("quit");
	    break;
	case STATUS:
	    puts("status");
	    break;
	case STORE:
	    puts("store metric \"value\"");
	    break;
	case WATCH:
	    puts("watch logfilename");
	    break;
	case TIMER:
	    puts("timer on | off");
	    break;
	case WAIT:
	    puts("wait seconds");
	    break;
	default:
	    fprintf(stderr, "Help for that command (%d) not supported!\n", command);
	}

	if (full == HELP_FULL) {
	    putchar('\n');
	    switch (command) {
	    case ATTR:
		puts(
"Set a security attribute. These set aspects of per-user authentication,\n"
"allowing a PMDA to provide different metric views for different users.\n");
		break;
	    case CLOSE:
		puts(
"Close the pipe to a daemon PMDA or dlclose(3) a DSO PMDA. dbpmda does not\n"
"exit, allowing another PMDA to be opened.\n");
		break;
	    case DBG:
		puts(
"Specify which debugging options should be active (see pmdbg(1)).  Options\n"
"may be specified by name (or number for the old bit-field options), with\n"
"multiple options separated by white space.  All options may be selected or\n"
"deselected if 'all' or 'none' is specified.  The current setting is\n"
"displayed by the status command.\n\n");
		break;
	    case DESC:
		puts(
"Print out the meta data description for the 'metric'.  The metric may be\n"
"specified by name, or as a PMID of the form N, N.N or N.N.N.\n");
		break;
	    case FETCH:
		puts(
"Fetch metrics from the PMDA.  The metrics may be specified as a list of\n"
"metric names, or PMIDs of the form N, N.N or N.N.N.\n");
		break;
	    case GETDESC:
		puts(
"Before doing a fetch, get the descriptor so that the result of a fetch\n"
"can be printed out correctly.\n");
		break;
	    case INFO:
		puts(
"Retrieve the help text for the 'metric' or 'indom' from the PMDA.  The one\n"
"line message is shown between '[' and ']' with the long message on the next\n"
"line.  To get the help text for an instance domain requires the word\n"
"``indom'' before the indom number\n");
		break;
	    case INSTANCE:
		puts(
"List the instances in 'indom'.  The list may be restricted to a specific\n"
"instance 'name' or 'number'.\n");
		break;
	    case NAMESPACE:
		puts(
"Unload the current Name Space and load up the given Name Space.\n"
"If unsuccessful then will try to reload the previous Name Space.\n");
		break;
	    case OPEN:
		puts(
"Open a PMDA as either a DSO, via a network socket (unix/inet/ipv6), or as a\n"
"daemon (connected with a pipe).  The 'dsoname' and 'execname' fields are\n"
"the path to the PMDA shared object file or executable.  The first socket PMDA\n"
"field is the type - either unix (if supported), inet or ipv6.  The 'sockname'\n"
"argument for unix sockets is a path of a named pipe where a PMDA is listening\n"
"for connections.  The 'port' argument is a port number, 'serv' a service name\n"
"typically defined in /etc/services (resolved to a port via getservent(3)).\n"
"The arguments to this command are similar to a line in the pmcd.conf file.\n");
		break;
	    case PMNS_CHILDREN:
	        puts(
"Fetch and print the next name component of the direct decendents of\n"
"metric-name in the PMNS, reporting for each if it is a leaf node or a\n"
"non-leaf node.\n"
"Most useful for PMDAs that support dynamic metrics in the PMNS.\n");
		break;
	    case PMNS_NAME:
		puts(
"Print the name of the metric with PMID pmid#.  The pmid# syntax follows\n"
"the source PMNS syntax, namely 3 numbers separated by '.' to encode\n"
"the domain, cluster and item components of the PMID, e.g.\n"
"    name 29.0.1004\n"
"Most useful for PMDAs that support dynamic metrics in the PMNS.\n");
		break;
	    case PMNS_PMID:
		puts(
"Print the PMID for the named metric\n"
"Most useful for PMDAs that support dynamic metrics in the PMNS.\n");
		break;
	    case PMNS_TRAVERSE:
		puts(
"Fetch and print all of the decendent metric names below metric-name\n"
"in the PMNS.\n"
"Most useful for PMDAs that support dynamic metrics in the PMNS.\n");
		break;
	    case PROFILE:
		puts(
"For the instance domain specified, the profile may be changed to include\n"
"'all' instances, no instances, add an instance or delete an instance.\n");
		break;
	    case QUIT:
		puts("Exit dbpmda.  This also closes any open PMDAs.\n");
		break;
	    case STATUS:
		puts(
"Display the state of dbpmda, including which PMDA is connected, which\n"
"debug options are set, and the current profile.\n");
		break;
	    case STORE:
		puts(
"Store the value (int, real or string) into the 'metric'.  The metric may be\n"
"specified by name or as a PMID with the format N, N.N, N.N.N.  The value to\n"
"be stored must be enclosed in quotes.  Unlike the other commands, a store\n"
"must request a metric description and fetch the metric to determine how to\n"
"interpret the value, and to allocate the PDU for transmitting the value,\n"
"respectively.  The current profile will be used.\n");
		break;
	    case TIMER:
		puts(
"Report the response time of the PMDA when sending and receiving PDUs.\n");
		break;
	    case WATCH:
		puts(
"An xterm window is opened which tails the specified log file.  This window\n"
"must be closed by the user when no longer required.\n");
		break;
	    case WAIT:
		puts("Sleep for this number of seconds\n");
		break;
	    }
	}
    }
}
コード例 #12
0
ファイル: gl_role.c プロジェクト: Arc0re/acehack
/**
   Runs before player selection, and is used to determine which game
   mode to play in. If the choice is to continue or start a new game, it
   sets the character name to determine which (currently unused name for
   the player = new game, currently used name = continue that game);
   otherwise, it implements the choice itself then either loops or
   exits.

   This is based on the tty code, except that it uses a menu rather
   than rendering the game mode selection by hand.
*/
void
Sdlgl_game_mode_selection()
{
  int c;
  char** saved;
  char** sp;
  int plname_in_saved = 0;
  int plname_was_explicit = !!*plname;
  (void) plname_was_explicit; /* TODO: use this */

  winid menuwin;
  int n;
  menu_item *selected;
  anything any;

  saved = get_saved_games();

  if (*plname && saved && *saved) {
    for (sp = saved; *sp; sp++) {
      /* Note that this means that public servers need to prevent two
         users with the same name but different capitalisation. (If
         they aren't, it's likely to cause problems anyway...) */
      if (!strcmpi(plname, *sp)) {
        plname_in_saved = 1;
        /* Fix capitalisation of the name to match the saved game. */
        strncpy(plname, *sp, sizeof(plname)-1);
      }
    }
  } else if (*plname) {
    set_savefile_name();
    /* Let's just try to open the savefile directly to see if it exists */
    plname_in_saved = verify_savefile();
  }

retry_mode_selection:;
reread_char:
  menuwin = create_nhwindow(NHW_MENU);
  any.a_void = 0;
  start_menu(menuwin);

  any.a_int = 'c';
  add_menu(menuwin, NO_GLYPH, &any, 'c', 0, ATR_NONE,
           "Continue game", MENU_UNSELECTED);
  any.a_int = 'n';
  add_menu(menuwin, NO_GLYPH, &any, 'n', 0, ATR_NONE,
           "New game", MENU_UNSELECTED);
  any.a_int = 't';
  add_menu(menuwin, NO_GLYPH, &any, 't', 0, ATR_NONE,
           "Tutorial", MENU_UNSELECTED);
  any.a_int = 'm';
  add_menu(menuwin, NO_GLYPH, &any, 'm', 0, ATR_NONE,
           "Other modes", MENU_UNSELECTED);

  any.a_void = 0;
  add_menu(menuwin, NO_GLYPH, &any, 0, 0, ATR_NONE, "", FALSE);

  any.a_int = 's';
  add_menu(menuwin, NO_GLYPH, &any, 's', 0, ATR_NONE,
           "Continue game", MENU_UNSELECTED);
  any.a_int = 'o';
  add_menu(menuwin, NO_GLYPH, &any, 'o', 0, ATR_NONE,
           "New game", MENU_UNSELECTED);
  any.a_int = '?';
  add_menu(menuwin, NO_GLYPH, &any, '?', 0, ATR_NONE,
           "Tutorial", MENU_UNSELECTED);
  any.a_int = 'q';
  add_menu(menuwin, NO_GLYPH, &any, 'q', 0, ATR_NONE,
           "Other modes", MENU_UNSELECTED);

  end_menu(menuwin, "Welcome to AceHack!");
  n = select_menu(menuwin, PICK_ONE, &selected);
  destroy_nhwindow(menuwin);

  if (n > 0) {
    c = selected[0].item.a_int;
    free((genericptr_t)selected);
  } else goto retry_mode_selection;

#if 0
  /* TODO: This is tty code for graying out unavailable options;
     we should do that in SDL/GL code too */
  {
    if (c == 1) { /* gray out if there's no game to continue */
      if (!*plname && (!saved || !*saved)) xputs("\033[31m");
      else if (*plname && !plname_in_saved) xputs("\033[31m");
      /* and bold if there is */
      else xputs("\033[1m");
    }
    else if (c == 2) { /* gray out if a game must be continued */
      if (*plname && plname_in_saved) xputs("\033[31m");
    }
    else xputc(c); /* low-level as codes are in the file itself */
  }
#endif

  switch (c) {
  case 'c': /* continue game */
    if (*plname && plname_in_saved) break; /* just load by name */
    if (!saved || !*saved) goto reread_char;
    if (*plname && !plname_in_saved) goto reread_char;
    if (!saved[1]) {
      /* only one game to continue */
      (void) strncpy(plname, *saved, sizeof(plname)-1);
    } else {
      /* we'll have to ask which game to continue */
      winid win;
      win = create_nhwindow(NHW_MENU);
      start_menu(win);
      any.a_void = 0;
      for (sp = saved; *sp; sp++) {
        any.a_void = (void*) *sp;
        add_menu(win, NO_GLYPH, &any, 0, 0, ATR_NONE, *sp, MENU_UNSELECTED);
      }
      end_menu(win, "Continue which saved game?");
      c = select_menu(win, PICK_ONE, &selected);
      destroy_nhwindow(win);
      if (c != 1) {
        free((genericptr_t) selected);
        goto retry_mode_selection;
      }
      (void) strncpy(plname, (char*)selected[0].item.a_void, sizeof(plname)-1);
      free((genericptr_t) selected);
    }
    break;
  case 'n': case 't': case 'm': /* the new game options */
    /* if the name is forced by the -u option, don't give an option to
       start a new game, as we're forced onto the existing game */
    if (*plname && plname_in_saved) goto reread_char;
    if (!*plname) {
      Sdlgl_askname();
      if (saved)
        for (sp = saved; *sp; sp++) {
          if (!strcmpi(plname, *sp)) {
            pline("A game is running with that name already.");
            Sdlgl_dismiss_nhwindow(NHW_MESSAGE); /* force a --More-- */
            *plname = 0;
            goto retry_mode_selection;
          }
        }
    }
    if (c == 'm') {
      pline("TODO: implement game mode selection here");
      goto retry_mode_selection;
      do {
        c = 0; /* read from keyboard */
        switch(c) {
          /* -D, -X on command line are overriden by selecting a normal game
             explicitly */
        case 'n': wizard = FALSE; discover = FALSE; break;
        case 't': break;
        case 'd':
#ifdef WIZARD
          /* The rules here are a little complex:
             - with no -u (local play, private server play), anyone
               can enter debug mode;
             - with -u set (generally public server play), only an
               authorized user can enter debug mode.
             Thus people can enter it freely in their own compiles,
             but on public servers likely only the admin can enter it,
             as only they can tweak the command line. (-D works too
             to enter wizmode, whatever the -u option, as if it's
             given the player has control over the command line anyway.) */
          if (plname_was_explicit && strcmpi(plname,WIZARD)) {
            extern int wiz_error_flag; /* from unixmain.c */
            wiz_error_flag = TRUE;
          } else {
            wizard = TRUE;
            c = 'n';
            break;
          }
          /*FALLTHRU*/
#endif /* otherwise fall through, as debug mode isn't compiled in */
        case 'x': discover = TRUE; c = 'n'; break;
        case 's': solo = TRUE; c = 'n'; break;
        case '\033': goto retry_mode_selection;
        default: continue;
        }
      } while (c != 'n' && c != 't');
    }
    if (c == 't') flags.tutorial = 1;
    break;
  case 's': /* show high score list */
    prscore_interactive();
    goto retry_mode_selection;
  case 'o': /* options */
    doset();
    goto retry_mode_selection;
  case '?': /* help */
    dohelp();
    Sdlgl_dismiss_nhwindow(NHW_MESSAGE); /* force a --More-- */
    goto retry_mode_selection;
  case 'q': case '\033': /* exit */
    /* This is the standard Sdlgl method of exiting. */
    Sdlgl_exit_nhwindows(0);
    terminate(EXIT_SUCCESS);
    /*NOTREACHED*/
  default:
    goto reread_char;
  }

  if (saved) free_saved_games(saved);
}
コード例 #13
0
int main( int argc, char **argv ) {
    extern const char *source_modtime_str, *source_version_str;
    const char *load_prefs = getenv("FONTFORGE_LOADPREFS");
    int i;
    extern int splash;
    int recover=1;
    GtkWidget *notices, *ffsplash;
    gchar *home_dir, *rc_path;
    struct argcontext args;

#ifdef FONTFORGE_CONFIG_TYPE3
    fprintf( stderr, "Copyright (c) 2000-2012 by George Williams.\n Executable based on sources from %s-ML.\n",
	    source_modtime_str );
#else
    fprintf( stderr, "Copyright (c) 2000-2012 by George Williams.\n Executable based on sources from %s.\n",
	    source_modtime_str );
#endif
    fprintf( stderr, " Library based on sources from %s.\n", library_version_configuration.library_source_modtime_string );

    gtk_set_locale ();

    home_dir = (gchar*) g_get_home_dir();
    rc_path = g_strdup_printf("%s/.fontforgerc", home_dir);
    gtk_rc_add_default_file(rc_path);
    g_free(rc_path);

    gtk_init (&argc, &argv);

#if defined(SHAREDIR)
    add_pixmap_directory( SHAREDIR "/pixmaps");
#elif defined(PREFIX)
    add_pixmap_directory( PREFIX "/share/fontforge/pixmaps" );
#else
    add_pixmap_directory( "./pixmaps" );
#endif

    bind_textdomain_codeset("FontForge","UTF-8");
    bindtextdomain("FontForge", getLocaleDir());
    textdomain("FontForge");

#if defined(__Mac)
    /* Start X if they haven't already done so. Well... try anyway */
    /* Must be before we change DYLD_LIBRARY_PATH or X won't start */
    if ( uses_local_x(argc,argv) && getenv("DISPLAY")==NULL ) {
	system( "open /Applications/Utilities/X11.app/" );
	setenv("DISPLAY",":0.0",0);
    }
#endif

    FF_SetUiInterface(&gtk_ui_interface);
    FF_SetPrefsInterface(&gtk_prefs_interface);
    /*FF_SetSCInterface(&gtk_sc_interface);*/
    /*FF_SetCVInterface(&gtk_cv_interface);*/
    /*FF_SetBCInterface(&gtk_bc_interface);*/
    FF_SetFVInterface(&gtk_fv_interface);
    /*FF_SetFIInterface(&gtk_fi_interface);*/
    /*FF_SetMVInterface(&gtk_mv_interface);*/
    /*FF_SetClipInterface(&gtk_clip_interface);*/
#ifndef _NO_PYTHON
    PythonUI_Init();
#endif

    InitSimpleStuff();
    if ( load_prefs!=NULL && strcasecmp(load_prefs,"Always")==0 )
	LoadPrefs();
    if ( default_encoding==NULL )
	default_encoding=FindOrMakeEncoding("ISO8859-1");
    if ( default_encoding==NULL )
	default_encoding=&custom;	/* In case iconv is broken */
    CheckIsScript(argc,argv);		/* Will run the script and exit if it is a script */
					/* If there is no UI, there is always a script */
			                /*  and we will never return from the above */
    if ( load_prefs==NULL ||
	    (strcasecmp(load_prefs,"Always")!=0 &&	/* Already loaded */
	     strcasecmp(load_prefs,"Never")!=0 ))
	LoadPrefs();
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];
	if ( pt[0]=='-' && pt[1]=='-' )
	    ++pt;

	if ( strcmp(pt,"-nosplash")==0 )
	    splash = 0;
	else if ( strcmp(pt,"-recover")==0 && i<argc-1 ) {
	    ++i;
	    if ( strcmp(argv[i],"none")==0 )
		recover=0;
	    else if ( strcmp(argv[i],"clean")==0 )
		recover= -1;
	    else if ( strcmp(argv[i],"auto")==0 )
		recover= 1;
	    else if ( strcmp(argv[i],"inquire")==0 )
		recover= 2;
	    else {
		fprintf( stderr, "Invalid argument to -recover, must be none, auto, inquire or clean\n" );
		dousage();
	    }
	} else if ( strcmp(pt,"-recover=none")==0 ) {
	    recover = 0;
	} else if ( strcmp(pt,"-recover=clean")==0 ) {
	    recover = -1;
	} else if ( strcmp(pt,"-recover=auto")==0 ) {
	    recover = 1;
	} else if ( strcmp(pt,"-recover=inquire")==0 ) {
	    recover = 2;
	} else if ( strcmp(pt,"-help")==0 )
	    dohelp();
	else if ( strcmp(pt,"-usage")==0 )
	    dousage();
	else if ( strcmp(pt,"-version")==0 )
	    doversion(source_version_str);
	else if ( strcmp(pt,"-library-status")==0 )
	    dolibrary();
    }

    InitCursors();
#ifndef _NO_PYTHON
    PyFF_ProcessInitFiles();
#endif

    if ( splash ) {
	splashw = create_FontForgeSplash ();
	splash_window_tooltip_fun( splashw );
	notices = lookup_widget(splashw,"Notices");
	if ( notices!=NULL )
	    gtk_widget_hide(notices);
	ffsplash = lookup_widget(splashw,"ffsplash2");
	if ( ffsplash!=NULL )
	    gtk_widget_hide(ffsplash);
	ffsplash = lookup_widget(splashw,"ffsplash3");
	if ( ffsplash!=NULL )
	    gtk_widget_hide(ffsplash);
	gtk_window_set_position(GTK_WINDOW(splashw),GTK_WIN_POS_CENTER_ALWAYS);
	gtk_widget_show (splashw);
	ff_progress_allow_events();
	gtk_timeout_add(1000,Splash_Changes,splashw);
    }

    gtk_timeout_add(30*1000,__DoAutoSaves,NULL);		/* Check for autosave every 30 seconds */

    args.argc = argc; args.argv = argv; args.recover = recover;
    gtk_timeout_add(100,ParseArgs,&args);
	/* Parse arguments within the main loop */

    gtk_main ();
return( 0 );
}
コード例 #14
0
ファイル: m_help.c プロジェクト: mdharris/ircd
/*
 * mo_uhelp - HELP message handler
 * This is used so that opers can view the user help file without deopering
 *      parv[0] = sender prefix
 */
static void
mo_uhelp(struct Client *client_p, struct Client *source_p,
            int parc, char *parv[])
{
  dohelp(source_p, UHPATH, parv[1]);
}
コード例 #15
0
ファイル: startui.c プロジェクト: dtanabe/fontforge
int fontforge_main( int argc, char **argv ) {
    extern const char *source_modtime_str;
    extern const char *source_version_str;
    const char *load_prefs = getenv("FONTFORGE_LOADPREFS");
    int i;
    int recover=2;
    int any;
    int next_recent=0;
    GRect pos;
    GWindowAttrs wattrs;
    char *display = NULL;
    FontRequest rq;
    int ds, ld;
    int openflags=0;
    int doopen=0, quit_request=0;
#if defined(__Mac)
    int local_x;
#endif

    fprintf( stderr, "Copyright (c) 2000-2012 by George Williams.\n Executable based on sources from %s"
	    "-ML"
#ifdef FREETYPE_HAS_DEBUGGER
	    "-TtfDb"
#endif
#ifdef _NO_PYTHON
	    "-NoPython"
#endif
#ifdef FONTFORGE_CONFIG_USE_DOUBLE
	    "-D"
#endif
	    ".\n",
	    source_modtime_str );
    fprintf( stderr, " Library based on sources from %s.\n", library_version_configuration.library_source_modtime_string );

    /* Must be done before we cache the current directory */
    /* Change to HOME dir if specified on the commandline */
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];
	if ( pt[0]=='-' && pt[1]=='-' ) ++pt;
#ifndef __Mac
	if (strcmp(pt,"-home")==0) {
#else
	if (strcmp(pt,"-home")==0 || strncmp(pt,"-psn_",5)==0) {
	    /* OK, I don't know what _-psn_ means, but to GW it means */
	    /* we've been started on the mac from the FontForge.app   */
	    /* structure, and the current directory is (shudder) "/"  */
#endif
	    if (getenv("HOME")!=NULL) chdir(getenv("HOME"));
	    break;	/* Done - Unnecessary to check more arguments */
	}
    }
	
#if defined(__Mac)
    /* Start X if they haven't already done so. Well... try anyway */
    /* Must be before we change DYLD_LIBRARY_PATH or X won't start */
    /* (osascript depends on a libjpeg which isn't found if we look in /sw/lib first */
    local_x = uses_local_x(argc,argv);
    if ( local_x==1 && getenv("DISPLAY")==NULL ) {
	/* Don't start X if we're just going to quit. */
	/* if X exists, it isn't needed. If X doesn't exist it's wrong */
	if ( !hasquit(argc,argv)) {
#if 1
	    /* This sequence is supposed to bring up an app without a window */
	    /*  but X still opens an xterm */
	    system( "osascript -e 'tell application \"X11\" to launch'" );
	    system( "osascript -e 'tell application \"X11\" to activate'" );
#else
	    system( "open /Applications/Utilities/X11.app/" );
#endif
	}
	setenv("DISPLAY",":0.0",0);
    } else if ( local_x==1 && *getenv("DISPLAY")!='/' && strcmp(getenv("DISPLAY"),":0.0")!=0 && strcmp(getenv("DISPLAY"),":0")!=0 )
	/* 10.5.7 uses a named socket or something "/tmp/launch-01ftWX:0" */
	local_x = 0;
#endif

#if defined(__MINGW32__)
    if( getenv("DISPLAY")==NULL ) {
	putenv("DISPLAY=127.0.0.1:0.0");
    }
    if( getenv("LC_ALL")==NULL ){
	char lang[8];
	char env[32];
	if( GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, 8) > 0 ){
	    strcpy(env, "LC_ALL=");
	    strcat(env, lang);
	    putenv(env);
	}
    }
#endif

    FF_SetUiInterface(&gdraw_ui_interface);
    FF_SetPrefsInterface(&gdraw_prefs_interface);
    FF_SetSCInterface(&gdraw_sc_interface);
    FF_SetCVInterface(&gdraw_cv_interface);
    FF_SetBCInterface(&gdraw_bc_interface);
    FF_SetFVInterface(&gdraw_fv_interface);
    FF_SetFIInterface(&gdraw_fi_interface);
    FF_SetMVInterface(&gdraw_mv_interface);
    FF_SetClipInterface(&gdraw_clip_interface);
#ifndef _NO_PYTHON
    PythonUI_Init();
#endif

    InitSimpleStuff();
    FindProgDir(argv[0]);

#if defined(__MINGW32__)
    {
	char  path[MAX_PATH+4];
	char  *c = path;
	unsigned int  len = GetModuleFileNameA(NULL, path, MAX_PATH);
	path[len] = '\0';
	for(; *c; *c++) /* backslash to slash */
	    if(*c == '\\')
		*c = '/';
	GResourceSetProg(path);
    }
#else
    GResourceSetProg(argv[0]);
#endif

#if defined(__Mac)
    /* The mac seems to default to the "C" locale, LANG and LC_MESSAGES are not*/
    /*  defined. This means that gettext will not bother to look up any message*/
    /*  files -- even if we have a "C" or "POSIX" entry in the locale diretory */
    /* Now if X11 gives us the command key, I want to force a rebinding to use */
    /*  Cmd rather than Control key -- more mac-like. But I can't do that if   */
    /*  there is no locale. So I force a locale if there is none specified */
    /* I force the US English locale, because that's the what the messages are */
    /*  by default so I'm changing as little as I can. I think. */
    /* Now the locale command will treat a LANG which is "" as undefined, but */
    /*  gettext will not. So I don't bother to check for null strings or "C"  */
    /*  or "POSIX". If they've mucked with the locale perhaps they know what  */
    /*  they are doing */
    { int did_keybindings = 0;
    if ( local_x && !get_mac_x11_prop("enable_key_equivalents") ) {
	/* Ok, we get the command key */
	if ( getenv("LANG")==NULL && getenv("LC_MESSAGES")==NULL ) {
	    setenv("LC_MESSAGES","en_US.UTF-8",0);
	}
	/* Can we find a set of keybindings designed for the mac with cmd key? */
	bind_textdomain_codeset("Mac-FontForge-MenuShortCuts","UTF-8");
	bindtextdomain("Mac-FontForge-MenuShortCuts", getLocaleDir());
	if ( *dgettext("Mac-FontForge-MenuShortCuts","Flag0x10+")!='F' ) {
	    GMenuSetShortcutDomain("Mac-FontForge-MenuShortCuts");
	    did_keybindings = 1;
	}
    }
    if ( !did_keybindings ) {
	/* Nope. we can't. Fall back to the normal stuff */
#endif
    GMenuSetShortcutDomain("FontForge-MenuShortCuts");
    bind_textdomain_codeset("FontForge-MenuShortCuts","UTF-8");
    bindtextdomain("FontForge-MenuShortCuts", getLocaleDir());
#if defined(__Mac)
    }}
#endif
    bind_textdomain_codeset("FontForge","UTF-8");
    bindtextdomain("FontForge", getLocaleDir());
    textdomain("FontForge");
    GResourceUseGetText();
#if defined(__MINGW32__)
    {
	size_t len = strlen(GResourceProgramDir);
	char*  path = galloc(len + 64);
	strcpy(path, GResourceProgramDir);

	strcpy(path+len, "/share/fontforge/pixmaps"); /* PixmapDir */
	GGadgetSetImageDir(path);

	strcpy(path+len, "/share/fontforge/resources/fontforge.resource"); /* Resource File */
	GResourceAddResourceFile(path, GResourceProgramName, false);

	gfree(path);
    }
#elif defined(SHAREDIR)
    GGadgetSetImageDir(SHAREDIR "/pixmaps");
    GResourceAddResourceFile(SHAREDIR "/resources/fontforge.resource",GResourceProgramName,false);
#endif
    hotkeysLoad();


    if ( load_prefs!=NULL && strcasecmp(load_prefs,"Always")==0 )
	LoadPrefs();
    if ( default_encoding==NULL )
	default_encoding=FindOrMakeEncoding("ISO8859-1");
    if ( default_encoding==NULL )
	default_encoding=&custom;	/* In case iconv is broken */
    CheckIsScript(argc,argv); /* Will run the script and exit if it is a script */
					/* If there is no UI, there is always a script */
			                /*  and we will never return from the above */
    if ( load_prefs==NULL ||
	    (strcasecmp(load_prefs,"Always")!=0 &&	/* Already loaded */
	     strcasecmp(load_prefs,"Never")!=0 ))
	LoadPrefs();
    GrokNavigationMask();
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];
	if ( pt[0]=='-' && pt[1]=='-' )
	    ++pt;
	if ( strcmp(pt,"-sync")==0 )
	    GResourceAddResourceString("Gdraw.Synchronize: true",argv[0]);
	else if ( strcmp(pt,"-depth")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.Depth", argv[++i]);
	else if ( strcmp(pt,"-vc")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.VisualClass", argv[++i]);
	else if ( (strcmp(pt,"-cmap")==0 || strcmp(pt,"-colormap")==0) && i<argc-1 )
	    AddR(argv[0],"Gdraw.Colormap", argv[++i]);
	else if ( (strcmp(pt,"-dontopenxdevices")==0) )
	    AddR(argv[0],"Gdraw.DontOpenXDevices", "true");
	else if ( strcmp(pt,"-keyboard")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.Keyboard", argv[++i]);
	else if ( strcmp(pt,"-display")==0 && i<argc-1 )
	    display = argv[++i];
# if MyMemory
	else if ( strcmp(pt,"-memory")==0 )
	    __malloc_debug(5);
# endif
	else if ( strncmp(pt,"-usecairo",strlen("-usecairo"))==0 ) {
	    if ( strcmp(pt,"-usecairo=no")==0 )
		GDrawEnableCairo(false);
	    else
		GDrawEnableCairo(true);
	} else if ( strcmp(pt,"-nosplash")==0 )
	    splash = 0;
	else if ( strcmp(pt,"-unique")==0 )
	    unique = 1;
	else if ( strcmp(pt,"-recover")==0 && i<argc-1 ) {
	    ++i;
	    if ( strcmp(argv[i],"none")==0 )
		recover=0;
	    else if ( strcmp(argv[i],"clean")==0 )
		recover= -1;
	    else if ( strcmp(argv[i],"auto")==0 )
		recover= 1;
	    else if ( strcmp(argv[i],"inquire")==0 )
		recover= 2;
	    else {
		fprintf( stderr, "Invalid argument to -recover, must be none, auto, inquire or clean\n" );
		dousage();
	    }
	} else if ( strcmp(pt,"-recover=none")==0 ) {
	    recover = 0;
	} else if ( strcmp(pt,"-recover=clean")==0 ) {
	    recover = -1;
	} else if ( strcmp(pt,"-recover=auto")==0 ) {
	    recover = 1;
	} else if ( strcmp(pt,"-recover=inquire")==0 ) {
	    recover = 2;
	} else if ( strcmp(pt,"-docs")==0 )
	    dohelp();
	else if ( strcmp(pt,"-help")==0 )
	    dousage();
	else if ( strcmp(pt,"-version")==0 )
	    doversion(source_version_str);
	else if ( strcmp(pt,"-quit")==0 )
	    quit_request = true;
	else if ( strcmp(pt,"-home")==0 )
	    /* already did a chdir earlier, don't need to do it again */;
#if defined(__Mac)
	else if ( strncmp(pt,"-psn_",5)==0 ) {
	    /* OK, I don't know what _-psn_ means, but to GW it means */
	    /* we've been started on the mac from the FontForge.app   */
	    /* structure, and the current directory was (shudder) "/" */
	    /* (however, we changed to HOME earlier in main routine). */
	    unique = 1;
	    listen_to_apple_events = true;
	}
#endif
    }

    ensureDotFontForgeIsSetup();
    GDrawCreateDisplays(display,argv[0]);
    default_background = GDrawGetDefaultBackground(screen_display);
    InitToolIconClut(default_background);
    InitToolIcons();
    InitCursors();
#ifndef _NO_PYTHON
    PyFF_ProcessInitFiles();
#endif

    /* Wait until the UI has started, otherwise people who don't have consoles*/
    /*  open won't get our error messages, and it's an important one */
    /* Scripting doesn't care about a mismatch, because scripting interpretation */
    /*  all lives in the library */
    check_library_version(&exe_library_version_configuration,true,false);

    /* the splash screen used not to have a title bar (wam_nodecor) */
    /*  but I found I needed to know how much the window manager moved */
    /*  the window around, which I can determine if I have a positioned */
    /*  decorated window created at the begining */
    /* Actually I don't care any more */
    wattrs.mask = wam_events|wam_cursor|wam_bordwidth|wam_backcol|wam_positioned|wam_utf8_wtitle|wam_isdlg;
    wattrs.event_masks = ~(1<<et_charup);
    wattrs.positioned = 1;
    wattrs.cursor = ct_pointer;
    wattrs.utf8_window_title = "FontForge";
    wattrs.border_width = 2;
    wattrs.background_color = 0xffffff;
    wattrs.is_dlg = !listen_to_apple_events;
    pos.x = pos.y = 200;
    pos.width = splashimage.u.image->width;
    pos.height = splashimage.u.image->height-56;		/* 54 */
    GDrawBindSelection(NULL,sn_user1,"FontForge");
    if ( unique && GDrawSelectionOwned(NULL,sn_user1)) {
	/* Different event handler, not a dialog */
	wattrs.is_dlg = false;
	splashw = GDrawCreateTopWindow(NULL,&pos,request_e_h,NULL,&wattrs);
	PingOtherFontForge(argc,argv);
    } else {
	if ( quit_request )
exit( 0 );
	splashw = GDrawCreateTopWindow(NULL,&pos,splash_e_h,NULL,&wattrs);
    }

    memset(&rq,0,sizeof(rq));
    rq.utf8_family_name = SERIF_UI_FAMILIES;
    rq.point_size = 12;
    rq.weight = 400;
    splash_font = GDrawInstanciateFont(NULL,&rq);
    splash_font = GResourceFindFont("Splash.Font",splash_font);
    GDrawDecomposeFont(splash_font, &rq);
    rq.style = fs_italic;
    splash_italic = GDrawInstanciateFont(NULL,&rq);
    splash_italic = GResourceFindFont("Splash.ItalicFont",splash_italic);
    GDrawSetFont(splashw,splash_font);
    GDrawWindowFontMetrics(splashw,splash_font,&as,&ds,&ld);
    fh = as+ds+ld;
    SplashLayout();
    localsplash = splash;

    if ( localsplash && !listen_to_apple_events )
	start_splash_screen();

    if ( AutoSaveFrequency>0 )
	autosave_timer=GDrawRequestTimer(splashw,2*AutoSaveFrequency*1000,AutoSaveFrequency*1000,NULL);

    GDrawProcessPendingEvents(NULL);
    GDrawSetBuildCharHooks(BuildCharHook,InsCharHook);

    any = 0;
    if ( recover==-1 )
	CleanAutoRecovery();
    else if ( recover )
	any = DoAutoRecovery(recover-1);

    openflags = 0;
    for ( i=1; i<argc; ++i ) {
	char buffer[1025];
	char *pt = argv[i];

	GDrawProcessPendingEvents(NULL);
	if ( pt[0]=='-' && pt[1]=='-' )
	    ++pt;
	if ( strcmp(pt,"-new")==0 ) {
	    FontNew();
	    any = 1;
#  if HANYANG
	} else if ( strcmp(pt,"-newkorean")==0 ) {
	    MenuNewComposition(NULL,NULL,NULL);
	    any = 1;
#  endif
	} else if ( strcmp(pt,"-last")==0 ) {
	    if ( next_recent<RECENT_MAX && RecentFiles[next_recent]!=NULL )
		if ( ViewPostScriptFont(RecentFiles[next_recent++],openflags))
		    any = 1;
	} else if ( strcmp(pt,"-sync")==0 || strcmp(pt,"-memory")==0 ||
		strcmp(pt,"-nosplash")==0 || strcmp(pt,"-recover=none")==0 ||
		strcmp(pt,"-recover=clean")==0 || strcmp(pt,"-recover=auto")==0 ||
		strcmp(pt,"-dontopenxdevices")==0 || strcmp(pt,"-unique")==0 ||
		strncmp(pt,"-usecairo",strlen("-usecairo"))==0 ||
		strcmp(pt,"-home")==0 )
	    /* Already done, needed to be before display opened */;
	else if ( strncmp(pt,"-psn_",5)==0 )
	    /* Already done */;
	else if ( (strcmp(pt,"-depth")==0 || strcmp(pt,"-vc")==0 ||
		    strcmp(pt,"-cmap")==0 || strcmp(pt,"-colormap")==0 || 
		    strcmp(pt,"-keyboard")==0 || 
		    strcmp(pt,"-display")==0 || strcmp(pt,"-recover")==0 ) &&
		i<argc-1 )
	    ++i; /* Already done, needed to be before display opened */
	else if ( strcmp(pt,"-allglyphs")==0 )
	    openflags |= of_all_glyphs_in_ttc;
	else if ( strcmp(pt,"-open")==0 )
	    doopen = true;
	else {
	    if ( strstr(argv[i],"://")!=NULL ) {		/* Assume an absolute URL */
		strncpy(buffer,argv[i],sizeof(buffer));
		buffer[sizeof(buffer)-1]= '\0';
	    } else
		GFileGetAbsoluteName(argv[i],buffer,sizeof(buffer));
	    if ( GFileIsDir(buffer) || (strstr(buffer,"://")!=NULL && buffer[strlen(buffer)-1]=='/')) {
		char *fname;
		fname = galloc(strlen(buffer)+strlen("/glyphs/contents.plist")+1);
		strcpy(fname,buffer); strcat(fname,"/glyphs/contents.plist");
		if ( GFileExists(fname)) {
		    /* It's probably a Unified Font Object directory */
		    free(fname);
		    if ( ViewPostScriptFont(buffer,openflags) )
			any = 1;
		} else {
		    strcpy(fname,buffer); strcat(fname,"/font.props");
		    if ( GFileExists(fname)) {
			/* It's probably a sf dir collection */
			free(fname);
			if ( ViewPostScriptFont(buffer,openflags) )
			    any = 1;
		    } else {
			free(fname);
			if ( buffer[strlen(buffer)-1]!='/' ) {
			    /* If dirname doesn't end in "/" we'll be looking in parent dir */
			    buffer[strlen(buffer)+1]='\0';
			    buffer[strlen(buffer)] = '/';
			}
			fname = GetPostScriptFontName(buffer,false);
			if ( fname!=NULL )
			    ViewPostScriptFont(fname,openflags);
			any = 1;	/* Even if we didn't get a font, don't bring up dlg again */
			free(fname);
		    }
		}
	    } else if ( ViewPostScriptFont(buffer,openflags)!=0 )
		any = 1;
	}
    }
    if ( !any && !doopen )
	any = ReopenLastFonts();
#if defined(__Mac)
    if ( listen_to_apple_events ) {
	install_apple_event_handlers();
	install_mac_timer();
	RunApplicationEventLoop();
    } else
#endif
    if ( doopen || !any )
	MenuOpen(NULL,NULL,NULL);
    GDrawEventLoop(NULL);

    hotkeysSave();
    
    uninm_names_db_close(names_db);
    lt_dlexit();

return( 0 );
}
コード例 #16
0
ファイル: oldfiles.c プロジェクト: rlp1938/oldfiles
time_t parsetimestring(const char *timestr)
{
   /*
    * check the string in dts for valid values
    * and return the time if all ok;
   */
   char dts[16];
   struct tm dt;

   // seconds will never be set here, also minutes & hours may not be.
   dt.tm_sec = 0;
   dt.tm_min = 0;
   dt.tm_hour = 0;
   dt.tm_wday = 0;
   dt.tm_yday = 0;

   strcpy(dts, timestr);
   switch(strlen(dts)) {
        case 12:
            dt.tm_min = atoi(&dts[10]);
            if ((dt.tm_min < 0 ) || (dt.tm_min > 59)) {
                fprintf(stderr, "Illegal value for minutes: %d\n",
                        dt.tm_min);
                dohelp(1);
            }
            dts[10] = '\0';
        case 10:
            dt.tm_hour = atoi(&dts[8]);
            if ((dt.tm_hour < 0 ) || (dt.tm_hour > 23)) {
                fprintf(stderr, "Illegal value for hours: %d\n",
                        dt.tm_hour);
                dohelp(1);
            }
            dts[8] = '\0';
        case 8:
            dt.tm_mday = atoi(&dts[6]);
            if ((dt.tm_mday < 1 ) || (dt.tm_mday > 31)) { // rough enough for now
                fprintf(stderr, "Illegal value for days: %d\n",
                        dt.tm_mday);
                dohelp(1);
            }
            dts[6] = '\0';
            dt.tm_mon = atoi(&dts[4]) - 1;
            if ((dt.tm_mon < 0 ) || (dt.tm_mon > 11)) {
                fprintf(stderr, "Illegal value for months: %d\n",
                        dt.tm_mon+1);
                dohelp(1);
            }
            dts[4] = '\0';

            dt.tm_year = atoi(dts) - 1900;
        break;
        default:
        fprintf(stderr, "%s is not formatted correctly\n", dts);
        dohelp(1);
        break;
        // now test if our days are valid for the month
    } // switch()


    if (!(validday(dt.tm_year+1900, dt.tm_mon+1, dt.tm_mday))) {
        fprintf(stderr, "For the year %d, month %d, %d"
                        " days is invalid\n",
                        dt.tm_year+1900, dt.tm_mon+1, dt.tm_mday);
        exit(EXIT_FAILURE);
    }
    return mktime(&dt);
} // parsetimestring()
コード例 #17
0
ファイル: mrtg-pnsclient.c プロジェクト: sshipway/routers2
/*
######################################################################
# defaults
*/
int main(int argc, char **argv) {
int c;
int n;
int hasoffset = 0;

port = PORT;
strncpy(pass,DEFPASS,sizeof(pass));
host[0] = '\0';
resp[0] = resp[1] = 0;
unknown[0] = unknown[1] = 1;
strncpy(mesg,"Data retrieved OK",sizeof(mesg));

/* process arguments */
static struct option options[] = {
	{ "host", 1, 0, 'H' },
	{ "port", 1, 0, 'p' },
	{ "offset", 1, 0, 'o' },
	{ "module", 1, 0, 'c' },
	{ "command", 1, 0, 'c' },
	{ "cmd", 1, 0, 'c' },
	{ "arg", 1, 0, 'a' },
	{ "debug", 0, 0, 'd' },
	{ "timeout", 1, 0, 't' },
	{ "ratio", 0, 0, 'r' },
	{ "password", 1, 0, 'P' },
	{ "compat", 0, 0, 'C' }
};
while(1) {
	c = getopt_long(argc,argv,"CP:H:s:p:o:n:c:v:l:a:dt:rh",options,NULL);
	if(c == -1) break;
	switch(c) {
		case 'H':
		case 's':
			strncpy(host,optarg,sizeof(host)-1); break;
		case 'p':
			port = atoi(optarg); break;
		case 'P':
			strncpy(pass,optarg,sizeof(pass)-1); break;
		case 'o': /* offset */
		case 'n':
			n = 0; if(hasoffset || (cmd[1]>-1) || arg[1]) { n = 1; }
			offset[n] = atoi(optarg);
			hasoffset = 1;
			break;
		case 'c': /* command */
		case 'v':
			n = 0; if(cmd[n]>-1) { n = 1; }
			if(cmd[n]>-1) {
				sprintf(mesg,"You may only specify two commands.");
				outputresp();
				exit(1);
			}
			cmd[n] = getcmd(optarg);
			if(cmd[n]<0) {
				sprintf(mesg,"Invalid command [%s]",optarg);
				outputresp();
				exit(1);
			}
			break;
		case 'l': /* arg */
		case 'a':
			n = 0; if((cmd[1]>-1) || arg[0]) { n = 1; }
			arg[n] = optarg;
			break;
		case 'd':
			debugmode = 1; break;
		case 't':
			timeout = atoi(optarg);
			if(timeout < 1) { timeout = TIMEOUT; }	
			break;
		case 'r':
			ratiomode = 1; break;
		case 'h':
			dohelp(); exit(1);
		case 'C':
			compatmode = 1; break;
		default:
			sprintf(mesg,"Option was not recognised..."); 
			outputresp();
			exit(1);
	} /* switch */
} /* while loop */

if( !port || !host[0] ) {
	sprintf(mesg,"Must specify a valid port and hostname");
	outputresp();
	exit( 1 );
}

/* we need to run a second command only if the args have changed */
if((cmd[1]<0) && !arg[1] && !offset[1]) { offset[1]=1; } /* ? */
if((cmd[1]<0) && arg[1]) { cmd[1] = cmd[0]; }

if(cmd[0]<0) {
	sprintf(mesg,"No command was given.");
	outputresp(); exit(1);
}
/*
# Now we have one or two command to pass to the agent.
# We connect, and send, then listen for the response.
# Repeat for second argument if necessary
*/
#ifdef WITHALARM
/* timeout for program */
signal(SIGALRM,handler);
if(debugmode) { printf("Starting alarm for %d sec\n",timeout); fflush(NULL); }
alarm(timeout);
#endif

/* first, identify remote agent if necessary */
if((cmd[0]==8)||(cmd[1]==8)) {
    if(debugmode) { printf("Testing version\n"); fflush(NULL); }
    makesocket();
    verstr = (char *)malloc(256);
    n = ask(1,(char *)0,(double *)0,0,0,0,verstr);
    close(sock);
    if(! strcasestr(verstr,"nsclient++") ) {
    	if(debugmode) { printf("Setting compat mode\n"); fflush(NULL); }
	compatmode = 1;
    }
}

/* Connect */
if(debugmode) { printf("Starting queries\n"); fflush(NULL); }
makesocket();
n = ask(cmd[0],arg[0],&resp[0],offset[0],ratiomode,0,NULL);
close(sock);
if(n) { outputresp(); exit(0); }
else { unknown[0] = 0; }
if(cmd[1]>-1) {
	makesocket();
	n = ask(cmd[1],arg[1],&resp[1],offset[1],ratiomode,0,NULL);
	close(sock);
	if(n) { outputresp(); exit(0); }
	else { unknown[1] = 0; }
} else {
	makesocket();
	n = ask(-1,(char *)NULL,&resp[1],offset[1],ratiomode,1,NULL);
	close(sock);
	if(!n) { unknown[1] = 0; }
}
#ifdef WITHALARM
alarm(0);
#endif

sprintf(mesg,"Nagios query agent version %s",VERSION);

outputresp();
exit(0);
}
コード例 #18
0
ファイル: startui.c プロジェクト: MichinariNukazawa/fontforge
int fontforge_main( int argc, char **argv ) {
    extern const char *source_modtime_str;
    extern const char *source_version_str;
    const char *load_prefs = getenv("FONTFORGE_LOADPREFS");
    int i;
    int recover=2;
    int any;
    int next_recent=0;
    GRect pos;
    GWindowAttrs wattrs;
    char *display = NULL;
    FontRequest rq;
    int ds, ld;
    int openflags=0;
    int doopen=0, quit_request=0;
    bool use_cairo = true;

#if !(GLIB_CHECK_VERSION(2, 35, 0))
    g_type_init();
#endif

    /* Must be done before we cache the current directory */
    /* Change to HOME dir if specified on the commandline */
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];
	if ( pt[0]=='-' && pt[1]=='-' ) ++pt;
	if (strcmp(pt,"-home")==0 || strncmp(pt,"-psn_",5)==0) {
	    /* OK, I don't know what _-psn_ means, but to GW it means */
	    /* we've been started on the mac from the FontForge.app   */
	    /* structure, and the current directory is (shudder) "/"  */
	    if (getenv("HOME")!=NULL) chdir(getenv("HOME"));
	    break;	/* Done - Unnecessary to check more arguments */
	}
	if (strcmp(pt,"-quiet")==0)
	    quiet = 1;
    }

    if (!quiet) {
        fprintf( stderr, "Copyright (c) 2000-2014 by George Williams. See AUTHORS for Contributors.\n" );
        fprintf( stderr, " License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n" );
        fprintf( stderr, " with many parts BSD <http://fontforge.org/license.html>. Please read LICENSE.\n" );
        fprintf( stderr, " Based on sources from %s"
	        "-ML"
#ifdef FREETYPE_HAS_DEBUGGER
	        "-TtfDb"
#endif
#ifdef _NO_PYTHON
	        "-NoPython"
#endif
#ifdef FONTFORGE_CONFIG_USE_DOUBLE
	        "-D"
#endif
	        ".\n",
	        FONTFORGE_MODTIME_STR );
        fprintf( stderr, " Based on source from git with hash: %s\n", FONTFORGE_GIT_VERSION );
    }

#if defined(__Mac)
    /* Start X if they haven't already done so. Well... try anyway */
    /* Must be before we change DYLD_LIBRARY_PATH or X won't start */
    /* (osascript depends on a libjpeg which isn't found if we look in /sw/lib first */
    int local_x = uses_local_x(argc,argv);
    if ( local_x==1 && getenv("DISPLAY")==NULL ) {
	/* Don't start X if we're just going to quit. */
	/* if X exists, it isn't needed. If X doesn't exist it's wrong */
	if ( !hasquit(argc,argv)) {
	    /* This sequence is supposed to bring up an app without a window */
	    /*  but X still opens an xterm */
	    system( "osascript -e 'tell application \"X11\" to launch'" );
	    system( "osascript -e 'tell application \"X11\" to activate'" );
	}
	setenv("DISPLAY",":0.0",0);
    } else if ( local_x==1 && *getenv("DISPLAY")!='/' && strcmp(getenv("DISPLAY"),":0.0")!=0 && strcmp(getenv("DISPLAY"),":0")!=0 )
	/* 10.5.7 uses a named socket or something "/tmp/launch-01ftWX:0" */
	local_x = 0;
#endif

#if defined(__MINGW32__)
    if( getenv("DISPLAY")==NULL ) {
	putenv("DISPLAY=127.0.0.1:0.0");
    }
    if( getenv("LC_ALL")==NULL ){
	char lang[8];
	char env[32];
	if( GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, 8) > 0 ){
	    strcpy(env, "LC_ALL=");
	    strcat(env, lang);
	    putenv(env);
	}
    }
#endif

    FF_SetUiInterface(&gdraw_ui_interface);
    FF_SetPrefsInterface(&gdraw_prefs_interface);
    FF_SetSCInterface(&gdraw_sc_interface);
    FF_SetCVInterface(&gdraw_cv_interface);
    FF_SetBCInterface(&gdraw_bc_interface);
    FF_SetFVInterface(&gdraw_fv_interface);
    FF_SetFIInterface(&gdraw_fi_interface);
    FF_SetMVInterface(&gdraw_mv_interface);
    FF_SetClipInterface(&gdraw_clip_interface);
#ifndef _NO_PYTHON
    PythonUI_Init();
#endif

    FindProgDir(argv[0]);
    InitSimpleStuff();

#if defined(__MINGW32__)
    {
        char path[MAX_PATH];
        unsigned int len = GetModuleFileNameA(NULL, path, MAX_PATH);
        path[len] = '\0';
        
        //The '.exe' must be removed as resources presumes it's not there.
        GResourceSetProg(GFileRemoveExtension(GFileNormalizePath(path)));
    }
#else
    GResourceSetProg(argv[0]);
#endif

#if defined(__Mac)
    /* The mac seems to default to the "C" locale, LANG and LC_MESSAGES are not*/
    /*  defined. This means that gettext will not bother to look up any message*/
    /*  files -- even if we have a "C" or "POSIX" entry in the locale diretory */
    /* Now if X11 gives us the command key, I want to force a rebinding to use */
    /*  Cmd rather than Control key -- more mac-like. But I can't do that if   */
    /*  there is no locale. So I force a locale if there is none specified */
    /* I force the US English locale, because that's the what the messages are */
    /*  by default so I'm changing as little as I can. I think. */
    /* Now the locale command will treat a LANG which is "" as undefined, but */
    /*  gettext will not. So I don't bother to check for null strings or "C"  */
    /*  or "POSIX". If they've mucked with the locale perhaps they know what  */
    /*  they are doing */
    {
	int did_keybindings = 0;
	int useCommandKey = get_mac_x11_prop("enable_key_equivalents") <= 0;

	if ( local_x && useCommandKey ) {
	    hotkeySystemSetCanUseMacCommand( 1 );

	    /* Ok, we get the command key */
	    if ( getenv("LANG")==NULL && getenv("LC_MESSAGES")==NULL ) {
		setenv("LC_MESSAGES","en_US.UTF-8",0);
	    }
	    /* Can we find a set of keybindings designed for the mac with cmd key? */
	    bind_textdomain_codeset("Mac-FontForge-MenuShortCuts","UTF-8");
	    bindtextdomain("Mac-FontForge-MenuShortCuts", getLocaleDir());
	    if ( *dgettext("Mac-FontForge-MenuShortCuts","Flag0x10+")!='F' ) {
		GMenuSetShortcutDomain("Mac-FontForge-MenuShortCuts");
		did_keybindings = 1;
	    }
	}
	if ( !did_keybindings ) {
	    /* Nope. we can't. Fall back to the normal stuff */
#endif
	    GMenuSetShortcutDomain("FontForge-MenuShortCuts");
	    bind_textdomain_codeset("FontForge-MenuShortCuts","UTF-8");
	    bindtextdomain("FontForge-MenuShortCuts", getLocaleDir());
#if defined(__Mac)
	}
    }
#endif
    bind_textdomain_codeset("FontForge","UTF-8");
    bindtextdomain("FontForge", getLocaleDir());
    textdomain("FontForge");
    GResourceUseGetText();
    {
	char shareDir[PATH_MAX];
	char* sd = getShareDir();
	strncpy( shareDir, sd, PATH_MAX );
    shareDir[PATH_MAX-1] = '\0';
	if(!sd) {
	    strcpy( shareDir, SHAREDIR );
	}

	char path[PATH_MAX];
	snprintf(path, PATH_MAX, "%s%s", shareDir, "/pixmaps" );
	GGadgetSetImageDir( path );

	snprintf(path, PATH_MAX, "%s%s", shareDir, "/resources/fontforge.resource" );
	GResourceAddResourceFile(path, GResourceProgramName,false);
    }
    hotkeysLoad();
//    loadPrefsFiles();
    Prefs_LoadDefaultPreferences();

    if ( load_prefs!=NULL && strcasecmp(load_prefs,"Always")==0 )
	LoadPrefs();
    if ( default_encoding==NULL )
	default_encoding=FindOrMakeEncoding("ISO8859-1");
    if ( default_encoding==NULL )
	default_encoding=&custom;	/* In case iconv is broken */

    // This no longer starts embedded Python unless control passes to the Python executors,
    // which exit independently rather than returning here.
    CheckIsScript(argc,argv); /* Will run the script and exit if it is a script */
					/* If there is no UI, there is always a script */
			                /*  and we will never return from the above */
    if ( load_prefs==NULL ||
	    (strcasecmp(load_prefs,"Always")!=0 &&	/* Already loaded */
	     strcasecmp(load_prefs,"Never")!=0 ))
	LoadPrefs();
    GrokNavigationMask();
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];
	if ( pt[0]=='-' && pt[1]=='-' )
	    ++pt;
	if ( strcmp(pt,"-sync")==0 )
	    GResourceAddResourceString("Gdraw.Synchronize: true",argv[0]);
	else if ( strcmp(pt,"-depth")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.Depth", argv[++i]);
	else if ( strcmp(pt,"-vc")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.VisualClass", argv[++i]);
	else if ( (strcmp(pt,"-cmap")==0 || strcmp(pt,"-colormap")==0) && i<argc-1 )
	    AddR(argv[0],"Gdraw.Colormap", argv[++i]);
	else if ( (strcmp(pt,"-dontopenxdevices")==0) )
	    AddR(argv[0],"Gdraw.DontOpenXDevices", "true");
	else if ( strcmp(pt,"-keyboard")==0 && i<argc-1 )
	    AddR(argv[0],"Gdraw.Keyboard", argv[++i]);
	else if ( strcmp(pt,"-display")==0 && i<argc-1 )
	    display = argv[++i];
# if MyMemory
	else if ( strcmp(pt,"-memory")==0 )
	    __malloc_debug(5);
# endif
	else if ( strncmp(pt,"-usecairo",strlen("-usecairo"))==0 ) {
	    if ( strcmp(pt,"-usecairo=no")==0 )
	        use_cairo = false;
	    else
	        use_cairo = true;
	    GDrawEnableCairo(use_cairo);
	} else if ( strcmp(pt,"-nosplash")==0 )
	    splash = 0;
	else if ( strcmp(pt,"-quiet")==0 )
	    /* already checked for this earlier, no need to do it again */;
	else if ( strcmp(pt,"-unique")==0 )
	    unique = 1;
	else if ( strcmp(pt,"-forceuihidden")==0 )
	    cmdlinearg_forceUIHidden = 0;
	else if ( strcmp(pt,"-recover")==0 && i<argc-1 ) {
	    ++i;
	    if ( strcmp(argv[i],"none")==0 )
		recover=0;
	    else if ( strcmp(argv[i],"clean")==0 )
		recover= -1;
	    else if ( strcmp(argv[i],"auto")==0 )
		recover= 1;
	    else if ( strcmp(argv[i],"inquire")==0 )
		recover= 2;
	    else {
		fprintf( stderr, "Invalid argument to -recover, must be none, auto, inquire or clean\n" );
		dousage();
	    }
	} else if ( strcmp(pt,"-recover=none")==0 ) {
	    recover = 0;
	} else if ( strcmp(pt,"-recover=clean")==0 ) {
	    recover = -1;
	} else if ( strcmp(pt,"-recover=auto")==0 ) {
	    recover = 1;
	} else if ( strcmp(pt,"-recover=inquire")==0 ) {
	    recover = 2;
	} else if ( strcmp(pt,"-docs")==0 )
	    dohelp();
	else if ( strcmp(pt,"-help")==0 )
	    dousage();
	else if ( strcmp(pt,"-version")==0 || strcmp(pt,"-v")==0 || strcmp(pt,"-V")==0 )
	    doversion(FONTFORGE_MODTIME_STR);
	else if ( strcmp(pt,"-quit")==0 )
	    quit_request = true;
	else if ( strcmp(pt,"-home")==0 )
	    /* already did a chdir earlier, don't need to do it again */;
#if defined(__Mac)
	else if ( strncmp(pt,"-psn_",5)==0 ) {
	    /* OK, I don't know what _-psn_ means, but to GW it means */
	    /* we've been started on the mac from the FontForge.app   */
	    /* structure, and the current directory was (shudder) "/" */
	    /* (however, we changed to HOME earlier in main routine). */
	    unique = 1;
	    listen_to_apple_events = true; // This has been problematic on Mavericks and later.
	}
#endif
    }

    ensureDotFontForgeIsSetup();
#if defined(__MINGW32__) && !defined(_NO_LIBCAIRO)
    //Load any custom fonts for the user interface
    if (use_cairo) {
        char *system_load = getGResourceProgramDir();
        char *user_load = getFontForgeUserDir(Data);
        char lbuf[MAX_PATH];
        int lret;

        if (system_load != NULL) {
            //Follow the FontConfig APPSHAREFONTDIR location
            lret = snprintf(lbuf, MAX_PATH, "%s/../share/fonts", system_load);
            if (lret > 0 && lret < MAX_PATH) {
                WinLoadUserFonts(lbuf);
            }
        }
        if (user_load != NULL) {
            lret = snprintf(lbuf, MAX_PATH, "%s/%s", user_load, "ui-fonts");
            if (lret > 0 && lret < MAX_PATH) {
                WinLoadUserFonts(lbuf);
            }
            free(user_load);
        }
    }
#endif
    InitImageCache(); // This is in gtextinfo.c. It zeroes imagecache for us.
    atexit(&ClearImageCache); // We register the destructor, which is also in gtextinfo.c.
    GDrawCreateDisplays(display,argv[0]);
    atexit(&GDrawDestroyDisplays); // We register the destructor so that it runs even if we call exit without finishing this function.
    default_background = GDrawGetDefaultBackground(screen_display);
    InitToolIconClut(default_background);
    InitToolIcons();
    InitCursors();

    /**
     * we have to do a quick sniff of argv[] here to see if the user
     * wanted to skip loading these python init files.
     */
    for ( i=1; i<argc; ++i ) {
	char *pt = argv[i];

	if ( !strcmp(pt,"-SkipPythonInitFiles")) {
	    ProcessPythonInitFiles = 0;
	}
    }
    
#ifndef _NO_PYTHON
/*# ifndef GWW_TEST*/
    FontForge_InitializeEmbeddedPython(); /* !!!!!! debug (valgrind doesn't like python) */
/*# endif*/
#endif

#ifndef _NO_PYTHON
    if( ProcessPythonInitFiles )
	PyFF_ProcessInitFiles();
#endif

    /* the splash screen used not to have a title bar (wam_nodecor) */
    /*  but I found I needed to know how much the window manager moved */
    /*  the window around, which I can determine if I have a positioned */
    /*  decorated window created at the begining */
    /* Actually I don't care any more */
    wattrs.mask = wam_events|wam_cursor|wam_bordwidth|wam_backcol|wam_positioned|wam_utf8_wtitle|wam_isdlg;
    wattrs.event_masks = ~(1<<et_charup);
    wattrs.positioned = 1;
    wattrs.cursor = ct_pointer;
    wattrs.utf8_window_title = "FontForge";
    wattrs.border_width = 2;
    wattrs.background_color = 0xffffff;
    wattrs.is_dlg = !listen_to_apple_events;
    pos.x = pos.y = 200;
    pos.width = splashimage.u.image->width;
    pos.height = splashimage.u.image->height-56;		/* 54 */
    GDrawBindSelection(NULL,sn_user1,"FontForge");
    if ( unique && GDrawSelectionOwned(NULL,sn_user1)) {
	/* Different event handler, not a dialog */
	wattrs.is_dlg = false;
	splashw = GDrawCreateTopWindow(NULL,&pos,request_e_h,NULL,&wattrs);
	PingOtherFontForge(argc,argv);
    } else {
	if ( quit_request )
exit( 0 );
	splashw = GDrawCreateTopWindow(NULL,&pos,splash_e_h,NULL,&wattrs);
    }

    memset(&rq,0,sizeof(rq));
    rq.utf8_family_name = SERIF_UI_FAMILIES;
    rq.point_size = 12;
    rq.weight = 400;
    splash_font = GDrawInstanciateFont(NULL,&rq);
    splash_font = GResourceFindFont("Splash.Font",splash_font);
    GDrawDecomposeFont(splash_font, &rq);
    rq.style = fs_italic;
    splash_italic = GDrawInstanciateFont(NULL,&rq);
    splash_italic = GResourceFindFont("Splash.ItalicFont",splash_italic);
    GDrawSetFont(splashw,splash_font);

    SplashLayout();
    localsplash = splash;

   if ( localsplash && !listen_to_apple_events )
	start_splash_screen();

    //
    // The below call will initialize the fontconfig cache if required.
    // That can take a while the first time it happens.
    //
   GDrawWindowFontMetrics(splashw,splash_font,&as,&ds,&ld);
   fh = as+ds+ld;

    if ( AutoSaveFrequency>0 )
	autosave_timer=GDrawRequestTimer(splashw,2*AutoSaveFrequency*1000,AutoSaveFrequency*1000,NULL);

    GDrawProcessPendingEvents(NULL);
    GDrawSetBuildCharHooks(BuildCharHook,InsCharHook);

    any = 0;
    if ( recover==-1 )
	CleanAutoRecovery();
    else if ( recover )
	any = DoAutoRecoveryExtended( recover-1 );
			
    openflags = 0;
    for ( i=1; i<argc; ++i ) {
	char buffer[1025];
	char *pt = argv[i];

	GDrawProcessPendingEvents(NULL);
	if ( pt[0]=='-' && pt[1]=='-' && pt[2]!='\0')
	    ++pt;
	if ( strcmp(pt,"-new")==0 ) {
	    FontNew();
	    any = 1;
#  if HANYANG
	} else if ( strcmp(pt,"-newkorean")==0 ) {
	    MenuNewComposition(NULL,NULL,NULL);
	    any = 1;
#  endif
	} else if ( !strcmp(pt,"-SkipPythonInitFiles")) {
	    // already handled above.
	} else if ( strcmp(pt,"-last")==0 ) {
	    if ( next_recent<RECENT_MAX && RecentFiles[next_recent]!=NULL )
		if ( ViewPostScriptFont(RecentFiles[next_recent++],openflags))
		    any = 1;
	} else if ( strcmp(pt,"-sync")==0 || strcmp(pt,"-memory")==0 ||
		    strcmp(pt,"-nosplash")==0 || strcmp(pt,"-recover=none")==0 ||
		    strcmp(pt,"-recover=clean")==0 || strcmp(pt,"-recover=auto")==0 ||
		    strcmp(pt,"-dontopenxdevices")==0 || strcmp(pt,"-unique")==0 ||
		    strncmp(pt,"-usecairo",strlen("-usecairo"))==0 ||
		    strcmp(pt,"-home")==0 || strcmp(pt,"-quiet")==0
		    || strcmp(pt,"-forceuihidden")==0 )
	    /* Already done, needed to be before display opened */;
	else if ( strncmp(pt,"-psn_",5)==0 )
	    /* Already done */;
	else if ( (strcmp(pt,"-depth")==0 || strcmp(pt,"-vc")==0 ||
		    strcmp(pt,"-cmap")==0 || strcmp(pt,"-colormap")==0 ||
		    strcmp(pt,"-keyboard")==0 ||
		    strcmp(pt,"-display")==0 || strcmp(pt,"-recover")==0 ) &&
		i<argc-1 )
	    ++i; /* Already done, needed to be before display opened */
	else if ( strcmp(pt,"-allglyphs")==0 )
	    openflags |= of_all_glyphs_in_ttc;
	else if ( strcmp(pt,"-open")==0 )
	    doopen = true;
	else {
	    printf("else argv[i]:%s\n", argv[i] );
	    if ( strstr(argv[i],"://")!=NULL ) {		/* Assume an absolute URL */
		strncpy(buffer,argv[i],sizeof(buffer));
		buffer[sizeof(buffer)-1]= '\0';
	    } else
		GFileGetAbsoluteName(argv[i],buffer,sizeof(buffer));
	    if ( GFileIsDir(buffer) || (strstr(buffer,"://")!=NULL && buffer[strlen(buffer)-1]=='/')) {
		char *fname;
		fname = malloc(strlen(buffer)+strlen("/glyphs/contents.plist")+1);
		strcpy(fname,buffer); strcat(fname,"/glyphs/contents.plist");
		if ( GFileExists(fname)) {
		    /* It's probably a Unified Font Object directory */
		    free(fname);
		    if ( ViewPostScriptFont(buffer,openflags) )
			any = 1;
		} else {
		    strcpy(fname,buffer); strcat(fname,"/font.props");
		    if ( GFileExists(fname)) {
			/* It's probably a sf dir collection */
			free(fname);
			if ( ViewPostScriptFont(buffer,openflags) )
			    any = 1;
		    } else {
			free(fname);
			if ( buffer[strlen(buffer)-1]!='/' ) {
			    /* If dirname doesn't end in "/" we'll be looking in parent dir */
			    buffer[strlen(buffer)+1]='\0';
			    buffer[strlen(buffer)] = '/';
			}
			fname = GetPostScriptFontName(buffer,false);
			if ( fname!=NULL )
			    ViewPostScriptFont(fname,openflags);
			any = 1;	/* Even if we didn't get a font, don't bring up dlg again */
			free(fname);
		    }
		}
	    } else if ( ViewPostScriptFont(buffer,openflags)!=0 )
		any = 1;
	}
    }
    if ( !any && !doopen )
	any = ReopenLastFonts();

    collabclient_ensureClientBeacon();
    collabclient_sniffForLocalServer();
#ifndef _NO_PYTHON
    PythonUI_namedpipe_Init();
#endif

#if defined(__Mac)
    if ( listen_to_apple_events ) {
	install_apple_event_handlers();
	install_mac_timer();
	setup_cocoa_app();

	
	// WARNING: See declaration of RunApplicationEventLoop() above as to
	// why you might not want to call that function anymore.
	// RunApplicationEventLoop();
	
    } else
#endif
    if ( doopen || !any )
	_FVMenuOpen(NULL);
    GDrawEventLoop(NULL);
    GDrawDestroyDisplays();

#ifndef _NO_PYTHON
/*# ifndef GWW_TEST*/
    FontForge_FinalizeEmbeddedPython(); /* !!!!!! debug (valgrind doesn't like python) */
/*# endif*/
#endif

    // These free menu translations, mostly.
    BitmapViewFinishNonStatic();
    MetricsViewFinishNonStatic();
    CharViewFinishNonStatic();
    FontViewFinishNonStatic();

    ClearImageCache(); // This frees the contents of imagecache.
    hotkeysSave();
    LastFonts_Save();

#ifndef _NO_LIBUNICODENAMES
    uninm_names_db_close(names_db);	/* close this database before exiting */
    uninm_blocks_db_close(blocks_db);
#endif

    lt_dlexit();

return( 0 );
}
コード例 #19
0
ファイル: WIZBOOK.C プロジェクト: arpruss/ozdev
void view(void)
{
	static byte mod;
	static unsigned k;
    static unsigned long delta;
    static byte i;
	load_headers();
    in_buf=0;
    ateof=0;
    atstart=1;
    scrollbar_pos=0xa000+29;
    if(last==0) last=header_length;
    goto_pos(last);
	mod=1;
    ozcls();
	while(1)
	{
        if(mod)
        {
            if(!backandforth)position_save();
            show();
            unbar();
            scrollbar();
            backandforth=mod=0;
        }
        switch(k=ozgetchblank())
		{
            case KEY_LEFT:
            case KEY_BACKSPACE:
#ifdef DEBUG
                putformatted(0,0,"positionptr=| numpositions=|  ",
                positionptr,numpositions);
                ozgetch();
#endif
                if(positionptr<=1) break;
                goto_pos(positions[(--positionptr)-1]);
                if(!positionptr) positionptr=1;
                backandforth=mod=1;
#ifdef DEBUG
                putformatted(0,0,"positionptr=| numpositions=|  ",
                positionptr,numpositions);
                ozgetch();
#endif
                break;
            case KEY_RIGHT:
#ifdef DEBUG
                putformatted(0,0,"positionptr=| numpositions=|  ",
                positionptr,numpositions);
                ozgetch();
#endif
                if(positionptr>=numpositions) break;
                goto_pos(positions[positionptr]);
                positionptr++;
                backandforth=mod=1;
#ifdef DEBUG
                putformatted(0,0,"positionptr=| numpositions=|  ",
                positionptr,numpositions);
                ozgetch();
#endif
                break;
            case 'm':
                /* mark position */
                if(numbookmarks>=MAX_BOOKMARKS)
                {
                    for(i=0;i<MAX_BOOKMARKS-1;i++)
                    {
                        bookmarks[i]=bookmarks[i+1];
                    }
                    numbookmarks--;
                }
                bookmarkptr=numbookmarks;
                bookmarks[numbookmarks++]=screen_offset+buffer_offset;
                bookmarksmod=1;
                break;
            case 'b':
                if(numbookmarks)
                {
                    goto_pos(bookmarks[bookmarkptr]);
                    if(bookmarkptr) bookmarkptr--;
                     else bookmarkptr=numbookmarks-1;
                    mod=1;
                }
                break;
            case 'r':
                show_bar=!show_bar;
                bookmarksmod=1;
                unbar();
                scrollbar();
                break;
            case 'h':
            case KEY_UPPER_MENU:
            case KEY_LOWER_MENU:
                dohelp();
                ozcls();
                mod=1;
                break;
            case 'i':
                _ozfilledbox(0,0,WIDTH,line_height,0);
                delta=screen_offset+buffer_offset-header_length;
                putformatted(0,0,"$ : ^/^=|%",filename,
                    delta,length-header_length,
                    (unsigned int)(delta*100/(length-header_length)) );
                _ozfilledbox(0,0,WIDTH,line_height,XOR);
                ozgetchblank();
                mod=1;
                ozcls();
                break;
            case 'c':
                if(numbookmarks && ozwarn("Delete all bookmarks?",yn)==KEY_LOWER_ENTER
                    )
                    {
                        bookmarksmod=1;
                        numbookmarks=0;
                    }
                mod=1;
                ozcls();
                break;
            case '-':
			case KEY_PAGEUP:
                for(i=0;i<num_lines-1;i++)
				{
					checkshiftup();
					backline();
				}
				mod=1;
				break;
            case 's':
                if(myfont) break;
                line_height++;
                if(line_height==11) line_height=8;
                if(line_height!=9) num_lines=80/line_height;
                    else num_lines=9;
                bookmarksmod=1;
                mod=1;
                ozcls();
                break;
			case KEY_PAGEDOWN:
            case KEY_LOWER_ENTER:
            case KEY_UPPER_ENTER:
            case KEY_RETURN:
            case ' ':
                for(i=0;i<num_lines-1;i++)
				{
					checkshiftdown();
					forwardline();
				}
				mod=1;
				break;
            case KEY_UP:
                checkshiftup();
                if(!backline()) break;
                unbar();
                ozscrolldown(line_height*30);
                dcompline(filebuf+screen_offset);
                puttextline(0);
                position_save();
                scrollbar();
                break;
            case KEY_DOWN:
                checkshiftdown();
                if(forwardline())
                {
                    mod=1;
                    showbot=1;
                    unbar();
                    ozscroll(line_height*30);
                }
                break;
            case KEY_LEFT_SHIFT | MASKSHIFT:
            case KEY_RIGHT_SHIFT | MASKSHIFT:
                switch(ozgetch() & 0xF0FF)
                {
                    case '-':
                        ozclick(!ozgetclick());
                        ozsavekeysettings();
                        break;
                    case KEY_PAGEUP:
                    case KEY_UP:
                        tenpercent(-1);
                        mod=1;
                        break;
                    case KEY_PAGEDOWN:
                    case KEY_DOWN:
                        tenpercent(1);
                        mod=1;
                        break;
                }
                break;
            case KEY_UP | MASKSHIFT:
            case KEY_PAGEUP | MASKSHIFT:
                tenpercent(-1);
                mod=1;
                break;
            case KEY_PAGEDOWN | MASKSHIFT:
            case KEY_DOWN | MASKSHIFT:
                tenpercent(1);
                mod=1;
                break;
			case KEY_2ND:
                switch(ozgetch() & 0xF0FF )
				{
                    case '-':
                        ozclick(!ozgetclick());
                        ozsavekeysettings();
                        break;
                    case KEY_PAGEUP:
					case KEY_UP:
                        goto_pos(header_length);
						mod=1;
						break;
					case KEY_PAGEDOWN:
					case KEY_DOWN:
                        goto_pos(length);
						mod=1;
						break;
				}
				break;
			case KEY_LOWER_ESC:
			case KEY_UPPER_ESC:
			case KEY_MYPROGRAMS:
				exit(0);
			case KEY_MAIN:
			case KEY_CALENDAR:
			case KEY_TELEPHONE:
			case KEY_MEMO:
				ozexitto(k);
			case KEY_BACKLIGHT:
                oztogglelight();
				break;
		}
	}
}
コード例 #20
0
ファイル: oldfiles.c プロジェクト: rlp1938/oldfiles
int main(int argc, char **argv)
{
    int opt, age, quiet;
    char topdir[PATH_MAX];
    char aunit = 'Y';
    struct stat sb;
    char *datestr;
	char command[PATH_MAX];
	char **workfile;

    // set up defaults
    quiet = 0;
    age = 3;
    strcpy(topdir, getenv("HOME"));
    head = newlistitem();
    opfn = (char *)NULL;
    oldcount = 0;
    workfile = workfiles("/tmp/", argv[0], 4);
    fpo=dofopen(workfile[0], "w");

    while((opt = getopt(argc, argv, ":ha:o:q")) != -1) {
        switch(opt){
        /* I have no idea what the value of topdir will be during
         * options processing so all I can do is set a task variable
         * to select action after topdir is known or whether it's
         * actually needed.
        */
        case 'h':
            dohelp(0);
        break;
        case 'a': // change default age
            age = strtol(optarg, NULL, 10);
            if (strchr(optarg, 'M')) aunit = 'M';
            if (strchr(optarg, 'm')) aunit = 'M';
            if (strchr(optarg, 'D')) aunit = 'D';
            if (strchr(optarg, 'd')) aunit = 'D';
        break;
        case 'q':
			quiet = 1;
        break;
        case 'o':   // list files older than input file time
            datestr = strdup(optarg);
            fileage = parsetimestring(datestr);
        break;
        case ':':
            fprintf(stderr, "Option %c requires an argument\n",optopt);
            dohelp(1);
        break;
        case '?':
            fprintf(stderr, "Illegal option: %c\n",optopt);
            dohelp(1);
        break;
        } //switch()
    }//while()

    // now process the non-option arguments

    // 1.See if argv[1] exists.
    if ((argv[optind])) {
       strcpy(topdir, argv[optind]);  // default is /home/$USER
    }

    // Check that the top dir is legitimate.
    if (stat(topdir, &sb) == -1) {
        perror(topdir);
        exit(EXIT_FAILURE);
    }
    // It exists then, but is it a dir?
    if (!(S_ISDIR(sb.st_mode))) {
        fprintf(stderr, "%s is not a directory!\n", topdir);
        exit(EXIT_FAILURE);
    }

	// Convert relative path to absolute if needed.
	if (topdir[0] != '/') dorealpath(argv[optind], topdir);

    fileage = cutofftimebyage(age, aunit);
    recursedir(topdir);
    fclose(fpo);
    if (oldcount > 0) {
		sprintf(command, "sort -u %s > %s", workfile[0],
					workfile[1]);
		dosystem(command);
	} else {
		if (!quiet) {
			fprintf(stderr, "No old files found\n");
		}
		unlink(workfile[0]);
		exit(EXIT_SUCCESS);
	}
	// get rid of the leading inode and sort on pathname
	stripinode(workfile[1], workfile[2]);
	sprintf(command, "sort %s > %s", workfile[2],
					workfile[3]);
	dosystem(command);
	dumpfile(workfile[3], stdout);

    return 0;
}//main()
コード例 #21
0
ファイル: shell.c プロジェクト: alujajakerry/SISO2
/*this is the main routine*/
void doshell()
{
	char line[80];

	/*run forever - the shell shouldn't end*/
	while(1==1)
	{
		/*read in a line*/
		printstring("SHELL>\0");
		readstring(line);

		/*match it against each possible command*/
		/*if the user presses return, ignore it*/
		if (line[0]==0xd)
			continue;
		else if (iscommand(line,"CLS\0")==1)
			doclear();
		else if (iscommand(line,"cls\0")==1)
			doclear();
		else if (iscommand(line,"COPY\0")==1)
			docopy();
		else if (iscommand(line,"copy\0")==1)
			docopy();
		else if (iscommand(line,"CREATE \0")==1)
			docreate(line);
		else if (iscommand(line,"create \0")==1)
			docreate(line);
		else if (iscommand(line,"DELETE \0")==1)
			dodelete(line);
		else if (iscommand(line,"delete \0")==1)
			dodelete(line);
		else if (iscommand(line,"DIR\0")==1)
			dodir();
		else if (iscommand(line,"dir\0")==1)
			dodir();
		else if (iscommand(line,"EXEC \0")==1)
			doexecute(line,1);
		else if (iscommand(line,"exec \0")==1)
			doexecute(line,1);
		else if (iscommand(line,"EXECBACK \0")==1)
			doexecute(line,0);
		else if (iscommand(line,"execback \0")==1)
			doexecute(line,0);
		else if (iscommand(line,"HELP\0")==1)
			dohelp();
		else if (iscommand(line,"help\0")==1)
			dohelp();
		else if (line[0]=='?')
			dohelp();
		else if (iscommand(line,"TYPE \0")==1)
			dotype(line);
		else if (iscommand(line,"type \0")==1)
			dotype(line);
		else if (iscommand(line,"KILL \0")==1)
			dokill(line);
		else if (iscommand(line,"kill \0")==1)
			dokill(line);
		else if (iscommand(line,"mkdir \0")==1)
			domkdir(line);
		else if (iscommand(line,"MKDIR\0")==1)
			domkdir(line);	
		else if (iscommand(line,"FORMAT\0")==1)
			doFormat();	
		else if (iscommand(line,"format\0")==1)
			doFormat();	
		else if (iscommand(line,"remove\0")==1)
			doRemove(line);	
		else if (iscommand(line,"REMOVE\0")==1)
			doRemove(line);	
		else if (iscommand(line,"list\0")==1)
			doList();	
		else if (iscommand(line,"LIST\0")==1)
			doList();	
		else if (iscommand(line,"count\0")==1)
			doCount(line);
		else if (iscommand(line,"WRITE\0")==1)
				doCreateFile(line);	
		else if (iscommand(line,"write\0")==1)
			doCreateFile(line);
		else if (iscommand(line,"READ\0")==1)
				doEcho(line);	
		else if (iscommand(line,"read\0")==1)
			doEcho(line);
		else
			printstring("Command not found\r\n\0");
		printstring("\r\n\0");
	}
}
コード例 #22
0
ファイル: dbpmda.c プロジェクト: ColeJackes/pcp
int
main(int argc, char **argv)
{
    int			c;
    int			sts;
    char		*endnum;

    iflag = isatty(0);

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'D':		/* debug flag */
	    sts = __pmParseDebug(opts.optarg);
	    if (sts < 0) {
		fprintf(stderr, "%s: unrecognized debug flag specification (%s)\n",
		    pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else
		pmDebug |= sts;
	    break;

	case 'e':		/* echo input */
	    eflag++;
	    break;

	case 'f':		/* skip .dbpmdarc processing */
	    fflag++;
	    break;

	case 'i':		/* be interactive */
	    iflag = 1;
	    break;

	case 'n':		/* alternative name space file */
	    pmnsfile = opts.optarg;
	    break;

	case 'q':
	    sts = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0' || sts <= 0.0) {
		pmprintf("%s: -q requires a positive numeric argument\n",
			pmProgname);
		opts.errors++;
	    } else {
		_creds_timeout = sts;
	    }
	    break;

	case 'U':		/* run under alternate user account */
	    __pmSetProcessIdentity(opts.optarg);
	    break;

	default:
	case '?':
	    opts.errors++;
	    break;
	}
    }

    if ((c = argc - opts.optind) > 0) {
	if (c > 1)
	    opts.errors++;
	else {
	    /* pid was specified */
	    if (primary) {
		pmprintf("%s: you may not specify both -P and a pid\n",
			pmProgname);
		opts.errors++;
	    }
	    else {
		pid = (int)strtol(argv[opts.optind], &endnum, 10);
		if (*endnum != '\0') {
		    pmprintf("%s: pid must be a numeric process id\n",
			    pmProgname);
		    opts.errors++;
		}
	    }
	}
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (pmnsfile == PM_NS_DEFAULT) {
	if ((sts = pmLoadNameSpace(pmnsfile)) < 0) {
		fprintf(stderr, "%s: Cannot load default namespace: %s\n",
			pmProgname, pmErrStr(sts));
	    exit(1);
	}
    }
    else {
	if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
		fprintf(stderr, "%s: Cannot load namespace from \"%s\": %s\n",
			pmProgname, pmnsfile, pmErrStr(sts));
	    exit(1);
	}
    }

    /* initialize the "fake context" ... */
    setup_context();

    setlinebuf(stdout);
    setlinebuf(stderr);

#ifdef HAVE_ATEXIT
    atexit(cleanup);
#endif

    for ( ; ; ) {
	initmetriclist();
	yyparse();
	if (yywrap()) {
	    if (iflag)
		putchar('\n');
	    break;
	}

	__pmSetInternalState(PM_STATE_PMCS);

	switch (stmt_type) {

	    case OPEN:
		profile_changed = 1;
		break;

	    case CLOSE:
		switch (connmode) {
		    case CONN_DSO:
			closedso();
			break;
		    
		    case CONN_DAEMON:
			closepmda();
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		connmode = NO_CONN;
		break;

	    case DESC:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_DESC_REQ);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_DESC_REQ);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case FETCH:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_FETCH);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_FETCH);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case INSTANCE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_INSTANCE_REQ);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_INSTANCE_REQ);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case STORE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_RESULT);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_RESULT);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case HELP:
		dohelp(param.number, param.pmid);
		break;

	    case WATCH:
		break;

	    case DBG:
		pmDebug = param.number;
		break;

	    case QUIT:
		goto done;

	    case STATUS:
		dostatus();
		break;

	    case INFO:
		switch (connmode) {
		case CONN_DSO:
		    dodso(PDU_TEXT_REQ);
		    break;

		case CONN_DAEMON:
		    dopmda(PDU_TEXT_REQ);
		    break;

		case NO_CONN:
		    yywarn("No PMDA currently opened");
		    break;
		}
		break;
	    case NAMESPACE:
		if (cmd_namespace != NULL)
		    free(cmd_namespace);
		cmd_namespace = strdup(param.name);
		if (cmd_namespace == NULL) {
		    fprintf(stderr, "%s: No memory for new namespace\n",
			    pmProgname);
		    exit(1);
		}
		pmUnloadNameSpace();
		strcpy(cmd_namespace, param.name);
		if ((sts = pmLoadASCIINameSpace(cmd_namespace, 1)) < 0) {
		    fprintf(stderr, "%s: Cannot load namespace from \"%s\": %s\n",
			    pmProgname, cmd_namespace, pmErrStr(sts));

		    pmUnloadNameSpace();
		    if (pmnsfile == PM_NS_DEFAULT) {
			fprintf(stderr, "%s: Reload default namespace\n",
				pmProgname);
			if ((sts = pmLoadNameSpace(pmnsfile)) < 0) {
			    fprintf(stderr,
				    "%s: Cannot load default namespace: %s\n",
				    pmProgname, pmErrStr(sts));
			    exit(1);
			}
		    }
		    else {
			fprintf(stderr, "%s: Reload namespace from \"%s\"\n",
				pmProgname, pmnsfile);
			if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
			    fprintf(stderr,
				    "%s: Cannot load namespace from \"%s\""
				    ": %s\n",
				    pmProgname, pmnsfile, pmErrStr(sts));
			    exit(1);
			}
		    }
		}
		break;

	    case EOL:
		break;

	    case PMNS_NAME:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_IDS);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_IDS);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_PMID:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_NAMES);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_NAMES);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_CHILDREN:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_CHILD);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_CHILD);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_TRAVERSE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_TRAVERSE);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_TRAVERSE);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case ATTR:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_AUTH);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_AUTH);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    default:
		printf("Unexpected result (%d) from parser?\n", stmt_type);
		break;
	}
	__pmSetInternalState(PM_STATE_APPL);
    }

done:
    cleanup();

    exit(0);
}