Esempio n. 1
0
/* 
 * run_etc_support() - Run command in etc/support 
 *
 * RETURN: >0 success : 0 failure
 */
int run_etc_support(char *pgm, char *rast)
{
    char path[GPATH_MAX];
    int stat;

    sprintf(path, "%s/etc/%s", G_gisbase(), pgm);

    if ((stat = G_spawn(path, pgm, rast, NULL)))
	G_sleep(3);

    return stat;
}
Esempio n. 2
0
const char *GPJ_set_csv_loc(const char *name)
{
    const char *gisbase = G_gisbase();
    static char *buf = NULL;

    if (buf != NULL)
	G_free(buf);

    G_asprintf(&buf, "%s%s/%s", gisbase, CSVDIR, name);

    return buf;
}
Esempio n. 3
0
void G_read_datum_table(void)
{
    FILE *fd;
    char file[GPATH_MAX];
    char buf[1024];
    int line;

    if (G_is_initialized(&table.initialized))
	return;

    sprintf(file, "%s%s", G_gisbase(), DATUMTABLE);

    fd = fopen(file, "r");
    if (!fd) {
	G_warning(_("unable to open datum table file: %s"), file);
	G_initialize_done(&table.initialized);
	return;
    }

    for (line = 1; G_getl2(buf, sizeof(buf), fd); line++) {
	char name[100], descr[100], ellps[100];
	struct datum *t;

	G_strip(buf);
	if (*buf == '\0' || *buf == '#')
	    continue;

	if (table.count >= table.size) {
	    table.size += 50;
	    table.datums = G_realloc(table.datums, table.size * sizeof(struct datum));
	}

	t = &table.datums[table.count];

	if (sscanf(buf, "%s \"%99[^\"]\" %s dx=%lf dy=%lf dz=%lf",
		   name, descr, ellps, &t->dx, &t->dy, &t->dz) != 6) {
	    G_warning(_("error in datum table file, line %d"), line);
	    continue;
	}

	t->name = G_store(name);
	t->descr = G_store(descr);
	t->ellps = G_store(ellps);

	table.count++;
    }

    qsort(table.datums, table.count, sizeof(struct datum), compare_table_names);

    G_initialize_done(&table.initialized);
}
Esempio n. 4
0
File: datum.c Progetto: caomw/grass
struct datum_list *read_datum_table(void)
{
    FILE *fd;
    char file[GPATH_MAX];
    char buf[4096];
    int line;
    struct datum_list *current = NULL, *outputlist = NULL;
    int count = 0;

    sprintf(file, "%s%s", G_gisbase(), DATUMTABLE);

    fd = fopen(file, "r");
    if (!fd) {
	G_warning(_("Unable to open datum table file <%s>"), file);
	return NULL;
    }

    for (line = 1; G_getl2(buf, sizeof(buf), fd); line++) {
	char name[100], descr[1024], ellps[100];
	double dx, dy, dz;

	G_strip(buf);
	if (*buf == '\0' || *buf == '#')
	    continue;

	if (sscanf(buf, "%s \"%1023[^\"]\" %s dx=%lf dy=%lf dz=%lf",
		   name, descr, ellps, &dx, &dy, &dz) != 6) {
	    G_warning(_("Error in datum table file <%s>, line %d"), file,
		      line);
	    continue;
	}

	if (current == NULL)
	    current = outputlist = G_malloc(sizeof(struct datum_list));
	else
	    current = current->next = G_malloc(sizeof(struct datum_list));
	current->name = G_store(name);
	current->longname = G_store(descr);
	current->ellps = G_store(ellps);
	current->dx = dx;
	current->dy = dy;
	current->dz = dz;
	current->next = NULL;

	count++;
    }

    fclose(fd);

    return outputlist;
}
Esempio n. 5
0
static void scan_rules(void)
{
    char path[GPATH_MAX];

    sprintf(path, "%s/etc/colors", G_gisbase());

    rules = G__ls(path, &nrules);

    rules = G_realloc(rules, (nrules + 4) * sizeof(const char *));

    rules[nrules++] = G_store("random");
    rules[nrules++] = G_store("grey.eq");
    rules[nrules++] = G_store("grey.log");
    rules[nrules++] = G_store("rules");

    qsort(rules, nrules, sizeof(char *), cmp);
}
Esempio n. 6
0
int GPJ__get_datum_params(const struct Key_Value *projinfo,
			  char **datumname, char **params)
{
    int returnval = -1;

    if (NULL != G_find_key_value("datum", projinfo)) {
	*datumname = G_store(G_find_key_value("datum", projinfo));
	G_debug(3, "GPJ__get_datum_params: datumname: <%s>", G_find_key_value("datum", projinfo));
	returnval = 1;
    }
    else
	*datumname = NULL;

    if (G_find_key_value("datumparams", projinfo) != NULL) {
	*params = G_store(G_find_key_value("datumparams", projinfo));
	G_debug(3, "GPJ__get_datum_params: datumparams: <%s>", G_find_key_value("datumparams", projinfo));
	returnval = 2;
    }
    else if (G_find_key_value("nadgrids", projinfo) != NULL) {
	const char *gisbase = G_gisbase();

	G_asprintf(params, "nadgrids=%s%s/%s", gisbase, GRIDDIR,
		   G_find_key_value("nadgrids", projinfo));
	returnval = 2;
    }
    else if (G_find_key_value("towgs84", projinfo) != NULL) {
	G_asprintf(params, "towgs84=%s",
		   G_find_key_value("towgs84", projinfo));
	returnval = 2;
    }
    else if (G_find_key_value("dx", projinfo) != NULL
	     && G_find_key_value("dy", projinfo) != NULL
	     && G_find_key_value("dz", projinfo) != NULL) {
	G_asprintf(params, "towgs84=%s,%s,%s",
		   G_find_key_value("dx", projinfo),
		   G_find_key_value("dy", projinfo),
		   G_find_key_value("dz", projinfo));
	returnval = 2;
    }
    else
	*params = NULL;

    return returnval;

}
Esempio n. 7
0
int run(char *pgm, char *flags, char *name)
{
    char path[GPATH_MAX];
    int stat;

    sprintf(path, "%s/etc/mon.%s", G_gisbase(), pgm);

    if (*flags) {
	if ((stat = G_spawn(path, pgm, flags, name, NULL)))
	    G_sleep(3);
    }
    else {
	if ((stat = G_spawn(path, pgm, name, NULL)))
	    G_sleep(3);
    }

    return stat;
}
Esempio n. 8
0
/*!
  \brief Get color rules description for Option->descriptions

  \return allocated buffer with descriptions
*/
char *G_color_rules_descriptions(void)
{
    char path[GPATH_MAX];
    struct Key_Value *kv;
    int result_len, result_max;
    char *result, **rules;
    const char *name, *desc;
    int i, len, nrules;

    result_len = 0;
    result_max = 2000;
    result = G_malloc(result_max);
    
    G_snprintf(path, GPATH_MAX, "%s/etc/colors.desc", G_gisbase());
    kv = G_read_key_value_file(path);
    if (!kv)
        return NULL;

    rules = scan_rules(&nrules);
    
    for (i = 0; i < nrules; i++) {
        name = rules[i];
        desc = G_find_key_value(name, kv);
        
        if (!desc)
	    desc = _("no description");
	
        /* desc = _(desc); */
	
        len = strlen(name) + strlen(desc) + 2;
        if (result_len + len >= result_max) {
            result_max = result_len + len + 1000;
            result = G_realloc(result, result_max);
        }

        sprintf(result + result_len, "%s;%s;", name, desc);
        result_len += len;
    }

    G_free_key_value(kv);
    G_free(rules);
    
    return result;
}
Esempio n. 9
0
/* start wxGUI display monitor */
void start_wx(const char *name, const char *tempfile,
	      const char *env_value, const char *cmd_value,
	      const char *width, const char *height)
{
    char progname[GPATH_MAX];
    char *env_name, *map_value;

    env_name = NULL;
    G_asprintf(&env_name, "MONITOR_%s_MAPFILE", name);
    G_asprintf(&map_value, "%s.ppm", tempfile);
    G_setenv(env_name, map_value);
    /* close(creat(map_value, 0666)); */
    
    G_debug(3, "       mapfile = %s", map_value);

    sprintf(progname, "%s/etc/gui/wxpython/gui_modules/mapdisp.py", G_gisbase());
    G_spawn_ex(getenv("GRASS_PYTHON"), progname, progname,
	       name, map_value, cmd_value, env_value, width ? width : "", height ? height : "", SF_BACKGROUND, NULL);
}
Esempio n. 10
0
static char *rules_descriptions(void)
{
    char path[GPATH_MAX];
    struct Key_Value *kv;
    int result_len = 0;
    int result_max = 2000;
    char *result = G_malloc(result_max);
    int stat;
    int i;

    sprintf(path, "%s/etc/colors.desc", G_gisbase());
    kv = G_read_key_value_file(path, &stat);
    if (!kv || stat < 0)
	return NULL;

    for (i = 0; i < nrules; i++) {
	const char *name = rules[i];
	const char *desc = G_find_key_value(name, kv);
	int len;

	if (!desc)
	    desc = "no description";

	desc = _(desc);

	len = strlen(name) + strlen(desc) + 2;
	if (result_len + len >= result_max) {
	    result_max = result_len + len + 1000;
	    result = G_realloc(result, result_max);
	}

	sprintf(result + result_len, "%s;%s;", name, desc);
	result_len += len;
    }

    G_free_key_value(kv);

    return result;
}
Esempio n. 11
0
int quit(int n)
{
    char command[1024];

    End_curses();
    R_close_driver();
    if (use_digitizer) {
	sprintf(command, "%s/etc/geo.unlock %s", G_gisbase(), digit_points);
	system(command);
    }
    unlink(tempfile1);
    unlink(tempfile2);
    unlink(cell_list);
    unlink(group_list);
    unlink(vect_list);
    unlink(digit_points);
    unlink(digit_results);

    system("d.frame -e");

    exit(n);
}
Esempio n. 12
0
struct proj_desc *get_proj_desc(const char *arg)
{
    char buf[4096];
    struct proj_desc *res;
    FILE *fp;

    sprintf(buf, "%s/etc/proj/desc.table", G_gisbase());

    fp = fopen(buf, "r");
    if (!fp)
	return NULL;

    for (res = NULL; !res;) {
	char name[16], type[16], key[16], desc[100];

	if (!G_getl2(buf, sizeof(buf), fp))
	    break;

	if (sscanf(buf, "%[^:]:%[^:]:%[^:]:%[^\n]", name, type, key, desc) !=
	    4)
	    continue;

	if (G_strcasecmp(arg, name) != 0)
	    continue;

	res = G_malloc(sizeof(struct proj_desc));

	res->name = G_store(name);
	res->type = G_store(type);
	res->key = G_store(key);
	res->desc = G_store(desc);
    }

    fclose(fp);

    return res;
}
Esempio n. 13
0
struct proj_unit *get_proj_unit(const char *arg)
{
    char buf[4096];
    struct proj_unit *unit;
    FILE *fp;

    sprintf(buf, "%s/etc/proj/units.table", G_gisbase());

    fp = fopen(buf, "r");
    if (!fp)
	return NULL;

    for (unit = NULL; !unit;) {
	char plural[16], singular[16];
	double factor;
	struct proj_unit *unit;

	if (!G_getl2(buf, sizeof(buf), fp))
	    break;

	if (sscanf(buf, "%[^:]:%[^:]:%lf", plural, singular, &factor) != 3)
	    continue;

	if (G_strcasecmp(arg, plural) != 0)
	    continue;

	unit = G_malloc(sizeof(struct proj_unit));

	unit->units = G_store(plural);
	unit->unit = G_store(singular);
	unit->fact = factor;
    }

    fclose(fp);

    return unit;
}
Esempio n. 14
0
/* 
 *  Read symbol specified by name.
 *  Name: group/name | group/name@mapset 
 *        (later add syntax to prefer symbol from GISBASE)
 *  S_read() searches first in mapsets (standard GRASS search) and
 *   then in GISBASE/etc/symbol/ 
 */
SYMBOL *S_read(const char *sname)
{
    int i, j, k, l;
    FILE *fp;
    char group[500], name[500], buf[2001];
    const char *ms;
    char *c;
    double x, y, x2, y2, rad, ang1, ang2;
    int r, g, b;
    double fr, fg, fb;
    int ret;
    char clock;
    SYMBOL *symb;
    int current;		/* current part_type */
    SYMBPART *part;		/* current part */
    SYMBCHAIN *chain;		/* current chain */
    SYMBEL *elem;		/* current element */

    G_debug(3, "S_read(): sname = %s", sname);

    /* Find file */
    /* Get group and name */
    strcpy(group, sname);
    c = strchr(group, '/');
    if (c == NULL) {
	G_warning(_("Incorrect symbol name: '%s' (should be: group/name or group/name@mapset)"),
		  sname);
	return NULL;
    }
    c[0] = '\0';

    c++;
    strcpy(name, c);

    G_debug(3, "  group: '%s' name: '%s'", group, name);

    /* Search in mapsets */
    sprintf(buf, "symbol/%s", group);
    ms = G_find_file(buf, name, NULL);

    if (ms != NULL) {		/* Found in mapsets */
	fp = G_fopen_old(buf, name, ms);
    }
    else {			/* Search in GISBASE */
	sprintf(buf, "%s/etc/symbol/%s", G_gisbase(), sname);
	fp = fopen(buf, "r");
    }

    if (fp == NULL) {
	G_warning(_("Cannot find/open symbol: '%s'"), sname);
	return NULL;
    }

    /* create new symbol */
    symb = new_symbol();

    current = OBJ_NONE;		/* no part */

    /* read file */
    while (G_getl2(buf, 2000, fp) != 0) {
	G_chop(buf);
	G_debug(3, "  BUF: [%s]", buf);

	/* skip empty and comment lines */
	if ((buf[0] == '#') || (buf[0] == '\0'))
	    continue;

	get_key_data(buf);

	if (strcmp(key, "VERSION") == 0) {
	    if (strcmp(data, "1.0") != 0) {
		sprintf(buf, "Wrong symbol version: '%s'", data);
		return (err(fp, symb, buf));
	    }
	}
	else if (strcmp(key, "BOX") == 0) {
	    if (sscanf(data, "%lf %lf %lf %lf", &x, &y, &x2, &y2) != 4) {
		sprintf(buf, "Incorrect box definition: '%s'", data);
		return (err(fp, symb, buf));
	    }
	    symb->xscale = 1 / (x2 - x);
	    symb->yscale = 1 / (y2 - y);
	    if (x2 - x > y2 - y) {
		symb->scale = symb->xscale;
	    }
	    else {
		symb->scale = symb->yscale;
	    }
	}
	else if (strcmp(key, "STRING") == 0) {
	    G_debug(4, "  STRING >");
	    current = OBJ_STRING;
	    part = new_part(S_STRING);
	    add_part(symb, part);

	    chain = new_chain();
	    add_chain(part, chain);
	}
	else if (strcmp(key, "POLYGON") == 0) {
	    G_debug(4, "  POLYGON >");
	    current = OBJ_POLYGON;
	    part = new_part(S_POLYGON);
	    add_part(symb, part);

	}
	else if (strcmp(key, "RING") == 0) {
	    G_debug(4, "  RING >");
	    current = OBJ_RING;
	    chain = new_chain();
	    add_chain(part, chain);

	}
	else if (strcmp(key, "LINE") == 0) {
	    G_debug(4, "    LINE >");
	    elem = new_line();
	    add_element(chain, elem);
	    read_coor(fp, elem);

	}
	else if (strcmp(key, "ARC") == 0) {
	    G_debug(4, "    ARC");
	    ret =
		sscanf(data, "%lf %lf %lf %lf %lf %c", &x, &y, &rad, &ang1,
		       &ang2, &clock);
	    if (ret < 5) {
		sprintf(buf, "Incorrect arc definition: '%s'", buf);
		return (err(fp, symb, buf));
	    }
	    if (ret == 6 && (clock == 'c' || clock == 'C'))
		i = 1;
	    else
		i = 0;
	    elem = new_arc(x, y, rad, ang1, ang2, i);
	    add_element(chain, elem);

	}
	else if (strcmp(key, "END") == 0) {
	    switch (current) {
	    case OBJ_STRING:
		G_debug(4, "  STRING END");
		current = OBJ_NONE;
		break;
	    case OBJ_POLYGON:
		G_debug(4, "  POLYGON END");
		current = OBJ_NONE;
		break;
	    case OBJ_RING:
		G_debug(4, "  RING END");
		current = OBJ_POLYGON;
		break;
	    }
	}
	else if (strcmp(key, "COLOR") == 0) {
	    if (G_strcasecmp(data, "NONE") == 0) {
		part->color.color = S_COL_NONE;
	    }
	    else if (sscanf(data, "%d %d %d", &r, &g, &b) == 3) {
		if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255)
		    G_warning(_("Incorrect symbol color: '%s', using default."),
			      buf);
		else {
		    fr = r / 255.0;
		    fg = g / 255.0;
		    fb = b / 255.0;
		    part->color.color = S_COL_DEFINED;
		    part->color.r = r;
		    part->color.g = g;
		    part->color.b = b;
		    part->color.fr = fr;
		    part->color.fg = fg;
		    part->color.fb = fb;
		    G_debug(4, "  color [%d %d %d] = [%.3f %.3f %.3f]", r, g,
			    b, fr, fg, fb);
		}
	    }
	    else {
		G_warning(_("Incorrect symbol color: '%s', using default."),
			  buf);
	    }
	}
	else if (strcmp(key, "FCOLOR") == 0) {
	    if (G_strcasecmp(data, "NONE") == 0) {
		part->fcolor.color = S_COL_NONE;
	    }
	    else if (sscanf(data, "%d %d %d", &r, &g, &b) == 3) {
		if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255)
		    G_warning(_("Incorrect symbol color: '%s', using default."),
			      buf);
		else {
		    fr = r / 255.0;
		    fg = g / 255.0;
		    fb = b / 255.0;
		    part->fcolor.color = S_COL_DEFINED;
		    part->fcolor.r = r;
		    part->fcolor.g = g;
		    part->fcolor.b = b;
		    part->fcolor.fr = fr;
		    part->fcolor.fg = fg;
		    part->fcolor.fb = fb;
		    G_debug(4, "  color [%d %d %d] = [%.3f %.3f %.3f]", r, g,
			    b, fr, fg, fb);
		}
	    }
	    else {
		G_warning(_("Incorrect symbol color: '%s', using default."),
			  buf);
	    }
	}
	else {
	    sprintf(buf, "Unknown keyword in symbol: '%s'", buf);
	    return (err(fp, symb, buf));
	    break;
	}
    }

    /* Debug output */

    G_debug(3, "Number of parts: %d", symb->count);
    for (i = 0; i < symb->count; i++) {
	part = symb->part[i];
	G_debug(4, "  Part %d: type: %d number of chains: %d", i, part->type,
		part->count);
	G_debug(4, "           color: %d: fcolor: %d", part->color.color,
		part->fcolor.color);
	for (j = 0; j < part->count; j++) {
	    chain = part->chain[j];
	    G_debug(4, "    Chain %d: number of elements: %d", j,
		    chain->count);
	    for (k = 0; k < chain->count; k++) {
		elem = chain->elem[k];
		G_debug(4, "      Element %d: type: %d", k, elem->type);
		if (elem->type == S_LINE) {
		    G_debug(4, "        Number of points %d",
			    elem->coor.line.count);
		    for (l = 0; l < elem->coor.line.count; l++) {
			G_debug(4, "        x, y: %f %f",
				elem->coor.line.x[l], elem->coor.line.y[l]);
		    }
		}
		else {
		    G_debug(4, "        arc r = %f", elem->coor.arc.r);
		}
	    }
	}
    }

    fclose(fp);

    return symb;
}
Esempio n. 15
0
File: datum.c Progetto: caomw/grass
struct gpj_datum_transform_list *GPJ_get_datum_transform_by_name(const char
								 *inputname)
{
    FILE *fd;
    char file[GPATH_MAX];
    char buf[1024];
    int line;
    struct gpj_datum_transform_list *current = NULL, *outputlist = NULL;
    struct gpj_datum dstruct;
    int count = 0;

    GPJ_get_datum_by_name(inputname, &dstruct);
    if (dstruct.dx < 99999 && dstruct.dy < 99999 && dstruct.dz < 99999) {
	/* Include the old-style dx dy dz parameters from datum.table at the 
	 * start of the list, unless these have been set to all 99999 to 
	 * indicate only entries in datumtransform.table should be used */
	if (current == NULL)
	    current = outputlist =
		G_malloc(sizeof(struct gpj_datum_transform_list));
	else
	    current = current->next =
		G_malloc(sizeof(struct gpj_datum_transform_list));
	G_asprintf(&(current->params), "towgs84=%.3f,%.3f,%.3f", dstruct.dx,
		   dstruct.dy, dstruct.dz);
	G_asprintf(&(current->where_used), "whole %s region", inputname);
	G_asprintf(&(current->comment),
		   "Default 3-Parameter Transformation (May not be optimum for "
		   "older datums; use this only if no more appropriate options "
		   "are available.)");
	count++;
	current->count = count;
	current->next = NULL;
    }
    GPJ_free_datum(&dstruct);

    /* Now check for additional parameters in datumtransform.table */

    sprintf(file, "%s%s", G_gisbase(), DATUMTRANSFORMTABLE);

    fd = fopen(file, "r");
    if (!fd) {
	G_warning(_("Unable to open datum table file <%s>"), file);
	return outputlist;
    }

    for (line = 1; G_getl2(buf, sizeof(buf), fd); line++) {
	char name[100], params[1024], where_used[1024], comment[1024];

	G_strip(buf);
	if (*buf == '\0' || *buf == '#')
	    continue;

	if (sscanf(buf, "%99s \"%1023[^\"]\" \"%1023[^\"]\" \"%1023[^\"]\"",
		   name, params, where_used, comment) != 4) {
	    G_warning(_("Error in datum table file <%s>, line %d"), file,
		      line);
	    continue;
	}

	if (G_strcasecmp(inputname, name) == 0) {
	    /* If the datum name in this line matches the one we are 
	     * looking for, add an entry to the linked list */
	    if (current == NULL)
		current = outputlist =
		    G_malloc(sizeof(struct gpj_datum_transform_list));
	    else
		current = current->next =
		    G_malloc(sizeof(struct gpj_datum_transform_list));
	    current->params = G_store(params);
	    current->where_used = G_store(where_used);
	    current->comment = G_store(comment);
	    count++;
	    current->count = count;
	    current->next = NULL;
	}
    }

    fclose(fd);

    return outputlist;

}
Esempio n. 16
0
struct ellps_list *read_ellipsoid_table(int fatal)
{
    FILE *fd;
    char file[GPATH_MAX];
    char buf[4096];
    char name[100], descr[1024], buf1[1024], buf2[1024];
    char badlines[1024];
    int line;
    int err;
    struct ellps_list *current = NULL, *outputlist = NULL;
    double a, e2, rf;

    int count = 0;

    sprintf(file, "%s%s", G_gisbase(), ELLIPSOIDTABLE);
    fd = fopen(file, "r");

    if (!fd) {
        (fatal ? G_fatal_error : G_warning)(
            _("Unable to open ellipsoid table file <%s>"), file);
        return NULL;
    }

    err = 0;
    *badlines = 0;
    for (line = 1; G_getl2(buf, sizeof buf, fd); line++) {
        G_strip(buf);
        if (*buf == 0 || *buf == '#')
            continue;

        if (sscanf(buf, "%s  \"%1023[^\"]\" %s %s", name, descr, buf1, buf2)
                != 4) {
            err++;
            sprintf(buf, " %d", line);
            if (*badlines)
                strcat(badlines, ",");
            strcat(badlines, buf);
            continue;
        }


        if (get_a_e2_rf(buf1, buf2, &a, &e2, &rf)
                || get_a_e2_rf(buf2, buf1, &a, &e2, &rf)) {
            if (current == NULL)
                current = outputlist = G_malloc(sizeof(struct ellps_list));
            else
                current = current->next = G_malloc(sizeof(struct ellps_list));
            current->name = G_store(name);
            current->longname = G_store(descr);
            current->a = a;
            current->es = e2;
            current->rf = rf;
            current->next = NULL;
            count++;
        }
        else {
            err++;
            sprintf(buf, " %d", line);
            if (*badlines)
                strcat(badlines, ",");
            strcat(badlines, buf);
            continue;
        }
    }

    fclose(fd);

    if (!err)
        return outputlist;

    (fatal ? G_fatal_error : G_warning)(
        _n(
            ("Line%s of ellipsoid table file <%s> is invalid"),
            ("Lines%s of ellipsoid table file <%s> are invalid"),
            err),
        badlines, file);

    return outputlist;
}
Esempio n. 17
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{
    int n, i;
    int skip;
    const char *cur_mapset, *mapset;
    char **ptr;
    char **tokens;
    int no_tokens;
    FILE *fp;
    char path_buf[GPATH_MAX];
    char *path, *fs;
    int operation, nchoices;
    
    char **mapset_name;
    int nmapsets;
    
    struct GModule *module;    
    struct _opt {
        struct Option *mapset, *op, *fs;
        struct Flag *print, *list, *dialog;
    } opt;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("settings"));
    G_add_keyword(_("search path"));
    module->label = _("Modifies/prints the user's current mapset search path.");
    module->description = _("Affects the user's access to data existing "
                            "under the other mapsets in the current location.");

    opt.mapset = G_define_standard_option(G_OPT_M_MAPSET);
    opt.mapset->required = YES;
    opt.mapset->multiple = YES;
    opt.mapset->description = _("Name(s) of existing mapset(s) to add/remove or set");
    opt.mapset->guisection = _("Search path");
    
    opt.op = G_define_option();
    opt.op->key = "operation";
    opt.op->type = TYPE_STRING;
    opt.op->required = YES;
    opt.op->multiple = NO;
    opt.op->options = "set,add,remove";
    opt.op->description = _("Operation to be performed");
    opt.op->guisection = _("Search path");
    opt.op->answer = "add";
    
    opt.fs = G_define_standard_option(G_OPT_F_SEP);
    opt.fs->label = _("Field separator for printing (-l and -p flags)");
    opt.fs->answer = "space";
    opt.fs->guisection = _("Print");
    
    opt.list = G_define_flag();
    opt.list->key = 'l';
    opt.list->description = _("List all available mapsets in alphabetical order");
    opt.list->guisection = _("Print");
    opt.list->suppress_required = YES;

    opt.print = G_define_flag();
    opt.print->key = 'p';
    opt.print->description = _("Print mapsets in current search path");
    opt.print->guisection = _("Print");
    opt.print->suppress_required = YES;

    opt.dialog = G_define_flag();
    opt.dialog->key = 's';
    opt.dialog->description = _("Launch mapset selection GUI dialog");
    opt.dialog->suppress_required = YES;
    
    path = NULL;
    mapset_name = NULL;
    nmapsets = nchoices = 0;

    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);

    operation = OP_UKN;
    if (opt.mapset->answer && opt.op->answer) {
        switch(opt.op->answer[0]) {
        case 's':
            operation = OP_SET;
            break;
        case 'a':
            operation = OP_ADD;
            break;
        case 'r':
            operation = OP_REM;
            break;
        default:
            G_fatal_error(_("Unknown operation '%s'"), opt.op->answer);
            break;
        }
    }
    
    fs = G_option_to_separator(opt.fs);

    /* list available mapsets */
    if (opt.list->answer) {
        if (opt.print->answer)
            G_warning(_("Flag -%c ignored"), opt.print->key);
        if (opt.dialog->answer)
            G_warning(_("Flag -%c ignored"), opt.dialog->key);
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        mapset_name = get_available_mapsets(&nmapsets);
        list_available_mapsets((const char **)mapset_name, nmapsets, fs);
        exit(EXIT_SUCCESS);
    }

    if (opt.print->answer) {
        if (opt.dialog->answer)
            G_warning(_("Flag -%c ignored"), opt.dialog->key);
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        list_accessible_mapsets(fs);
        exit(EXIT_SUCCESS);
    }
    
    /* show GUI dialog */
    if (opt.dialog->answer) {
        if (opt.mapset->answer)
            G_warning(_("Option <%s> ignored"), opt.mapset->key);
        sprintf(path_buf, "%s/gui/wxpython/modules/mapsets_picker.py", G_gisbase());
        G_spawn(getenv("GRASS_PYTHON"), "mapsets_picker.py", path_buf, NULL);
        exit(EXIT_SUCCESS);
    }

    cur_mapset = G_mapset();
    
    /* modify search path */
    if (operation == OP_SET) {
        int cur_found;
        
        cur_found = FALSE;
        for (ptr = opt.mapset->answers; *ptr != NULL; ptr++) {
            mapset = substitute_mapset(*ptr);
            if (G__mapset_permissions(mapset) < 0)
                G_fatal_error(_("Mapset <%s> not found"), mapset);
            if (strcmp(mapset, cur_mapset) == 0)
                cur_found = TRUE;
            nchoices++;
            append_mapset(&path, mapset);
        }
        if (!cur_found)
            G_warning(_("Current mapset (<%s>) must always included in the search path"),
                      cur_mapset);
    }
    else if (operation == OP_ADD) {
        /* add to existing search path */
        const char *oldname;
        
        if (path) {
            G_free(path);
            path = NULL;
        }

        /* read existing mapsets from SEARCH_PATH */
        for (n = 0; (oldname = G_get_mapset_name(n)); n++)
            append_mapset(&path, oldname);

        /* fetch and add new mapsets from param list */
        for (ptr = opt.mapset->answers; *ptr != NULL; ptr++) {

            mapset = substitute_mapset(*ptr);

            if (G_is_mapset_in_search_path(mapset)) {
                G_message(_("Mapset <%s> already in the path"), mapset);
                continue;
            }
            
            if (G__mapset_permissions(mapset) < 0)
                G_fatal_error(_("Mapset <%s> not found"), mapset);
            else
                G_verbose_message(_("Mapset <%s> added to search path"),
                                  mapset);

            nchoices++;
            append_mapset(&path, mapset);
        }
    }
    else if (operation == OP_REM) {
        /* remove from existing search path */
        const char *oldname;
        int found;
        
        if (path) {
            G_free(path);
            path = NULL;
        }
        
        /* read existing mapsets from SEARCH_PATH */
        for (n = 0; (oldname = G_get_mapset_name(n)); n++) {
            found = FALSE;
            
            for (ptr = opt.mapset->answers; *ptr && !found; ptr++)

                mapset = substitute_mapset(*ptr);
            
                if (strcmp(oldname, mapset) == 0)
                    found = TRUE;
            
                if (found) {
                    if (strcmp(oldname, cur_mapset) == 0)
                        G_warning(_("Current mapset (<%s>) must always included in the search path"),
                                  cur_mapset);
                    else
                        G_verbose_message(_("Mapset <%s> removed from search path"),
                                          oldname);
                    continue;
                }
                
                nchoices++;
                append_mapset(&path, oldname);
        }
    }
    /* stuffem sets nchoices */

    if (nchoices == 0) {
        G_important_message(_("Search path not modified"));
        if (path)
            G_free(path);
        
        if (nmapsets) {
            for(nmapsets--; nmapsets >= 0; nmapsets--)
                G_free(mapset_name[nmapsets]);
            G_free(mapset_name);
        }
        
        exit(EXIT_SUCCESS);
    }
    
    /* note I'm assuming that mapsets cannot have ' 's in them */
    tokens = G_tokenize(path, " ");

    fp = G_fopen_new("", "SEARCH_PATH");
    if (!fp)
        G_fatal_error(_("Unable to open SEARCH_PATH for write"));

    /*
     * make sure current mapset is specified in the list if not add it
     * to the head of the list
     */
    
    skip = 0;
    for (n = 0; n < nchoices; n++)
        if (strcmp(cur_mapset, tokens[n]) == 0) {
            skip = 1;
            break;
        }
    if (!skip) {
        fprintf(fp, "%s\n", cur_mapset);
    }

    /*
     * output the list, removing duplicates
     */

    no_tokens = G_number_of_tokens(tokens);

    for (n = 0; n < no_tokens; n++) {
        skip = 0;
        for (i = n; i < no_tokens; i++) {
            if (i != n) {
                if (strcmp(tokens[i], tokens[n]) == 0)
                    skip = 1;
            }
        }

        if (!skip)
            fprintf(fp, "%s\n", tokens[n]);
    }

    fclose(fp);
    G_free_tokens(tokens);

    if (path)
        G_free(path);

    if (nmapsets) {
        for(nmapsets--; nmapsets >= 0; nmapsets--)
            G_free(mapset_name[nmapsets]);
        G_free(mapset_name);
    }

    exit(EXIT_SUCCESS);
}
Esempio n. 18
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *out_opt, *in_opt;
    struct Flag *z_flag, *circle_flag, *l_flag, *int_flag;
    char buf[2000];

    /* DWG */
    char path[2000];
    short initerror, entset, retval;
    AD_OBJHANDLE pspace, mspace;
    PAD_ENT_HDR adenhd;
    PAD_ENT aden;
    AD_VMADDR entlist;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("import"));
    module->description = _("Converts DWG/DXF to GRASS vector map");

    in_opt = G_define_standard_option(G_OPT_F_INPUT);
    in_opt->description = _("Name of DWG or DXF file");

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    out_opt->required = YES;

    layers_opt = G_define_option();
    layers_opt->key = "layers";
    layers_opt->type = TYPE_STRING;
    layers_opt->required = NO;
    layers_opt->multiple = YES;
    layers_opt->description = _("List of layers to import");

    invert_flag = G_define_flag();
    invert_flag->key = 'i';
    invert_flag->description =
	_("Invert selection by layers (don't import layers in list)");

    z_flag = G_define_flag();
    z_flag->key = 'z';
    z_flag->description = _("Create 3D vector map");

    circle_flag = G_define_flag();
    circle_flag->key = 'c';
    circle_flag->description = _("Write circles as points (centre)");

    l_flag = G_define_flag();
    l_flag->key = 'l';
    l_flag->description = _("List available layers and exit");

    int_flag = G_define_flag();
    int_flag->key = 'n';
    int_flag->description = _("Use numeric type for attribute \"layer\"");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    db_init_string(&sql);
    db_init_string(&str);
    adenhd = (PAD_ENT_HDR) G_malloc(sizeof(AD_ENT_HDR));
    aden = (PAD_ENT) G_malloc(sizeof(AD_ENT));
    Layer = (PAD_LAY) G_malloc(sizeof(AD_LAY));
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    Block = NULL;

    atrans = 20;		/* nested, recursive levels */
    Trans = (TRANS *) G_malloc(atrans * sizeof(TRANS));

    /* Init OpenDWG */
    sprintf(path, "%s/etc/adinit.dat", G_gisbase());
    if (!adInitAd2(path, &initerror)) {
	sprintf(buf, _("Unable to initialize OpenDWG Toolkit, error: %d: %s."),
		initerror, adErrorStr(initerror));
	if (initerror == AD_UNABLE_TO_OPEN_INIT_FILE)
	    sprintf(buf, _("%s Cannot open %s"), buf, path);
	G_fatal_error(buf);
    }
    adSetupDwgRead();
    adSetupDxfRead();

    /* Open input file */
    if ((dwghandle = adLoadFile(in_opt->answer, AD_PRELOAD_ALL, 1)) == NULL) {
	G_fatal_error(_("Unable to open input file <%s>. Error %d: %s"),
		      in_opt->answer, adError(),
		      adErrorStr(adError()));
    }

    if (l_flag->answer) {	/* List layers */
	PAD_TB adtb;
	AD_DWGHDR adhd;
	int i;
	char on, frozen, vpfrozen, locked;

	adtb = (PAD_TB) G_malloc(sizeof(AD_TB));

	G_debug(2, "%d layers", (int)adNumLayers(dwghandle));
	adReadHeaderBlock(dwghandle, &adhd);
	adStartLayerGet(dwghandle);

	fprintf(stdout, "%d layers:\n", (int)adNumLayers(dwghandle));
	for (i = 0; i < (int)adNumLayers(dwghandle); i++) {
	    adGetLayer(dwghandle, &(adtb->lay));
	    if (!adtb->lay.purgedflag) {
		fprintf(stdout, "%s COLOR %d, ", adtb->lay.name,
			adtb->lay.color);
	    }
	    adGetLayerState(dwghandle, adtb->lay.objhandle, &on, &frozen,
			    &vpfrozen, &locked);
	    if (on)
		fprintf(stdout, "ON, ");
	    else
		fprintf(stdout, "OFF, ");
	    if (frozen)
		fprintf(stdout, "FROZEN, ");
	    else
		fprintf(stdout, "THAWED, ");
	    if (vpfrozen)
		fprintf(stdout, "VPFROZEN, ");
	    else
		fprintf(stdout, "VPTHAWED, ");
	    if (locked)
		fprintf(stdout, "LOCKED\n");
	    else
		fprintf(stdout, "UNLOCKED\n");
	}
	adCloseFile(dwghandle);
	adCloseAd2();
	exit(EXIT_SUCCESS);
    }


    /* open output vector */
    if (Vect_open_new(&Map, out_opt->answer, z_flag->answer) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer);

    Vect_hist_command(&Map);

    /* Add DB link */
    Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Map, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database,
			Fi->driver);

    driver =
	db_start_driver_open_database(Fi->driver,
				      Vect_subst_var(Fi->database, &Map));
    if (driver == NULL) {
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Vect_subst_var(Fi->database, &Map), Fi->driver);
    }
    db_set_error_handler_driver(driver);

    db_begin_transaction(driver);

    /* Create table */
    if (int_flag->answer) {	/* List layers */
	sprintf(buf,
		"create table %s ( cat integer, entity_name varchar(20), color int, weight int, "
		"layer real, block varchar(100), txt varchar(100) )",
		Fi->table);

    }
    else {
	sprintf(buf,
		"create table %s ( cat integer, entity_name varchar(20), color int, weight int, "
		"layer varchar(100), block varchar(100), txt varchar(100) )",
		Fi->table);
    }
    db_set_string(&sql, buf);
    G_debug(3, db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK) {
	db_close_database(driver);
	db_shutdown_driver(driver);
	G_fatal_error(_("Unable to create table: '%s'"), db_get_string(&sql));
    }

    if (db_create_index2(driver, Fi->table, GV_KEY_COLUMN) != DB_OK)
	G_warning(_("Unable to create index for table <%s>, key <%s>"),
		  Fi->table, GV_KEY_COLUMN);

    if (db_grant_on_table
	(driver, Fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
	G_fatal_error(_("Unable to grant privileges on table <%s>"),
		      Fi->table);

    cat = 1;
    n_elements = n_skipped = 0;
    /* Write each entity. Some entities may be composed by other entities (like INSERT or BLOCK) */
    /* Set transformation for first (index 0) level */
    Trans[0].dx = Trans[0].dy = Trans[0].dz = 0;
    Trans[0].xscale = Trans[0].yscale = Trans[0].zscale = 1;
    Trans[0].rotang = 0;
    if (adGetBlockHandle(dwghandle, pspace, AD_PAPERSPACE_HANDLE)) {
	entlist = adEntityList(dwghandle, pspace);
	adStartEntityGet(entlist);
	for (entset = 0; entset < 2; entset++) {
	    do {
		if (!(retval = adGetEntity(entlist, adenhd, aden)))
		    continue;
		wrentity(adenhd, aden, 0, entlist, circle_flag->answer);
	    } while (retval == 1);
	    if (entset == 0) {
		if (adGetBlockHandle(dwghandle, mspace, AD_MODELSPACE_HANDLE)) {
		    entlist = adEntityList(dwghandle, mspace);
		    adStartEntityGet(entlist);
		}
	    }
	}
    }

    db_commit_transaction(driver);
    db_close_database_shutdown_driver(driver);

    adCloseFile(dwghandle);
    adCloseAd2();

    Vect_build(&Map, stderr);
    Vect_close(&Map);
    
    if (n_skipped > 0)
	G_message(_("%d elements skipped (layer name was not in list)"),
		  n_skipped);
    
    G_done_msg(_("%d elements processed"), n_elements);

    exit(EXIT_SUCCESS);
}
Esempio n. 19
0
/*!
  \brief Read dbmscap
  
  dbmscap file was used in grass5.0 but it is not used in
  grass5.7 until we find it necessary. All code for dbmscap
  file is commented here. 
  
  Instead of in dbmscap file db_read_dbmscap() searches 
  for available dbmi drivers in $(GISBASE)/driver/db/

  \return pointer to dbDbmscap
*/
dbDbmscap *db_read_dbmscap(void)
{
    /*  
       FILE *fd;
       char *file;
       char name[1024];
       char startup[1024];
       char comment[1024];
       int  line;
     */
    char *dirpath;
    DIR *dir;
    struct dirent *ent;

    dbDbmscap *list = NULL;

    /* START OF OLD CODE FOR dbmscap FILE - NOT USED, BUT KEEP IT FOR FUTURE */
#if 0
    /* get the full name of the dbmscap file */

    file = db_dbmscap_filename();
    if (file == NULL)
	return (dbDbmscap *) NULL;


    /* open the dbmscap file */

    fd = fopen(file, "r");
    if (fd == NULL) {
	db_syserror(file);
	return (dbDbmscap *) NULL;
    }


    /* find all valid entries
     * blank lines and lines with # as first non blank char are ignored
     * format is:
     *   driver name:startup command:comment
     */

    for (line = 1; fgets(buf, sizeof buf, fd); line++) {
	if (sscanf(buf, "%1s", comment) != 1 || *comment == '#')
	    continue;
	if (sscanf(buf, "%[^:]:%[^:]:%[^:\n]", name, startup, comment) == 3)
	    add_entry(&list, name, startup, comment);
	else if (sscanf(buf, "%[^:]:%[^:\n]", name, startup) == 2)
	    add_entry(&list, name, startup, "");
	else {
	    fprintf(stderr, "%s: line %d: invalid entry\n", file, line);
	    fprintf(stderr, "%d:%s\n", line, buf);
	}
	if (list == NULL)
	    break;
    }
    fclose(fd);
#endif
    /* END OF OLD CODE FOR dbmscap FILE */

    /* START OF NEW CODE FOR SEARCH IN $(GISBASE)/driver/db/ */

    /* opend db drivers directory */
#ifdef __MINGW32__
    dirpath = G_malloc(strlen("\\driver\\db\\") + strlen(G_gisbase()) + 1);
    sprintf(dirpath, "%s\\driver\\db\\", G_gisbase());
    G_convert_dirseps_to_host(dirpath);
#else
    G_asprintf(&dirpath, "%s/driver/db/", G_gisbase());
#endif

    G_debug(2, "dbDbmscap(): opendir [%s]", dirpath);
    dir = opendir(dirpath);
    if (dir == NULL) {
	db_syserror("Cannot open drivers directory");
	return (dbDbmscap *) NULL;
    }
    G_free(dirpath);

    /* read all drivers */
    while ((ent = readdir(dir))) {
	char *name;

	if ((strcmp(ent->d_name, ".") == 0)
	    || (strcmp(ent->d_name, "..") == 0))
	    continue;

	/* Remove '.exe' from name (windows extension) */
	name = G_str_replace(ent->d_name, ".exe", "");

#ifdef __MINGW32__
	dirpath = G_malloc(strlen("\\driver\\db\\")
			   + strlen(G_gisbase()) + strlen(ent->d_name) + 1);
	sprintf(dirpath, "%s\\driver\\db\\%s", G_gisbase(), ent->d_name);
	G_convert_dirseps_to_host(dirpath);
#else
	G_asprintf(&dirpath, "%s/driver/db/%s", G_gisbase(), ent->d_name);
#endif
	add_entry(&list, name, dirpath, "");
	G_free(name);
	G_free(dirpath);
    }

    closedir(dir);

    return list;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
    struct Flag *tostdout, *overwrite;
    struct Option *extradirs;
    struct GModule *module;

    FILE *outstream;
    char *fontcapfile;
    struct stat status;
    int i;

    G_set_program_name(argv[0]);
    G_no_gisinit();
    G_set_gisrc_mode(G_GISRC_MODE_MEMORY);

    module = G_define_module();
    module->keywords = "general";
    module->description =
	"Generates the font configuration file by scanning various directories "
	"for fonts";

    overwrite = G_define_flag();
    overwrite->key = 'o';
    overwrite->description =
	"Overwrite font configuration file if already existing";

    tostdout = G_define_flag();
    tostdout->key = 's';
    tostdout->description =
	"Write font configuration file to standard output instead of "
	"$GISBASE/etc";

    extradirs = G_define_option();
    extradirs->key = "extradirs";
    extradirs->type = TYPE_STRING;
    extradirs->required = NO;
    extradirs->description =
	"Comma-separated list of extra directories to scan for "
	"Freetype-compatible fonts as well as the defaults (see documentation)";

    if (argc > 1 && G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (!tostdout->answer) {
	const char *gisbase = G_gisbase();
	const char *alt_file = getenv("GRASS_FONT_CAP");

	if (alt_file)
	    fontcapfile = G_store(alt_file);
	else
	    G_asprintf(&fontcapfile, "%s/etc/fontcap", gisbase);

	if (!stat(fontcapfile, &status)) {	/* File exists? */
	    if (!overwrite->answer)
		G_fatal_error
		    ("Fontcap file %s already exists; use -%c flag if you "
		     "wish to overwrite it", fontcapfile, overwrite->key);
	}
    }

    searchdirs = NULL;
    numsearchdirs = 0;

    /* Prepare list of directories to search */
    if (extradirs->answer) {
#ifndef HAVE_FT2BUILD_H
	G_warning("This GRASS installation was compiled without Freetype support, extradirs parameter ignored");
#endif
	char *str = G_store(extradirs->answer);

	while ((str = strtok(str, ","))) {
	    add_search_dir(str);
	    str = NULL;
	}
    }
    i = -1;
    while (standarddirs[++i])
	add_search_dir(standarddirs[i]);

    totalfonts = maxfonts = 0;
    fontcap = NULL;

    find_stroke_fonts();
    find_freetype_fonts();

    qsort(fontcap, totalfonts, sizeof(struct GFONT_CAP), compare_fonts);

    if (tostdout->answer)
	outstream = stdout;
    else {
	outstream = fopen(fontcapfile, "w");
	if (outstream == NULL)
	    G_fatal_error("Cannot open %s for writing: %s", fontcapfile,
			  strerror(errno));
    }

    for (i = 0; i < totalfonts; i++)
	fprintf(outstream, "%s|%s|%d|%s|%d|%s|\n", fontcap[i].name,
		fontcap[i].longname, fontcap[i].type, fontcap[i].path,
		fontcap[i].index, fontcap[i].encoding);

    fclose(outstream);

    exit(EXIT_SUCCESS);

}
Esempio n. 21
0
int GPJ_osr_to_grass(struct Cell_head *cellhd, struct Key_Value **projinfo,
		     struct Key_Value **projunits, OGRSpatialReferenceH hSRS,
		     int datumtrans)
{
    struct Key_Value *temp_projinfo;
    char *pszProj4 = NULL, *pszRemaining;
    char *pszProj = NULL;
    char *datum = NULL;
    struct gpj_datum dstruct;

    if (hSRS == NULL)
	goto default_to_xy;

    /* Set finder function for locating OGR csv co-ordinate system tables */
    SetCSVFilenameHook(GPJ_set_csv_loc);

    /* Hopefully this doesn't do any harm if it wasn't in ESRI format
     * to start with... */
    OSRMorphFromESRI(hSRS);

    /* -------------------------------------------------------------------- */
    /*      Set cellhd for well known coordinate systems.                   */
    /* -------------------------------------------------------------------- */
    if (!OSRIsGeographic(hSRS) && !OSRIsProjected(hSRS))
	goto default_to_xy;

    if (cellhd) {
	int bNorth;

	if (OSRIsGeographic(hSRS)) {
	    cellhd->proj = PROJECTION_LL;
	    cellhd->zone = 0;
	}
	else if (OSRGetUTMZone(hSRS, &bNorth) != 0) {
	    cellhd->proj = PROJECTION_UTM;
	    cellhd->zone = OSRGetUTMZone(hSRS, &bNorth);
	    if (!bNorth)
		cellhd->zone *= -1;
	}
	else {
	    cellhd->proj = PROJECTION_OTHER;
	    cellhd->zone = 0;
	}
    }

    /* -------------------------------------------------------------------- */
    /*      Get the coordinate system definition in PROJ.4 format.          */
    /* -------------------------------------------------------------------- */
    if (OSRExportToProj4(hSRS, &pszProj4) != OGRERR_NONE)
	goto default_to_xy;

    /* -------------------------------------------------------------------- */
    /*      Parse the PROJ.4 string into key/value pairs.  Do a bit of      */
    /*      extra work to "GRASSify" the result.                            */
    /* -------------------------------------------------------------------- */
    temp_projinfo = G_create_key_value();

    /* Create "local" copy of proj4 string so we can modify and free it
     * using GRASS functions */
    pszRemaining = G_store(pszProj4);
    CPLFree(pszProj4);
    pszProj4 = pszRemaining;
    while ((pszRemaining = strstr(pszRemaining, "+")) != NULL) {
	char *pszToken, *pszValue;

	pszRemaining++;

	/* Advance pszRemaining to end of this token[=value] pair */
	pszToken = pszRemaining;
	while (*pszRemaining != ' ' && *pszRemaining != '\0')
	    pszRemaining++;

	if (*pszRemaining == ' ') {
	    *pszRemaining = '\0';
	    pszRemaining++;
	}

	/* parse token, and value */
	if (strstr(pszToken, "=") != NULL) {
	    pszValue = strstr(pszToken, "=");
	    *pszValue = '\0';
	    pszValue++;
	}
	else
	    pszValue = "defined";


	if (G_strcasecmp(pszToken, "proj") == 0) {
	    /* The ll projection is known as longlat in PROJ.4 */
	    if (G_strcasecmp(pszValue, "longlat") == 0)
		pszValue = "ll";

	    pszProj = pszValue;
	    continue;
	}

	/* Ellipsoid and datum handled separately below */
	if (G_strcasecmp(pszToken, "ellps") == 0
	    || G_strcasecmp(pszToken, "a") == 0
	    || G_strcasecmp(pszToken, "b") == 0
	    || G_strcasecmp(pszToken, "es") == 0
	    || G_strcasecmp(pszToken, "rf") == 0
	    || G_strcasecmp(pszToken, "datum") == 0)
	    continue;

	/* We will handle units separately */
	if (G_strcasecmp(pszToken, "to_meter") == 0
	    || G_strcasecmp(pszToken, "units") == 0)
	    continue;

	G_set_key_value(pszToken, pszValue, temp_projinfo);
    }

    *projinfo = G_create_key_value();

    /* -------------------------------------------------------------------- */
    /*      Derive the user name for the projection.                        */
    /* -------------------------------------------------------------------- */
    if (pszProj) {
	char path[4095];
	char name[80];

	sprintf(path, "%s/etc/projections", G_gisbase());
	if (G_lookup_key_value_from_file(path, pszProj, name, sizeof(name)) >
	    0)
	    G_set_key_value("name", name, *projinfo);
	else
	    G_set_key_value("name", pszProj, *projinfo);

	G_set_key_value("proj", pszProj, *projinfo);
    }
    else
	G_warning(_("No projection name! Projection parameters likely to be meaningless."));


    /* -------------------------------------------------------------------- */
    /*      Find the GRASS datum name and choose parameters either          */
    /*      interactively or not.                                           */
    /* -------------------------------------------------------------------- */

    {
	const char *pszDatumNameConst = OSRGetAttrValue(hSRS, "DATUM", 0);
	struct datum_list *list, *listhead;
	char *dum1, *dum2, *pszDatumName;
	int paramspresent =
	    GPJ__get_datum_params(temp_projinfo, &dum1, &dum2);

	if (pszDatumNameConst) {
	    /* Need to make a new copy of the string so we don't mess
	     * around with the memory inside the OGRSpatialReferenceH? */

	    pszDatumName = G_store(pszDatumNameConst);
	    DatumNameMassage(&pszDatumName);

	    list = listhead = read_datum_table();

	    while (list != NULL) {
		if (G_strcasecmp(pszDatumName, list->longname) == 0) {
		    datum = G_store(list->name);
		    break;
		}
		list = list->next;
	    }
	    free_datum_list(listhead);

	    if (datum == NULL) {
		if (paramspresent < 2)
		    /* Only give warning if no parameters present */
		    G_warning(_("Datum <%s> not recognised by GRASS and no parameters found"),
			      pszDatumName);
	    }
	    else {
		G_set_key_value("datum", datum, *projinfo);

		if (paramspresent < 2) {
		    /* If no datum parameters were imported from the OSR
		     * object then we should use the set specified by datumtrans */
		    char *params, *chosenparams = NULL;
		    int paramsets;

		    paramsets =
			GPJ_get_default_datum_params_by_name(datum, &params);

		    if (paramsets < 0)
			G_warning(_("Datum <%s> apparently recognised by GRASS but no parameters found. "
				   "You may want to look into this."), datum);
		    else if (datumtrans > paramsets) {

			G_warning(_("Invalid transformation number %d; valid range is 1 to %d. "
				   "Leaving datum transform parameters unspecified."),
				  datumtrans, paramsets);
			datumtrans = 0;
		    }

		    if (paramsets > 0) {
			struct gpj_datum_transform_list *list, *old;

			list = GPJ_get_datum_transform_by_name(datum);

			if (list != NULL) {
			    do {
				if (list->count == datumtrans)
				    chosenparams = G_store(list->params);
				old = list;
				list = list->next;
				GPJ_free_datum_transform(old);
			    } while (list != NULL);
			}
		    }

		    if (chosenparams != NULL) {
			char *paramkey, *paramvalue;

			paramkey = strtok(chosenparams, "=");
			paramvalue = chosenparams + strlen(paramkey) + 1;
			G_set_key_value(paramkey, paramvalue, *projinfo);
			G_free(chosenparams);
		    }

		    if (paramsets > 0)
			G_free(params);
		}

	    }
	    G_free(pszDatumName);
	}
    }

    /* -------------------------------------------------------------------- */
    /*   Determine an appropriate GRASS ellipsoid name if possible, or      */
    /*   else just put a and es values into PROJ_INFO                       */
    /* -------------------------------------------------------------------- */

    if ((datum != NULL) && (GPJ_get_datum_by_name(datum, &dstruct) > 0)) {
	/* Use ellps name associated with datum */
	G_set_key_value("ellps", dstruct.ellps, *projinfo);
	GPJ_free_datum(&dstruct);
	G_free(datum);
    }
    else {
	/* If we can't determine the ellipsoid from the datum, derive it
	 * directly from "SPHEROID" parameters in WKT */
	const char *pszSemiMajor = OSRGetAttrValue(hSRS, "SPHEROID", 1);
	const char *pszInvFlat = OSRGetAttrValue(hSRS, "SPHEROID", 2);

	if (pszSemiMajor != NULL && pszInvFlat != NULL) {
	    char *ellps = NULL;
	    struct ellps_list *list, *listhead;
	    double a = atof(pszSemiMajor), invflat = atof(pszInvFlat), flat;
	    double es;

	    /* Allow for incorrect WKT describing a sphere where InvFlat 
	     * is given as 0 rather than inf */
	    if (invflat > 0)
		flat = 1 / invflat;
	    else
		flat = 0;

	    es = flat * (2.0 - flat);

	    list = listhead = read_ellipsoid_table(0);

	    while (list != NULL) {
		/* Try and match a and es against GRASS defined ellipsoids;
		 * accept first one that matches. These numbers were found
		 * by trial and error and could be fine-tuned, or possibly
		 * a direct comparison of IEEE floating point values used. */
		if ((a == list->a || fabs(a - list->a) < 0.1 || fabs(1 - a / list->a) < 0.0000001) && ((es == 0 && list->es == 0) ||	/* Special case for sphere */
												       (invflat == list->rf || fabs(invflat - list->rf) < 0.0000001))) {
		    ellps = G_store(list->name);
		    break;
		}
		list = list->next;
	    }
	    if (listhead != NULL)
		free_ellps_list(listhead);

	    if (ellps == NULL) {
		/* If we weren't able to find a matching ellps name, set
		 * a and es values directly from WKT-derived data */
		char es_str[100];

		G_set_key_value("a", (char *)pszSemiMajor, *projinfo);

		sprintf(es_str, "%.16g", es);
		G_set_key_value("es", es_str, *projinfo);
	    }
	    else {
		/* else specify the GRASS ellps name for readability */
		G_set_key_value("ellps", ellps, *projinfo);
		G_free(ellps);
	    }

	}

    }

    /* -------------------------------------------------------------------- */
    /*      Finally append the detailed projection parameters to the end    */
    /* -------------------------------------------------------------------- */

    {
	int i;

	for (i = 0; i < temp_projinfo->nitems; i++)
	    G_set_key_value(temp_projinfo->key[i],
			    temp_projinfo->value[i], *projinfo);

	G_free_key_value(temp_projinfo);
    }

    G_free(pszProj4);

    /* -------------------------------------------------------------------- */
    /*      Set the linear units.                                           */
    /* -------------------------------------------------------------------- */
    *projunits = G_create_key_value();

    if (OSRIsGeographic(hSRS)) {
	/* We assume degrees ... someday we will be wrong! */
	G_set_key_value("unit", "degree", *projunits);
	G_set_key_value("units", "degrees", *projunits);
	G_set_key_value("meters", "1.0", *projunits);
    }
    else {
	char szFormatBuf[256];
	char *pszUnitsName = NULL;
	double dfToMeters;
	char *pszUnitsPlural, *pszStringEnd;

	dfToMeters = OSRGetLinearUnits(hSRS, &pszUnitsName);

	/* Workaround for the most obvious case when unit name is unknown */
	if ((G_strcasecmp(pszUnitsName, "unknown") == 0) &&
	    (dfToMeters == 1.))
	    G_asprintf(&pszUnitsName, "meter");

	G_set_key_value("unit", pszUnitsName, *projunits);

	/* Attempt at plural formation (WKT format doesn't store plural
	 * form of unit name) */
	pszUnitsPlural = G_malloc(strlen(pszUnitsName) + 3);
	strcpy(pszUnitsPlural, pszUnitsName);
	pszStringEnd = pszUnitsPlural + strlen(pszUnitsPlural) - 4;
	if (G_strcasecmp(pszStringEnd, "foot") == 0) {
	    /* Special case for foot - change two o's to e's */
	    pszStringEnd[1] = 'e';
	    pszStringEnd[2] = 'e';
	}
	else if (G_strcasecmp(pszStringEnd, "inch") == 0) {
	    /* Special case for inch - add es */
	    pszStringEnd[4] = 'e';
	    pszStringEnd[5] = 's';
	    pszStringEnd[6] = '\0';
	}
	else {
	    /* For anything else add an s at the end */
	    pszStringEnd[4] = 's';
	    pszStringEnd[5] = '\0';
	}

	G_set_key_value("units", pszUnitsPlural, *projunits);
	G_free(pszUnitsPlural);

	sprintf(szFormatBuf, "%.16g", dfToMeters);
	G_set_key_value("meters", szFormatBuf, *projunits);

    }

    return 2;

    /* -------------------------------------------------------------------- */
    /*      Fallback to returning an ungeoreferenced definition.            */
    /* -------------------------------------------------------------------- */
  default_to_xy:
    if (cellhd != NULL) {
	cellhd->proj = PROJECTION_XY;
	cellhd->zone = 0;
    }

    *projinfo = NULL;
    *projunits = NULL;

    return 1;
}
Esempio n. 22
0
/*!
  \brief Read ellipsoid table

  \param fatal non-zero value for G_fatal_error(), otherwise
  G_warning() is used

  \return 1 on sucess
  \return 0 on error
*/
int G_read_ellipsoid_table(int fatal)
{
    FILE *fd;
    char file[GPATH_MAX];
    char buf[1024];
    char badlines[256];
    int line;
    int err;

    if (G_is_initialized(&table.initialized))
	return 1;

    sprintf(file, "%s/etc/proj/ellipse.table", G_gisbase());
    fd = fopen(file, "r");

    if (fd == NULL) {
	(fatal ? G_fatal_error : G_warning)(_("Unable to open ellipsoid table file <%s>"), file);
	G_initialize_done(&table.initialized);
	return 0;
    }

    err = 0;
    *badlines = 0;
    for (line = 1; G_getl2(buf, sizeof buf, fd); line++) {
	char name[100], descr[100], buf1[100], buf2[100];
	struct ellipse *e;

	G_strip(buf);
	if (*buf == 0 || *buf == '#')
	    continue;

	if (sscanf(buf, "%s  \"%99[^\"]\" %s %s", name, descr, buf1, buf2) != 4) {
	    err++;
	    sprintf(buf, " %d", line);
	    if (*badlines)
		strcat(badlines, ",");
	    strcat(badlines, buf);
	    continue;
	}

	if (table.count >= table.size) {
	    table.size += 60;
	    table.ellipses = G_realloc(table.ellipses, table.size * sizeof(struct ellipse));
	}

	e = &table.ellipses[table.count];

	e->name = G_store(name);
	e->descr = G_store(descr);

	if (get_a_e2_f(buf1, buf2, &e->a, &e->e2, &e->f) ||
	    get_a_e2_f(buf2, buf1, &e->a, &e->e2, &e->f))
	    table.count++;
	else {
	    err++;
	    sprintf(buf, " %d", line);
	    if (*badlines)
		strcat(badlines, ",");
	    strcat(badlines, buf);
	    continue;
	}
    }

    fclose(fd);

    if (!err) {
	/* over correct typed version */
	qsort(table.ellipses, table.count, sizeof(struct ellipse), compare_ellipse_names);
	G_initialize_done(&table.initialized);
	return 1;
    }

    (fatal ? G_fatal_error : G_warning)(
	_n(
	("Line%s of ellipsoid table file <%s> is invalid"),
        ("Lines%s of ellipsoid table file <%s> are invalid"),
        err), 
	badlines, file);

    G_initialize_done(&table.initialized);

    return 0;
}
Esempio n. 23
0
struct proj_parm *get_proj_parms(const char *arg)
{
    char buf[4096];
    struct proj_parm *parm_table = NULL;
    int parm_num = 0;
    int parm_max = 0;
    char *data;
    int done;
    FILE *fp;

    sprintf(buf, "%s/etc/proj/parms.table", G_gisbase());

    fp = fopen(buf, "r");
    if (!fp)
	return NULL;

    for (data = NULL; !data;) {
	char *p;

	if (!G_getl2(buf, sizeof(buf), fp))
	    break;

	for (p = buf; *p && *p != ':'; p++) ;

	if (*p != ':')
	    break;

	*p++ = '\0';

	if (G_strcasecmp(buf, arg) != 0)
	    continue;

	for (; *p && *p != ':'; p++) ;

	if (*p != ':')
	    break;

	*p++ = '\0';

	data = p;
    }

    fclose(fp);

    if (!data)
	return NULL;

    for (done = 0; !done;) {
	char name[16], ask[8], dfl[32];
	struct proj_parm *parm;
	char *p;

	for (p = data; *p && *p != ';'; p++) ;

	if (*p == ';')
	    *p++ = '\0';
	else
	    done = 1;

	if (sscanf(data, "%[^=]=%[^,],%s", name, ask, dfl) != 3) {
	    data = p;
	    continue;
	}

	data = p;

	if (parm_num + 1 >= parm_max) {
	    parm_max += 16;
	    parm_table =
		G_realloc(parm_table, parm_max * sizeof(struct proj_parm));
	}

	parm = &parm_table[parm_num++];

	parm->name = G_store(name);

	if (strcmp(ask, "ask") == 0)
	    parm->ask = 1;
	else if (strcmp(ask, "noask") == 0)
	    parm->ask = 0;
	else {
	    parm->ask = 1;
	    G_warning(_("Unrecognized 'ask' value in parms.table: %s"),
		      ask);
	}

	if (strcmp(dfl, "nodfl") == 0)
	    parm->def_exists = 0;
	else if (sscanf(dfl, "%lf", &parm->deflt) == 1)
	    parm->def_exists = 1;
	else {
	    parm->def_exists = 0;
	    G_warning(_("Unrecognized default value in parms.table: %s"),
		      dfl);
	}
    }

    parm_table[parm_num].name = NULL;

    return parm_table;
}
Esempio n. 24
0
/* adopted from r.colors */
char *icon_files(void)
{
    char **list, *ret;
    char buf[GNAME_MAX], path[GPATH_MAX], path_i[GPATH_MAX];
    int i, count;
    size_t len;
    DIR *dir, *dir_i;
    struct dirent *d, *d_i;

    list = NULL;
    len = 0;
    sprintf(path, "%s/etc/symbol", G_gisbase());

    dir = opendir(path);
    if (!dir)
	return NULL;

    count = 0;
    
    /* loop over etc/symbol */
    while ((d = readdir(dir))) {
	if (d->d_name[0] == '.')
	    continue;

	sprintf(path_i, "%s/etc/symbol/%s", G_gisbase(), d->d_name);
	dir_i = opendir(path_i);

	if (!dir_i)
	    continue;

	/* loop over each directory in etc/symbols */
	while ((d_i = readdir(dir_i))) {
	    if (d_i->d_name[0] == '.')
		continue;
	    
	    list = G_realloc(list, (count + 1) * sizeof(char *));
	    
	    sprintf(buf, "%s/%s", d->d_name, d_i->d_name);
	    list[count++] = G_store(buf);
	    
	    len += strlen(d->d_name) + strlen(d_i->d_name) + 2; /* '/' + ',' */
	}

	closedir(dir_i);
    }

    closedir(dir);

    qsort(list, count, sizeof(char *), cmp);
    
    if (len > 0) {
	ret = G_malloc((len + 1) * sizeof(char)); /* \0 */
	*ret = '\0';
	for (i = 0; i < count; i++) {
	    if (i > 0)
		strcat(ret, ",");
	    strcat(ret, list[i]);
	    G_free(list[i]);
	}
	G_free(list);
    }
    else {
	ret = G_store("");
    }
    
    return ret;
}
Esempio n. 25
0
int read_eps(double e, double n)
{
    char buf[1024], eps_file[GPATH_MAX];
    char *eps;
    double scale, rotate;
    int have_eps;
    char *key, *data;
    int masked;
    FILE *fp;

    static char *help[] = {
	"epsfile EPS file",
	"scale   #",
	"rotate   #",
	"masked [y|n]",
	""
    };

    scale = 1.0;
    rotate = 0.0;
    have_eps = 0;
    masked = 0;

    while (input(2, buf, help)) {
	if (!key_data(buf, &key, &data))
	    continue;

	if (KEY("masked")) {
	    masked = yesno(key, data);
	    if (masked)
		PS.mask_needed = 1;
	    continue;
	}

	if (KEY("epsfile")) {
	    G_chop(data);

	    /* expand "$GISBASE" if present */
	    if (strncmp(data, "$GISBASE", 8) != 0)
		strcpy(eps_file, data);
	    else {
		strcpy(eps_file, G_gisbase());
		data += 8;
		strcat(eps_file, data);
	    }

	    eps = G_store(eps_file);

	    /* test if file is accessible */
	    if ((fp = fopen(eps, "r")) == NULL)
		error(key, data, _("Can't open eps file"));

	    have_eps = 1;
	    fclose(fp);
	    continue;
	}

	if (KEY("scale")) {
	    if (sscanf(data, "%lf", &scale) != 1 || scale <= 0.0) {
		scale = 1.0;
		error(key, data, "illegal scale request");
	    }
	    continue;
	}

	if (KEY("rotate")) {
	    if (sscanf(data, "%lf", &rotate) != 1) {
		rotate = 0.0;
		error(key, data, "illegal rotate request");
	    }
	    continue;
	}

	error(key, data, "illegal eps request");
    }
    if (have_eps) {
	sprintf(buf, "E %d %f %f %f %f %s", masked, e, n, scale, rotate, eps);
    }
    add_to_plfile(buf);

    return 0;
}
Esempio n. 26
0
/* in addition there seem to be some useful user options here which are not currently available from the main parser */
int com_line_Gwater(INPUT * input, OUTPUT * output)
{
    struct Cell_head *window;
    char map_layer[48], buf[100], *prog_name, *mapset;
    double d;
    int i;

    window = &(output->window);
    if (0 == G_yes("Continue?", 1))
	exit(EXIT_SUCCESS);

    input->haf_name = (char *)G_calloc(40, sizeof(char));
    input->accum_name = (char *)G_calloc(40, sizeof(char));

    G_message(_("\nThis set of questions will organize the command line for the"));
    G_message(_("%s program to run properly for your application."),
	      NON_NAME);
    G_message(_("The first question is whether you want %s to run"),
	      NON_NAME);
    G_message(_("in its fast mode or its slow mode.  If you run %s"),
	      NON_NAME);
    G_message(_("in the fast mode, the computer will finish about 10 times faster"));
    G_message(_("than in the slow mode, but will not allow other programs to run"));
    G_message(_("at the same time.  The fast mode also places all of the data into"));
    G_message(_("RAM, which limits the size of window that can be run.  The slow"));
    G_message(_("mode uses disk space in the same hard disk partition as where GRASS is"));
    G_message(_("stored.  Thus, if the program does not work in the slow mode, you will"));
    G_message(_("need to remove unnecessary files from that partition.  The slow mode"));
    G_message(_("will allow other processes to run concurrently with %s.\n"),
	      NON_NAME);

    sprintf(buf, "Do you want to use the fast mode of %s?", NON_NAME);
    input->com_line_ram = input->com_line_seg = NULL;
    input->fast = 0;
    input->slow = 0;
    if (G_yes(buf, 1)) {
	input->fast = 1;
	input->com_line_ram = (char *)G_calloc(400, sizeof(char));
	prog_name = G_store(RAM_NAME);
	sprintf(input->com_line_ram,
		"\"%s/etc/water/%s\"", G_gisbase(), RAM_NAME);
	fprintf(stderr,
		"\nIf there is not enough ram for the fast mode (%s) to run,\n",
		RAM_NAME);
	sprintf(buf, "should the slow mode (%s) be run instead?", SEG_NAME);
	if (G_yes(buf, 1)) {
	    input->slow = 1;
	    input->com_line_seg = (char *)G_calloc(400, sizeof(char));
	    sprintf(input->com_line_seg,
		    "\"%s/etc/water/%s\"", G_gisbase(), SEG_NAME);
	}
    }
    else {
	input->slow = 1;
	prog_name = G_store(SEG_NAME);
	input->com_line_seg = (char *)G_calloc(400, sizeof(char));
	sprintf(input->com_line_seg,
		"\"%s/etc/water/%s\"", G_gisbase(), SEG_NAME);
    }

    G_message(_("\nIf you hit <return> by itself for the next question, this"));
    G_message(_("program will terminate."));

    mapset = G_ask_old("What is the name of the elevation map layer?",
		       map_layer, "cell", "cell");
    if (!mapset)
	exit(EXIT_FAILURE);
    if (input->fast)
	com_line_add(&(input->com_line_ram), " el=", map_layer, mapset);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " el=", map_layer, mapset);

    G_message(_("\nOne of the options for %s is a `depression map'.  A"),
	      prog_name);
    G_message(_("depression map indicates all the locations in the current map window where"));
    G_message(_("water accumulates and does not leave by the edge of the map. Lakes without"));
    G_message(_("outlet streams and sinkholes are examples of `depressions'.  If you wish to"));
    G_message(_("have a depression map, prepare a map where non-zero values indicate the"));
    G_message(_("locations where depressions occur.\n"));
    G_message(_("Hit <return> by itself for the next question if there is no depression map."));

    mapset = G_ask_old("What is the name of the depression map layer?",
		       map_layer, "cell", "cell");
    if (mapset) {
	if (input->fast)
	    com_line_add(&(input->com_line_ram), " de=", map_layer, mapset);
	if (input->slow)
	    com_line_add(&(input->com_line_seg), " de=", map_layer, mapset);
    }

    G_message(_("\nThe %s program will divide the elevation map into a number of"),
	      prog_name);
    G_message(_("watershed basins.  The number of watershed basins is indirectly determined"));
    G_message(_("by the `basin threshold' value.  The basin threshold is the area necessary for"));
    G_message(_("%s to define a unique watershed basin.  This area only applies to"),
	      prog_name);
    G_message(_("`exterior drainage basins'.  An exterior drainage basin does not have any"));
    G_message(_("drainage basins flowing into it.  Interior drainage basin size is determined"));
    G_message(_("by the surface flow going into stream segments between stream interceptions."));
    G_message(_("Thus interior drainage basins can be of any size.  The %s program"),
	      prog_name);
    G_message(_("also allows the user to relate basin size to potential overland flow"));
    G_message(_("(i.e., areas with low infiltration capacities will need smaller areas to"));
    G_message(_("develop stream channels than neighboring areas with high infiltration rates)."));
    G_message(_("The user can create a map layer with potential overland flow values, and"));
    G_message(_("%s will accumulate those values instead of area.\n"),
	      prog_name);
    G_message(_("What unit of measure will you use for the basin threshold:"));

    do {
	G_message(_(" 1) acres,          2) meters sq., 3) miles sq., 4) hectares,"));
	G_message(_(" 5) kilometers sq., 6) map cells,  7) overland flow units"));
	fprintf(stderr, _("Choose 1-7 or 0 to exit this program: "));
	G_gets(map_layer);
	sscanf(map_layer, "%d", &i);
    } while (i > 7 || i < 0);

    if (!i)
	exit(EXIT_SUCCESS);

    output->type_area = (char)i;

    G_message(_("\nHow large an area (or how many overland flow units) must a drainage basin"));
    fprintf(stderr, _("be for it to be an exterior drainage basin: "));
    G_gets(map_layer);
    sscanf(map_layer, "%lf", &d);

    switch (i) {
    case 1:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, ACRE_TO_METERSQ, window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, ACRE_TO_METERSQ, window);
	break;
    case 2:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, 1.0, window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, 1.0, window);
	break;
    case 3:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, MILESQ_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, MILESQ_TO_METERSQ,
			  window);
	break;
    case 4:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, HECTACRE_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, HECTACRE_TO_METERSQ,
			  window);
	break;
    case 5:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, KILOSQ_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, KILOSQ_TO_METERSQ,
			  window);
	break;
    case 6:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d,
			  (window->ns_res * window->ew_res), window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d,
			  (window->ns_res * window->ew_res), window);
	break;
    case 7:			/* needs an overland flow map */
	G_message(_("\nIf you hit <return> by itself for the next question, this"));
	G_message(_("program will terminate."));
	mapset = G_ask_old("What is the name of the overland flow map layer?",
			   map_layer, "cell", "cell");
	if (!mapset)
	    exit(EXIT_FAILURE);
	if (input->fast) {
	    com_line_add(&(input->com_line_ram), " ov=", map_layer, mapset);
	    basin_com_add(&(input->com_line_ram), d,
			  (window->ns_res * window->ew_res), window);
	}
	if (input->slow) {
	    com_line_add(&(input->com_line_seg), " ov=", map_layer, mapset);
	    basin_com_add(&(input->com_line_seg), d,
			  (window->ns_res * window->ew_res), window);
	}
	break;
    }

    G_message(_("\n%s must create a map layer of watershed basins"),
	      prog_name);
    G_message(_("before %s can run properly."), G_program_name());

    strcpy(buf, "Please name the output watershed basin map:");
    do {
	mapset = G_ask_new(buf, input->haf_name, "cell", "");
    } while (NULL == mapset);

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ba=", input->haf_name, NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ba=", input->haf_name, NULL);

    /* 
       This section queries the user about the armsed file input. If
       you want to make this an option,  the code below "COMMENT2" needs to be
       modified. 
     */

#ifdef ARMSED
    G_message(_("\n%s must create a file of watershed basin relationships"),
	      prog_name);
    G_message(_("before %s can run properly."), G_program_name());

    input->ar_file_name = NULL;
    while (input->ar_file_name == NULL) {
	fprintf(stderr, _("\nPlease name this file:"));
	G_gets(char_input);
	if (1 != G_legal_filename(char_input)) {
	    G_message(_("<%s> is an illegal file name"), char_input);
	}
	else
	    input->ar_file_name = G_store(char_input);
    }

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ar=", input->ar_file_name,
		     NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ar=", input->ar_file_name,
		     NULL);

    /*
       end of ARMSED comment code
     */

    /*
       COMMENT2 This section of code tells the program where to place the statistics
       about the watershed basin. GRASS users don't need this (w/ r.stats), but the
       format is suppossed to be "user-friendly" to hydrologists. For the stats to be
       created, the armsed file output needs to exist. For the stats to be an option
       in this program: 1) it should be querried before the armsed file query, and 2)
       make the armsed file query manditory if this option is invoked.
     */

    G_message(_("\n%s will generate a lot of output.  Indicate a file"),
	      G_program_name());
    G_message(_("name for %s to send the output to."), G_program_name());

    output->file_name = NULL;
    while (output->file_name == NULL) {
	fprintf(stderr, _("\nPlease name this file:"));
	G_gets(char_input);
	if (1 != G_legal_filename(char_input)) {
	    G_message(_("<%s> is an illegal file name"), char_input);
	}
	else
	    output->file_name = G_store(char_input);
    }

    /* 
       end of COMMENT2
     */
#endif

    G_message(_("\nThe accumulation map from %s must be present for"),
	      prog_name);
    G_message(_("%s to work properly."), G_program_name());
    strcpy(buf, "Please name the accumulation map:");
    do {
	mapset = G_ask_new(buf, input->accum_name, "cell", "");
    } while (NULL == mapset);

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ac=", input->accum_name, NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ac=", input->accum_name, NULL);

    G_message(_("\n%s can produce several maps not necessary for"),
	      prog_name);
    G_message(_("%s to function (stream channels, overland flow aspect, and"),
	      G_program_name());
    G_message(_("a display version of the accumulation map).  %s also has the"),
	      prog_name);
    G_message(_("ability to generate several variables in the Revised Universal Soil Loss"));
    G_message(_("Equation (Rusle): Slope Length (LS), and Slope Steepness (S).\n"));

    sprintf(buf, "Would you like any of these maps to be created?");
    if (G_yes(buf, 1)) {
	mapset = G_ask_new("", map_layer, "cell", "stream channel");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " se=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " se=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "half basin");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " ha=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " ha=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "overland aspect");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " dr=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " dr=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "display");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " di=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " di=", map_layer, NULL);
	}
	i = 0;
	mapset = G_ask_new("", map_layer, "cell", "Slope Length");
	if (mapset != NULL) {
	    i = 1;
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " LS=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " LS=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "Slope Steepness");
	if (mapset != NULL) {
	    i = 1;
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " S=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " S=", map_layer, NULL);
	}

	if (i) {
	    G_message(_("\nThe Slope Length factor (LS) and Slope Steepness (S) are influenced by"));
	    G_message(_("disturbed land.  %s reflects this with an optional map layer or value"),
		      prog_name);
	    G_message(_("where the value indicates the percent of disturbed (barren) land in that cell."));
	    G_message(_("Type <return> if you do not have a disturbed land map layer."));

	    mapset = G_ask_old("", map_layer, "cell", "disturbed land");
	    if (mapset != NULL) {
		if (input->fast)
		    com_line_add(&(input->com_line_ram), " r=", map_layer,
				 NULL);
		if (input->slow)
		    com_line_add(&(input->com_line_seg), " r=", map_layer,
				 NULL);
	    }
	    else {
		G_message(_("\nType the value indicating the percent of disturbed land.  This value will"));
		G_message(_("be used for every cell in the current region."));
		i = -6;
		while (i < 0 || i > 100) {
		    fprintf(stderr, _("\nInput value here [0-100]: "));
		    fgets(buf, 80, stdin);
		    sscanf(buf, "%d", &i);
		}
		if (input->fast)
		    com_add(&(input->com_line_ram), " r=", i);
		if (input->slow)
		    com_add(&(input->com_line_seg), " r=", i);
	    }

	    /*       12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
	    G_message(_("\nOverland surface flow only occurs for a set distance before swales form."));
	    G_message(_("Because of digital terrain model limitations, %s cannot pick up"),
		      prog_name);
	    G_message(_("these swales.  %s allows for an input (warning: kludge factor)"),
		      prog_name);
	    G_message(_("that prevents the surface flow distance from getting too long.  Normally,"));
	    G_message(_("maximum slope length is around 600 feet (about 183 meters)."));

	    i = -1;
	    while (i < 0) {
		fprintf(stdout,
			"\nInput maximum slope length here (in meters): ");
		fgets(buf, 80, stdin);
		sscanf(buf, "%d", &i);
	    }
	    if (input->fast)
		com_add(&(input->com_line_ram), " ms=", i);
	    if (input->slow)
		com_add(&(input->com_line_seg), " ms=", i);

	    /*       12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
	    G_message(_("\nRoads, ditches, changes in ground cover, and other factors will stop"));
	    G_message(_("slope length.  You may input a raster map indicating the locations of these"));
	    G_message(_("blocking factors.\n"));
	    G_message(_("Hit <return> by itself for the next question if there is no blocking map."));

	    mapset = G_ask_old("What is the name of the blocking map layer?",
			       map_layer, "cell", "cell");
	    if (mapset) {
		if (input->fast)
		    com_line_add(&(input->com_line_ram), " ob=", map_layer,
				 mapset);
		if (input->slow)
		    com_line_add(&(input->com_line_seg), " ob=", map_layer,
				 mapset);
	    }
	}
    }

    return 0;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    char command[GPATH_MAX];
    int err, ret;
    struct Option *opt1;
    struct Option *opt2;
    struct Option *opt3;
    struct Option *opt4;
    struct Option *opt5;
    struct Option *opt6;
    struct Option *opt7;
    struct Option *opt8;
    struct Option *opt9;
    struct Option *opt10;
    struct Option *opt11;
    struct Option *opt12;
    struct Option *opt13;
    struct Option *opt14;
    struct Option *opt15;
    struct Option *opt16;
    struct Flag *flag_sfd;
    struct Flag *flag_flow;
    struct Flag *flag_seg;
    struct Flag *flag_abs;
    struct Flag *flag_flat;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    module->description = _("Calculates hydrological parameters and RUSLE factors.");

    opt1 = G_define_standard_option(G_OPT_R_ELEV);
    opt1->guisection = _("Inputs");

    opt2 = G_define_standard_option(G_OPT_R_INPUT);
    opt2->key = "depression";
    opt2->label = _("Name of input depressions raster map");
    opt2->description = _("All non-NULL and non-zero cells are considered as real depressions");
    opt2->required = NO;
    opt2->guisection = _("Inputs");

    opt3 = G_define_standard_option(G_OPT_R_INPUT);
    opt3->key = "flow";
    opt3->description = _("Name of input raster representing amount of overland flow per cell");
    opt3->required = NO;
    opt3->guisection = _("Inputs");

    opt4 = G_define_standard_option(G_OPT_R_INPUT);
    opt4->key = "disturbed_land";
    opt4->label = _("Name of input raster map percent of disturbed land");
    opt4->description = _("For USLE");
    opt4->required = NO;
    opt4->guisection = _("Inputs");

    opt5 = G_define_standard_option(G_OPT_R_INPUT);
    opt5->key = "blocking";
    opt5->label =
	_("IName of input raster map blocking overland surface flow");
    opt5->description =
	_("For USLE. All non-NULL and non-zero cells are considered as blocking terrain.");
    opt5->required = NO;
    opt5->guisection = _("Inputs");

    opt6 = G_define_option();
    opt6->key = "threshold";
    opt6->description =
	_("Minimum size of exterior watershed basin");
    opt6->required = NO;
    opt6->type = TYPE_INTEGER;
    opt6->guisection = _("Inputs");

    opt7 = G_define_option();
    opt7->key = "max_slope_length";
    opt7->label =
	_("Maximum length of surface flow in map units");
    opt7->description = _("For USLE");
    opt7->required = NO;
    opt7->type = TYPE_DOUBLE;
    opt7->guisection = _("Inputs");

    opt8 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt8->key = "accumulation";
    opt8->label =
	_("Name for output accumulation raster map");
    opt8->description =
    _("Number of cells that drain through each cell");
    opt8->required = NO;
    opt8->guisection = _("Outputs");

    opt9 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt9->key = "drainage";
    opt9->description = _("Name for output drainage direction raster map");
    opt9->required = NO;
    opt9->guisection = _("Outputs");

    opt10 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt10->key = "basin";
    opt10->description =
	_("Name for basins raster map");
    opt10->description = _("Unique label for each watershed basin");
    opt10->required = NO;
    opt10->guisection = _("Outputs");

    opt11 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt11->key = "stream";
    opt11->description = _("Name for output stream segments raster map");
    opt11->required = NO;
    opt11->guisection = _("Outputs");

    opt12 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt12->key = "half_basin";
    opt12->label = _("Name for output half basins raster map");
    opt12->description =
	_("Each half-basin is given a unique value");
    opt12->required = NO;
    opt12->guisection = _("Outputs");

    opt13 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt13->key = "length_slope";
    opt13->label = _("Name for output slope length raster map");
    opt13->description =
	_("Slope length and steepness (LS) factor for USLE");
    opt13->required = NO;
    opt13->guisection = _("Outputs");

    opt14 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt14->key = "slope_steepness";
    opt14->label = _("Name for output slope steepness raster map");
    opt14->description = _("Slope steepness (S) factor for USLE");
    opt14->required = NO;
    opt14->guisection = _("Outputs");

    opt15 = G_define_option();
    opt15->key = "convergence";
    opt15->type = TYPE_INTEGER;
    opt15->required = NO;
    opt15->answer = "5";
    opt15->label = _("Convergence factor for MFD (1-10)");
    opt15->description =
	_("1 = most diverging flow, 10 = most converging flow. Recommended: 5");

    opt16 = G_define_option();
    opt16->key = "memory";
    opt16->type = TYPE_INTEGER;
    opt16->required = NO;
    opt16->answer = "300";	/* 300MB default value, please keep r.terraflow in sync */
    opt16->description = _("Maximum memory to be used with -m flag (in MB)");

    flag_sfd = G_define_flag();
    flag_sfd->key = 's';
    flag_sfd->label = _("SFD (D8) flow (default is MFD)");
    flag_sfd->description =
	_("SFD: single flow direction, MFD: multiple flow direction");

    flag_flow = G_define_flag();
    flag_flow->key = '4';
    flag_flow->description =
	_("Allow only horizontal and vertical flow of water");

    flag_seg = G_define_flag();
    flag_seg->key = 'm';
    flag_seg->label =
	_("Enable disk swap memory option: Operation is slow");
    flag_seg->description =
	_("Only needed if memory requirements exceed available RAM; see manual on how to calculate memory requirements");

    flag_abs = G_define_flag();
    flag_abs->key = 'a';
    flag_abs->label =
	_("Use positive flow accumulation even for likely underestimates");
    flag_abs->description =
	_("See manual for a detailed description of flow accumulation output");

    flag_flat = G_define_flag();
    flag_flat->key = 'b';
    flag_flat->label =
	_("Beautify flat areas");
    flag_flat->description =
	_("Flow direction in flat areas is modified to look prettier");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* Check option combinations */

    /* Check for some output map */
    if ((opt8->answer == NULL)
	&& (opt9->answer == NULL)
	&& (opt10->answer == NULL)
	&& (opt11->answer == NULL)
	&& (opt12->answer == NULL)
	&& (opt14->answer == NULL)
	&& (opt15->answer == NULL)) {
	G_fatal_error(_("Sorry, you must choose an output map."));
    }

    err = 0;
    /* basin and basin threshold */
    err += (opt10->answer != NULL && opt6->answer == NULL);
    /* stream and basin threshold */
    err += (opt11->answer != NULL && opt6->answer == NULL);
    /* half_basin and basin threshold */
    err += (opt12->answer != NULL && opt6->answer == NULL);
    /* LS factor and basin threshold */
    err += (opt13->answer != NULL && opt6->answer == NULL);
    /* S factor and basin threshold */
    err += (opt14->answer != NULL && opt6->answer == NULL);

    if (err) {
	G_message(_("Sorry, if any of the following options are set:\n"
		    "    basin, stream, half_basin, length_slope, or slope_steepness\n"
		    "    you MUST provide a value for the basin "
		    "threshold parameter."));
	G_usage();
	exit(EXIT_FAILURE);
    }

    /* Build command line */
    sprintf(command, "%s/etc/r.watershed.%s",
	    G_gisbase(),
	    flag_seg->answer ? "seg" : "ram");
    new_argv[new_argc++] = command;

    if (flag_sfd->answer)
	new_argv[new_argc++] = "-s";

    if (flag_flow->answer)
	new_argv[new_argc++] = "-4";

    if (flag_abs->answer)
	new_argv[new_argc++] = "-a";

    if (flag_flat->answer && !flag_seg->answer)
	new_argv[new_argc++] = "-b";

    if (flag_flat->answer && flag_seg->answer)
	G_message(_("Beautify flat areas is not yet supported for disk swap mode"));

    do_opt(opt1);
    do_opt(opt2);
    do_opt(opt3);
    do_opt(opt4);
    do_opt(opt5);
    do_opt(opt6);
    do_opt(opt7);
    do_opt(opt8);
    do_opt(opt9);
    do_opt(opt10);
    do_opt(opt11);
    do_opt(opt12);
    do_opt(opt13);
    do_opt(opt14);
    do_opt(opt15);
    if (flag_seg->answer)
	do_opt(opt16);
    new_argv[new_argc++] = NULL;

    G_debug(1, "Mode: %s", flag_seg->answer ? "Segmented" : "All in RAM");

    ret = G_vspawn_ex(new_argv[0], new_argv);

    if (ret != EXIT_SUCCESS)
	G_warning(_("Subprocess failed with exit code %d"), ret);

    /* record map metadata/history info */
    if (opt8->answer)
	write_hist(opt8->answer,
		   "Watershed accumulation: overland flow that traverses each cell",
		   opt1->answer, flag_seg->answer, flag_sfd->answer);
    if (opt9->answer)
	write_hist(opt9->answer,
		   "Watershed drainage direction (CCW from East divided by 45deg)",
		   opt1->answer, flag_seg->answer, flag_sfd->answer);
    if (opt10->answer)
	write_hist(opt10->answer,
		   "Watershed basins", opt1->answer, flag_seg->answer, 
		   flag_sfd->answer);
    if (opt11->answer)
	write_hist(opt11->answer,
		   "Watershed stream segments", opt1->answer,
		   flag_seg->answer, flag_sfd->answer);
    if (opt12->answer)
	write_hist(opt12->answer,
		   "Watershed half-basins", opt1->answer, flag_seg->answer, 
		   flag_sfd->answer);
    if (opt13->answer)
	write_hist(opt13->answer,
		   "Watershed slope length and steepness (LS) factor",
		   opt1->answer, flag_seg->answer, flag_sfd->answer);
    if (opt14->answer)
	write_hist(opt14->answer,
		   "Watershed slope steepness (S) factor",
		   opt1->answer, flag_seg->answer, flag_sfd->answer);

    exit(ret);
}
Esempio n. 28
0
int main(int argc, char **argv)
{
    int overwrite;
    int interactive;
    int remove;
    int have_colors;
    struct Colors colors, colors_tmp;
    struct Cell_stats statf;
    int have_stats = 0;
    struct FPRange range;
    DCELL min, max;
    char *name, *mapset;
    char *style, *cmap, *cmapset;
    char *rules;
    int fp;
    struct GModule *module;
    struct
    {
	struct Flag *r, *w, *l, *g, *a, *e, *i, *q, *n;
    } flag;
    struct
    {
	struct Option *map, *colr, *rast, *rules;
    } opt;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, color table");
    module->description =
	_("Creates/modifies the color table associated with a raster map layer.");

    opt.map = G_define_standard_option(G_OPT_R_MAP);
    opt.map->required = NO;
    opt.map->guisection = _("Required");

    scan_rules();

    opt.colr = G_define_option();
    opt.colr->key = "color";
    opt.colr->key_desc = "style";
    opt.colr->type = TYPE_STRING;
    opt.colr->required = NO;
    opt.colr->options = rules_list();
    opt.colr->description = _("Type of color table");
    opt.colr->descriptions = rules_descriptions();
    opt.colr->guisection = _("Colors");

    opt.rast = G_define_option();
    opt.rast->key = "raster";
    opt.rast->type = TYPE_STRING;
    opt.rast->required = NO;
    opt.rast->gisprompt = "old,cell,raster";
    opt.rast->description =
	_("Raster map name from which to copy color table");

    opt.rules = G_define_standard_option(G_OPT_F_INPUT);
    opt.rules->key = "rules";
    opt.rules->required = NO;
    opt.rules->description = _("Path to rules file (\"-\" to read rules from stdin)");
    opt.rules->guisection = _("Colors");

    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description = _("Remove existing color table");

    flag.w = G_define_flag();
    flag.w->key = 'w';
    flag.w->description =
	_("Only write new color table if one doesn't already exist");

    flag.l = G_define_flag();
    flag.l->key = 'l';
    flag.l->description = _("List available rules then exit");

    flag.n = G_define_flag();
    flag.n->key = 'n';
    flag.n->description = _("Invert colors");
    flag.n->guisection = _("Colors");

    flag.g = G_define_flag();
    flag.g->key = 'g';
    flag.g->description = _("Logarithmic scaling");
    flag.g->guisection = _("Colors");

    flag.a = G_define_flag();
    flag.a->key = 'a';
    flag.a->description = _("Logarithmic-absolute scaling");
    flag.a->guisection = _("Colors");

    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Histogram equalization");
    flag.e->guisection = _("Colors");

    flag.i = G_define_flag();
    flag.i->key = 'i';
    flag.i->description = _("Enter rules interactively");

    /* please, remove before GRASS 7 released */
    flag.q = G_define_flag();
    flag.q->key = 'q';
    flag.q->description = _("Run quietly");


    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* please, remove before GRASS 7 released */
    if (flag.q->answer) {
	G_putenv("GRASS_VERBOSE", "0");
	G_warning(_("The '-q' flag is superseded and will be removed "
		    "in future. Please use '--quiet' instead."));
    }

    if (flag.l->answer) {
	list_rules();
	return EXIT_SUCCESS;
    }

    overwrite = !flag.w->answer;
    interactive = flag.i->answer;
    remove = flag.r->answer;

    name = opt.map->answer;

    style = opt.colr->answer;
    cmap = opt.rast->answer;
    rules = opt.rules->answer;

    if (!name)
	G_fatal_error(_("No raster map specified"));

    if (!cmap && !style && !rules && !interactive && !remove)
	G_fatal_error(_("One of \"-i\" or \"-r\" or options \"color\", \"rast\" or \"rules\" must be specified!"));

    if (interactive && (style || rules || cmap))
	G_fatal_error(_("Interactive mode is incompatible with \"color\", \"rules\", and \"raster\" options"));

    if ((style && (cmap || rules)) || (cmap && rules)) {
	if ((style && rules && !cmap) && strcmp(style, "rules") == 0)
	    style = NULL;
	else
	    G_fatal_error(
		_("\"color\", \"rules\", and \"raster\" options are mutually exclusive"));
    }

    /* handle rules="-" (from stdin) by translating that to colors=rules */
    /* this method should not be ported to GRASS 7 verbatim, as color=rules DNE */
    if (rules && strcmp(rules, "-") == 0) {
	style = G_store("rules");
	rules = NULL;
    }

    if (flag.g->answer && flag.a->answer)
	G_fatal_error(_("-g and -a flags are mutually exclusive"));

    mapset = G_find_cell2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    if (remove) {
	int stat = G_remove_colors(name, mapset);

	if (stat < 0)
	    G_fatal_error(_("Unable to remove color table of raster map <%s>"), name);
	if (stat == 0)
	    G_warning(_("Color table of raster map <%s> not found"), name);
	return EXIT_SUCCESS;
    }

    G_suppress_warnings(1);
    have_colors = G_read_colors(name, mapset, &colors);
    /*if (have_colors >= 0)
       G_free_colors(&colors); */

    if (have_colors > 0 && !overwrite) {
	G_warning(_("Color table exists. Exiting."));
	exit(EXIT_FAILURE);
    }

    G_suppress_warnings(0);

    fp = G_raster_map_is_fp(name, mapset);
    G_read_fp_range(name, mapset, &range);
    G_get_fp_range_min_max(&range, &min, &max);

    if (interactive) {
	if (!read_color_rules(stdin, &colors, min, max, fp))
	    exit(EXIT_FAILURE);
    }
    else if (style) {
	/* 
	 * here the predefined color-table color-styles are created by GRASS library calls. 
	 */
	if (strcmp(style, "random") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'random' is not supported for floating point raster map"));
	    G_make_random_colors(&colors, (CELL) min, (CELL) max);
	}
	else if (strcmp(style, "grey.eq") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'grey.eq' is not supported for floating point raster map"));
	    if (!have_stats)
		have_stats = get_stats(name, mapset, &statf);
	    G_make_histogram_eq_colors(&colors, &statf);
	}
	else if (strcmp(style, "grey.log") == 0) {
	    if (fp)
		G_fatal_error(_("Color table 'grey.log' is not supported for floating point raster map"));
	    if (!have_stats)
		have_stats = get_stats(name, mapset, &statf);
	    G_make_histogram_log_colors(&colors, &statf, (CELL) min,
					(CELL) max);
	}
	else if (strcmp(style, "rules") == 0) {
	    if (!read_color_rules(stdin, &colors, min, max, fp))
		exit(EXIT_FAILURE);
	}
	else if (find_rule(style))
	    G_make_fp_colors(&colors, style, min, max);
	else
	    G_fatal_error(_("Unknown color request '%s'"), style);
    }
    else if (rules) {
	if (!G_load_fp_colors(&colors, rules, min, max)) {
	    /* for backwards compatibility try as std name; remove for GRASS 7 */
	    char path[GPATH_MAX];

	    /* don't bother with native dirsep as not needed for backwards compatibility */
	    sprintf(path, "%s/etc/colors/%s", G_gisbase(), rules);

	    if (!G_load_fp_colors(&colors, path, min, max))
		G_fatal_error(_("Unable to load rules file <%s>"), rules);
	}
    }
    else {
	/* use color from another map (cmap) */
	cmapset = G_find_cell2(cmap, "");
	if (cmapset == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), cmap);

	if (G_read_colors(cmap, cmapset, &colors) < 0)
	    G_fatal_error(_("Unable to read color table for raster map <%s>"), cmap);
    }

    if (fp)
	G_mark_colors_as_fp(&colors);

    if (flag.n->answer)
	G_invert_colors(&colors);

    if (flag.e->answer) {
	if (fp) {
	    struct FP_stats fpstats;
	    get_fp_stats(name, mapset, &fpstats, min, max, flag.g->answer, flag.a->answer);
	    G_histogram_eq_colors_fp(&colors_tmp, &colors, &fpstats);
	}
	else {
	    if (!have_stats) 
		have_stats = get_stats(name, mapset, &statf);
	    G_histogram_eq_colors(&colors_tmp, &colors, &statf);
	}
	colors = colors_tmp;
    }

    if (flag.g->answer) {
	G_log_colors(&colors_tmp, &colors, 100);
	colors = colors_tmp;
    }

    if (flag.a->answer) {
	G_abs_log_colors(&colors_tmp, &colors, 100);
	colors = colors_tmp;
    }

    if (fp)
	G_mark_colors_as_fp(&colors);

    if (G_write_colors(name, mapset, &colors) >= 0)
	G_message(_("Color table for raster map <%s> set to '%s'"), name,
		  interactive ? "rules" : style ? style : rules ? rules :
		  cmap);

    exit(EXIT_SUCCESS);
}
Esempio n. 29
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{
    struct Option *type, *rc_file;
    struct Flag *update, *nolaunch;
    struct GModule *module;
    const char *gui_type_env;
    char progname[GPATH_MAX];
    char *desc;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("gui"));
    G_add_keyword(_("user interface"));
    module->label =
	_("Launches a GRASS graphical user interface (GUI) session.");
    module->description = _("And updates default user interface settings.");

    type = G_define_option();
    type->key = "ui";
    type->type = TYPE_STRING;
    type->label = _("User interface");
    type->description = _("Default value: GRASS_GUI if defined otherwise wxpython");
    desc = NULL;
    G_asprintf(&desc,
	        "wxpython;%s;text;%s",
	        _("wxPython based GUI (wxGUI)"),
	        _("command line interface only"));
    type->descriptions = desc;
    type->options = "wxpython,text";
    type->guisection = _("Type");
    
    rc_file = G_define_standard_option(G_OPT_F_INPUT);
    rc_file->key = "workspace";
    rc_file->required = NO;
    rc_file->key_desc = "name.gxw";
    rc_file->description = _("Name of workspace file to load on start-up (valid only for wxGUI)");

    update = G_define_flag();
    update->key = 'd';
    update->description = _("Update default user interface settings");
    update->guisection = _("Default");

    nolaunch = G_define_flag();
    nolaunch->key = 'n';
    nolaunch->description =
	_("Do not launch GUI after updating the default user interface settings");
    nolaunch->guisection = _("Default");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    if (type->answer && strcmp(type->answer, "text") == 0 &&
	!nolaunch->answer)
	nolaunch->answer = TRUE;
    
    if (nolaunch->answer && !update->answer)
	update->answer = TRUE;
    
    gui_type_env = G__getenv("GUI");

    if (!type->answer) {
	if (gui_type_env && strcmp(gui_type_env, "text")) {
	    type->answer = G_store(gui_type_env);
	}
	else {
	    type->answer = "wxpython";
	}
    }

    if (((gui_type_env && update->answer) &&
	 strcmp(gui_type_env, type->answer) != 0) || !gui_type_env) {
	G_setenv("GUI", type->answer);
	G_message(_("<%s> is now the default GUI"), type->answer);
    }
    else {
	if(update->answer)
	    if(gui_type_env) {
		G_debug(1, "No change: old gui_type_env=[%s], new type->ans=[%s]",
			gui_type_env, type->answer);
	    }
    }

    if(nolaunch->answer)
	exit(EXIT_SUCCESS);


    G_message(_("Launching <%s> GUI in the background, please wait..."), type->answer);

    if (strcmp(type->answer, "wxpython") == 0) {
	sprintf(progname, "%s/gui/wxpython/wxgui.py", G_gisbase());
	if (rc_file->answer) {
	    G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
		    "--workspace", rc_file->answer, SF_BACKGROUND, NULL);
	}
	else {
	    G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
		    SF_BACKGROUND, NULL);
	}
    }

    /* stop the impatient from starting it again
        before the splash screen comes up */
    G_sleep(3);

    exit(EXIT_SUCCESS);
}
Esempio n. 30
0
int main(int argc, char *argv[])
{
    struct Option *type, *rc_file;
    struct Flag *update_ui, *fglaunch, *nolaunch;
    struct GModule *module;
    const char *gui_type_env;
    char progname[GPATH_MAX];
    char *desc;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("GUI"));
    G_add_keyword(_("user interface"));

    module->label =
        _("Launches a GRASS graphical user interface (GUI) session.");
    module->description = _("Optionally updates default user interface settings.");

    type = G_define_option();
    type->key = "ui";
    type->type = TYPE_STRING;
    type->description = _("User interface");
    desc = NULL;
    G_asprintf(&desc,
               "wxpython;%s;text;%s;gtext;%s;",
               _("wxPython based GUI (wxGUI)"),
               _("command line interface only"),
               _("command line interface with GUI startup screen"));
    type->descriptions = desc;
    type->options = "wxpython,text,gtext";
    type->answer = "wxpython";
    type->guisection = _("Type");

    rc_file = G_define_standard_option(G_OPT_F_INPUT);
    rc_file->key = "workspace";
    rc_file->required = NO;
    rc_file->key_desc = "name.gxw";
    rc_file->label = _("Name of workspace file to load on start-up");
    rc_file->description = _("This is valid only for wxGUI (wxpython)");

    fglaunch = G_define_flag();
    fglaunch->key = 'f';
    fglaunch->label = _("Start GUI in the foreground");
    fglaunch->description = _("By default the GUI starts in the background"
                              " and control is immediately returned to the caller."
                              " When GUI runs in foregreound, it blocks the command line");

    update_ui = G_define_flag();
    update_ui->key = 'd';
    update_ui->description = _("Update default user interface settings");
    update_ui->guisection = _("Default");

    nolaunch = G_define_flag();
    nolaunch->key = 'n';
    nolaunch->description =
        _("Do not launch GUI after updating the default user interface settings");
    nolaunch->guisection = _("Default");

    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);

    gui_type_env = G_getenv_nofatal("GUI");
    G_debug(1, "GUI: %s", gui_type_env ? gui_type_env : "unset");
    if (update_ui->answer) {
        if (!gui_type_env || strcmp(type->answer, gui_type_env)) {
            G_setenv("GUI", type->answer);
            G_message(_("<%s> is now the default GUI"), type->answer);
        }
    }

    if(strcmp(type->answer, "wxpython") != 0 || nolaunch->answer) {
        if (!update_ui->answer)
            G_warning(_("Nothing to do. For setting up <%s> as default UI use -%c flag."),
                      type->answer, update_ui->key);
        exit(EXIT_SUCCESS);
    }

    sprintf(progname, "%s/gui/wxpython/wxgui.py", G_gisbase());
    if (access(progname, F_OK) == -1)
        G_fatal_error(_("Your installation doesn't include GUI, exiting."));

    if (fglaunch->answer) {
        G_message(_("Launching <%s> GUI, please wait..."), type->answer);
        if (rc_file->answer) {
            G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
                       "--workspace", rc_file->answer, NULL);
        }
        else {
            G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
                       NULL);
        }
    }
    else {
        G_message(_("Launching <%s> GUI in the background, please wait..."), type->answer);
        if (rc_file->answer) {
            G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
                       "--workspace", rc_file->answer, SF_BACKGROUND, NULL);
        }
        else {
            G_spawn_ex(getenv("GRASS_PYTHON"), getenv("GRASS_PYTHON"), progname,
                       SF_BACKGROUND, NULL);
        }
        /* stop the impatient from starting it again
           before the splash screen comes up */
        G_sleep(3);
    }

    exit(EXIT_SUCCESS);
}