Exemple #1
0
int show_env(void)
{
    fprintf(stderr, "env(%d) switch to LOCATION %s, MAPSET %s\n", which_env,
	    G__getenv("LOCATION_NAME") ==
	    NULL ? "?" : G__getenv("LOCATION_NAME"),
	    G__getenv("MAPSET") == NULL ? "?" : G__getenv("MAPSET"));
    G_sleep(2);

    return 0;
}
Exemple #2
0
int G_check_overwrite(int argc, char **argv)
{
    char *overstr;
    int overwrite;

    overwrite = 0;
    if ((overstr = G__getenv("OVERWRITE"))) {
	overwrite = atoi(overstr);
    }

    /* check if inherited GRASS_OVERWRITE is 1 */
    if (!overwrite && (overstr = getenv("GRASS_OVERWRITE"))) {
	overwrite = atoi(overstr);
    }

    /* check for --o or --overwrite option */
    if (!overwrite) {
	int i;

	for (i = 0; i < argc; i++) {
	    if (strcmp(argv[i], "--o") == 0 ||
		strcmp(argv[i], "--overwrite") == 0) {
		overwrite = 1;
		break;
	    }
	}
    }

    G__setenv("OVERWRITE", "1");

    return overwrite;
}
Exemple #3
0
/*!
  \brief Append command to the cmd file

  Cmd file is created by d.mon by defining GRASS variable
  \c MONITOR_<name>_CMDFILE, where \c \<name\> is the upper case name of
  the monitor.

  Command string is usually generated by G_recreate_command(), NULL is
  used to clean up list of commands (see d.erase command).

  \param cmd string buffer with command or NULL

  \return 0 no monitor selected
  \return -1 on error
  \return 1 on success
*/
int D_save_command(const char *cmd)
{
    const char *mon_name, *mon_cmd;
    char *env, *flag, *u_mon_name;
    FILE *fd;

    G_debug(1, "D_save_command(): %s", cmd);

    mon_name = G__getenv("MONITOR");
    if (!mon_name || /* if no monitor selected */
	/* or wx monitor selected and display commands called by the monitor */
	(G_strncasecmp(mon_name, "wx", 2) == 0 &&
	 getenv("GRASS_RENDER_IMMEDIATE")))
	return 0;

    /* GRASS variable names should be upper case. */
    u_mon_name = G_store_upper(mon_name);

    env = NULL;
    G_asprintf(&env, "MONITOR_%s_CMDFILE", u_mon_name);
    mon_cmd = G__getenv(env);
    if (!mon_cmd)
	return 0;

    if (cmd)
	flag = "a";
    else
	flag = "w";

    fd = fopen(mon_cmd, flag);
    if (!fd) {
	G_warning(_("Unable to open file '%s'"), mon_cmd);
	return -1;
    }

    if (cmd)
	fprintf(fd, "%s\n", cmd);
    
    fclose(fd);

    return 1;
}
Exemple #4
0
/* check if monitor is running */
int check_mon(const char *name)
{
    char *env_name;
    const char *str;
    
    env_name = NULL;
    G_asprintf(&env_name, "MONITOR_%s_ENVFILE", G_store_upper(name));
    str = G__getenv(env_name);
    if (!str)
	return FALSE;
    
    return TRUE;
}
Exemple #5
0
int G_debug(int level, const char *msg, ...)
{
#ifdef GDEBUG
    char *lstr, *filen;
    va_list ap;
    FILE *fd;

    if (grass_debug_level < 0) {
	lstr = G__getenv("DEBUG");

	if (lstr != NULL)
	    grass_debug_level = atoi(lstr);
	else
	    grass_debug_level = 0;
    }

    if (grass_debug_level >= level) {
	va_start(ap, msg);

	filen = getenv("GRASS_DEBUG_FILE");
	if (filen != NULL) {
	    fd = fopen(filen, "a");
	    if (!fd) {
		G_warning(_("Cannot open debug file '%s'"), filen);
		return 0;
	    }
	}
	else {
	    fd = stderr;
	}

	fprintf(fd, "D%d/%d: ", level, grass_debug_level);
	vfprintf(fd, msg, ap);
	fprintf(fd, "\n");
	fflush(fd);

	if (filen != NULL)
	    fclose(fd);

	va_end(ap);
    }
#endif

    return 1;
}
Exemple #6
0
/* list related commands for given monitor */
void list_cmd(const char *name, FILE *fd_out)
{
    char buf[1024];
    char *cmd_name;
    const char *cmd_value;
    FILE *fd;

    cmd_name = NULL;
    G_asprintf(&cmd_name, "MONITOR_%s_CMDFILE", G_store_upper(name));
    cmd_value = G__getenv(cmd_name);
    if (!cmd_value)
	G_fatal_error(_("Command file not found"));
    
    fd = fopen(cmd_value, "r");
    if (!fd)
	G_fatal_error(_("Unable to read command file"));

    while (G_getl2(buf, sizeof(buf) - 1, fd) != 0) {
	fprintf(fd_out, "%s\n", buf);
    }
    
    fclose(fd);
}
Exemple #7
0
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);
}
Exemple #8
0
int start_mon(const char *name, const char *output, int select,
	      const char *width, const char *height, const char *bgcolor,
	      int truecolor)
{
    const char *curr_mon;
    char *env_name, *env_value, *cmd_value;
    char *tempfile, buf[1024];
    int env_fd;
    
    curr_mon = G__getenv("MONITOR");
    if (curr_mon && strcmp(curr_mon, name) == 0 && check_mon(curr_mon))
	G_fatal_error(_("Monitor <%s> already running"), name);
    
    tempfile = G_tempfile();

    env_name = env_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_ENVFILE", name);
    G_asprintf(&env_value, "%s.env", tempfile);
    G_setenv(env_name, env_value);
    env_fd = creat(env_value, 0666);
    if (env_fd < 0)
	G_fatal_error(_("Unable to create file '%s'"), env_value);
    if (width) {
	sprintf(buf, "GRASS_WIDTH=%s\n", width);
	write(env_fd, buf, strlen(buf));
    }
    if (height) {
	sprintf(buf, "GRASS_HEIGHT=%s\n", height);
	write(env_fd, buf, strlen(buf));
    }
    if (bgcolor) {
	if (strcmp(bgcolor, "none") == 0)
	    sprintf(buf, "GRASS_TRANSPARENT=TRUE\n");
	else
	    sprintf(buf, "GRASS_BACKGROUNDCOLOR=%s\n", bgcolor);
	write(env_fd, buf, strlen(buf));
    }
    if (truecolor) {
	sprintf(buf, "GRASS_TRUECOLOR=TRUE\n");
	write(env_fd, buf, strlen(buf));
    }
    close(env_fd);

    cmd_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_CMDFILE", name);
    G_asprintf(&cmd_value, "%s.cmd", tempfile);
    G_setenv(env_name, cmd_value);
    close(creat(cmd_value, 0666));

    G_verbose_message(_("Staring monitor <%s> with env file '%s'"), name, env_value);
    
    G_debug(1, "start: name=%s ", name);
    G_debug(3, "       envfile = %s", env_value);
    G_debug(3, "       cmdfile = %s", cmd_value);
    
    if (select)
	G_setenv("MONITOR", name);
    
    if (strncmp(name, "wx", 2) == 0) /* use G_strncasecmp() instead */
	start_wx(name, tempfile, env_value, cmd_value, 
		 width, height);
    else
	start(name, output);
    
    return 0;
}
Exemple #9
0
int main(int argc, char *argv[])
{
    int error;
    int oops;
    char *mon_name;

    struct GModule *module;
    struct Option *start, *stop, *select, *unlock;
    struct Flag *list, *status, *print, *release, *no_auto_select;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("display");
    module->description =
	_("To establish and control use of a graphics display monitor.");

    start = G_define_option();
    start->key = "start";
    start->type = TYPE_STRING;
    start->required = NO;
    start->description = _("Name of graphics monitor to start");

    stop = G_define_option();
    stop->key = "stop";
    stop->type = TYPE_STRING;
    stop->required = NO;
    stop->description = _("Name of graphics monitor to stop");

    select = G_define_option();
    select->key = "select";
    select->type = TYPE_STRING;
    select->required = NO;
    select->description = _("Name of graphics monitor to select");

    unlock = G_define_option();
    unlock->key = "unlock";
    unlock->type = TYPE_STRING;
    unlock->required = NO;
    unlock->description = _("Name of graphics monitor to unlock");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List all monitors");

    status = G_define_flag();
    status->key = 'L';
    status->description = _("List all monitors (with current status)");

    print = G_define_flag();
    print->key = 'p';
    print->description = _("Print name of currently selected monitor");

    release = G_define_flag();
    release->key = 'r';
    release->description = _("Release currently selected monitor");

    no_auto_select = G_define_flag();
    no_auto_select->key = 's';
    no_auto_select->description =
	_("Do not automatically select when starting");

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

    if (unlock->answer)
	run("release", "-f", unlock->answer);

    if (!select->answer && !no_auto_select->answer)
	select->answer = start->answer;

    G__read_env();
    mon_name = G__getenv("MONITOR");	/* remember old monitor name */

    error = 0;
    if (status->answer)
	error += run("status", "", "");
    else if (list->answer)
	error += run("list", "", "");
    if (release->answer)
	error += run("release", "", "");
    if (stop->answer)
	error += run("stop", "", stop->answer);
    if (start->answer) {
	error += run("start", "", start->answer);
	if (error) {		/* needed procedure failed */
	    if (mon_name != NULL) {
		/* restore the previous environ. */
		G__setenv("MONITOR", mon_name);
		/* write the name to the .gisrc file */
		G__write_env();
	    }
	}
    }
    if (select->answer) {
	oops = run("select", "", select->answer);	/* couldn't select */
	if (oops && start->answer && strcmp(start->answer, select->answer) == 0) {
	    /* try once more */
	    G_message(_("Problem selecting %s. Will try once more"),
		      select->answer);
	    oops = run("select", "", select->answer);	/* couldn't select */
	}
	if (oops) {		/* needed procedure failed */
	    if (mon_name != NULL) {
		/* restore the previous environ. */
		G__setenv("MONITOR", mon_name);
		/* write the name to the .gisrc file */
		G__write_env();
	    }
	}
	error += oops;
    }
    if (print->answer)
	error += run("which", "", "");

    exit(error ? EXIT_FAILURE : EXIT_SUCCESS);
}
Exemple #10
0
/*!
 * \brief Get current mapset name
 *
 * \return pointer mapset name
 * \return NULL on error
 */
const char *G__mapset(void)
{
    return G__getenv("MAPSET");
}
Exemple #11
0
int main(int argc, char *argv[])
{
    int ret;
    struct GModule *module;
    struct Option *gisdbase_opt, *location_opt, *mapset_opt;
    struct Flag *f_add, *f_list;
    char *gisdbase_old, *location_old, *mapset_old;
    char *gisdbase_new, *location_new, *mapset_new;
    char *gis_lock;
    char *mapset_old_path, *mapset_new_path;
    char *lock_prog;
    char path[GPATH_MAX];
    char *shell, *monitor;
    struct MON_CAP *cap;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("general, settings");
    module->label = _("Changes current mapset.");
    module->description = _("Optionally create new mapset or list available mapsets in given location.");
    
    mapset_opt = G_define_option();
    mapset_opt->key = "mapset";
    mapset_opt->type = TYPE_STRING;
    mapset_opt->required = NO;
    mapset_opt->multiple = NO;
    mapset_opt->description = _("Name of mapset where to switch");
    mapset_opt->guisection = _("Settings");

    location_opt = G_define_option();
    location_opt->key = "location";
    location_opt->type = TYPE_STRING;
    location_opt->required = NO;
    location_opt->multiple = NO;
    location_opt->description = _("Location name (not location path)");
    location_opt->guisection = _("Settings");

    gisdbase_opt = G_define_option();
    gisdbase_opt->key = "gisdbase";
    gisdbase_opt->type = TYPE_STRING;
    gisdbase_opt->required = NO;
    gisdbase_opt->multiple = NO;
    gisdbase_opt->key_desc = "path";
    gisdbase_opt->description =
	_("GIS data directory (full path to the directory where the new location is)");
    gisdbase_opt->guisection = _("Settings");
    
    f_add = G_define_flag();
    f_add->key = 'c';
    f_add->description = _("Create mapset if it doesn't exist");
    f_add->answer = FALSE;
    f_add->guisection = _("Create");

    f_list = G_define_flag();
    f_list->key = 'l';
    f_list->description = _("List available mapsets");
    f_list->guisection = _("Print");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (!mapset_opt->answer && !f_list->answer)
	G_fatal_error(_("Either mapset= or -l must be used"));

    /* Store original values */
    gisdbase_old = G__getenv("GISDBASE");
    location_old = G__getenv("LOCATION_NAME");
    mapset_old = G__getenv("MAPSET");
    G_asprintf(&mapset_old_path, "%s/%s/%s", gisdbase_old, location_old,
	       mapset_old);
    monitor = G__getenv("MONITOR");

    /* New values */
    if (gisdbase_opt->answer)
	gisdbase_new = gisdbase_opt->answer;
    else
	gisdbase_new = gisdbase_old;

    if (location_opt->answer)
	location_new = location_opt->answer;
    else
	location_new = location_old;

    if (f_list->answer) {
	char **ms;
	int nmapsets;

	G__setenv("LOCATION_NAME", location_new);
	G__setenv("GISDBASE", gisdbase_new);

	ms = G_available_mapsets();

	for (nmapsets = 0; ms[nmapsets]; nmapsets++) {
	    if (G__mapset_permissions(ms[nmapsets]) > 0) {
		fprintf(stdout, "%s ", ms[nmapsets]);
	    }
	}
	fprintf(stdout, "\n");

	exit(EXIT_SUCCESS);
    }

    mapset_new = mapset_opt->answer;
    G_asprintf(&mapset_new_path, "%s/%s/%s", gisdbase_new, location_new,
	       mapset_new);

    /* TODO: this should be checked better (repeated '/' etc.) */
    if (strcmp(mapset_old_path, mapset_new_path) == 0)
	G_fatal_error(_("<%s> is already the current mapset"), mapset_new);

    /* Check if the mapset exists and user is owner */
    G_debug(2, "check : %s", mapset_new_path);

    ret = G__mapset_permissions2(gisdbase_new, location_new, mapset_new);
    switch (ret) {
    case 0:
	G_fatal_error(_("You don't have permission to use this mapset"));
	break;
    case -1:
	if (f_add->answer == TRUE) {
	    G_debug(2, "Mapset %s doesn't exist, attempting to create it",
		    mapset_new);
	    G_make_mapset(gisdbase_new, location_new, mapset_new);
	}
	else
	    G_fatal_error(_("The mapset does not exist. Use -c flag to create it."));
	break;
    default:
	break;
    }

    /* Check if the mapset is in use */
    gis_lock = getenv("GIS_LOCK");
    if (!gis_lock)
	G_fatal_error(_("Unable to read GIS_LOCK environment variable"));

    G_asprintf(&lock_prog, "%s/etc/lock", G_gisbase());

    sprintf(path, "%s/.gislock", mapset_new_path);
    G_debug(2, path);

    ret = G_spawn(lock_prog, lock_prog, path, gis_lock, NULL);
    G_debug(2, "lock result = %d", ret);
    G_free(lock_prog);

    /* Warning: the value returned by system() is not that returned by exit() in executed program
     *          e.g. exit(1) -> 256 (multiplied by 256) */
    if (ret != 0)
	G_fatal_error(_("%s is currently running GRASS in selected mapset or lock file cannot be checked"),
		      G_whoami());

    /* Erase monitors */
    G_message(_("Erasing monitors..."));
    while ((cap = R_parse_monitorcap(MON_NEXT, "")) != NULL) {
	G__setenv("MONITOR", cap->name);
	R__open_quiet();
	if (R_open_driver() == 0) {
	    D_erase(DEFAULT_BG_COLOR);
	    D_add_to_list("d.erase");
	    R_close_driver();
	    R_release_driver();
	}
    }
    if (monitor)
	G_setenv("MONITOR", monitor);

    /* Clean temporary directory */
    sprintf(path, "%s/etc/clean_temp", G_gisbase());
    G_verbose_message(_("Cleaning up temporary files..."));
    G_spawn(path, "clean_temp", NULL);

    /* Reset variables */
    G_setenv("GISDBASE", gisdbase_new);
    G_setenv("LOCATION_NAME", location_new);
    G_setenv("MAPSET", mapset_new);

    /* Remove old lock */
    sprintf(path, "%s/.gislock", mapset_old_path);
    remove(path);

    G_free(mapset_old_path);

    G_important_message(_("Your shell continues to use the history for the old mapset"));

    if ((shell = getenv("SHELL"))) {
	if (strstr(shell, "bash")) {
	    G_important_message(_("You can switch the history by commands:\n"
				  "history -w; history -r %s/.bash_history; HISTFILE=%s/.bash_history"),
				mapset_new_path, mapset_new_path);
	}
	else if (strstr(shell, "tcsh")) {
	    G_important_message(_("You can switch the history by commands:\n"
				  "history -S; history -L %s/.history; setenv histfile=%s/.history"),
				mapset_new_path, mapset_new_path);
	}
    }

    G_message(_("Your current mapset is <%s>"), mapset_new);
    
    G_free(mapset_new_path);

    return (EXIT_SUCCESS);
}
Exemple #12
0
/* unused, coor file is never loaded to memory. Remove ? MM 2010 */
int dig_file_load(struct gvfile * file)
{
    int ret, mode, load;
    const char *cmode;
    size_t size;
    STRUCT_STAT sbuf;

    G_debug(2, "dig_file_load ()");

    if (file->file == NULL) {
	G_warning(_("Unable to load file to memory, file not open"));
	return -1;
    }

    /* Get mode */
    mode = GV_MEMORY_NEVER;
    cmode = G__getenv("GV_MEMORY");
    if (cmode != NULL) {
	if (G_strcasecmp(cmode, "ALWAYS") == 0)
	    mode = GV_MEMORY_ALWAYS;
	else if (G_strcasecmp(cmode, "NEVER") == 0)
	    mode = GV_MEMORY_NEVER;
	else if (G_strcasecmp(cmode, "AUTO") == 0)
	    mode = GV_MEMORY_AUTO;
	else
	    G_warning(_("Vector memory mode not supported, using 'AUTO'"));
    }
    G_debug(2, "  requested mode = %d", mode);


    fstat(fileno(file->file), &sbuf);
    size = sbuf.st_size;

    G_debug(2, "  size = %lu", (long unsigned int) size);

    /* Decide if the file should be loaded */
    /* TODO: I don't know how to get size of free memory (portability) to decide if load or not for auto */
    if (mode == GV_MEMORY_AUTO)
	mode = GV_MEMORY_NEVER;
    if (mode == GV_MEMORY_ALWAYS)
	load = 1;
    else
	load = 0;

    if (load) {
	file->start = G_malloc(size);
	if (file->start == NULL)
	    return -1;

	G_fseek(file->file, 0L, 0);
	ret = fread(file->start, size, 1, file->file);	/* Better to read in smaller portions? */
	G_fseek(file->file, 0L, 0);	/* reset to the beginning */

	if (ret <= 0) {
	    G_free(file->start);
	    return -1;
	}

	file->alloc = size;
	file->size = size;
	file->current = file->start;
	file->end = file->start + size;

	file->loaded = 1;
	G_debug(2, "  file was loaded to the memory");
	return 1;
    }
    else {
	G_debug(2, "  file was not loaded to the memory");
    }

    return 0;
}
Exemple #13
0
/*!
 * \brief Build topo for area from lines
 *
 * Area is built in clockwise order.
 * Take a given line and start off to the RIGHT/LEFT and try to complete
 * an area. 
 * 
 * Possible Scenarios:
 *  - I.    path runs into first line.                              : AREA!
 *  - II.   path runs into a dead end (no other area lines at node) : no area
 *  - III.  path runs into a previous line that is not 1st line or to 1st line but not to start node : no area
 *
 * After we find an area then we call point_in_area() to see if the
 * specified point is w/in the area
 *
 * Old returns  -1:  error   0:  no area    (1:  point in area)
 *              -2: island  !!
 *
 * \param[in] plus pointer to Plus_head structure
 * \param[in] first_line line id of first line
 * \param[in] side side of line to build area on (GV_LEFT | GV_RIGHT)
 * \param[in] lines pointer to array of lines
 *
 * \return  -1 on error   
 * \return   0 no area
 * \return   number of lines
 */
int
dig_build_area_with_line(struct Plus_head *plus, plus_t first_line, int side,
			 plus_t ** lines)
{
    register int i;
    int prev_line, next_line;
    static plus_t *array;
    char *p;
    static int array_size;	/* 0 on startup */
    int n_lines;
    struct P_line *Line;
    struct P_topo_b *topo;
    int node;

    if (debug_level == -1) {
	const char *dstr = G__getenv("DEBUG");

	if (dstr != NULL)
	    debug_level = atoi(dstr);
	else
	    debug_level = 0;
    }

    G_debug(3, "dig_build_area_with_line(): first_line = %d, side = %d",
	    first_line, side);

    /* First check if line is not degenerated (degenerated lines have angle -9) 
     *  Following degenerated lines are skip by dig_angle_next_line() */
    Line = plus->Line[first_line];
    if (Line->type != GV_BOUNDARY)
	return -1;

    topo = (struct P_topo_b *)Line->topo;
    node = topo->N1;		/* to check one is enough, because if degenerated N1 == N2 */
    if (dig_node_line_angle(plus, node, first_line) == -9.) {
	G_debug(3, "First line degenerated");
	return (0);
    }

    if (array_size == 0) {	/* first time */
	array_size = 1000;
	array = (plus_t *) dig__falloc(array_size, sizeof(plus_t));
	if (array == NULL)
	    return (dig_out_of_memory());
    }

    if (side == GV_LEFT) {
	first_line = -first_line;	/* start at node1, reverse direction */
    }
    array[0] = first_line;
    prev_line = -first_line;	/* start at node2 for direct and node1 for
				   reverse direction */
    /* angle of first line */
    n_lines = 1;
    while (1) {
	next_line =
	    dig_angle_next_line(plus, prev_line, GV_RIGHT, GV_BOUNDARY);
	G_debug(3, "next_line = %d", next_line);

	if (next_line == 0)
	    return (-1);	/* Not found */

	/* Check if adjacent lines do not have the same angle */
	if (!dig_node_angle_check(plus, next_line, GV_BOUNDARY)) {
	    G_debug(3,
		    "Cannot build area, a neighbour of the line %d has the same angle at the node",
		    next_line);
	    return 0;
	}

	/*  I. Area closed. This also handles the problem w/ 1 single area line */
	if (first_line == next_line) {
	    /* GOT ONE!  fill area struct  and return */
	    G_debug(3, "Got one! :");

	    /* avoid loop when not debugging */
	    if (debug_level > 2) {
		for (i = 0; i < n_lines; i++) {
		    G_debug(3, " area line (%d) = %d", i, array[i]);
		}
	    }

	    *lines = array;
	    return (n_lines);
	}

	/* II. Note this is a dead end */
	/* ( if prev_line != -first_line so it goes after the previous test) ? */
	if (prev_line == next_line) {
	    G_debug(3, "Dead_end:");
	    return (0);		/* dead end */
	}

	/* III. Unclosed ?, I would say started from free end */
	for (i = 0; i < n_lines; i++)
	    if (abs(next_line) == abs(array[i])) {
		G_debug(3, "Unclosed area:");
		return (0);	/* ran into a different area */
	    }

	/* otherwise keep going */
	if (n_lines >= array_size) {
	    p = dig__frealloc(array, array_size + 100, sizeof(plus_t),
			      array_size);
	    if (p == NULL)
		return (dig_out_of_memory());
	    array = (plus_t *) p;
	    array_size += 100;
	}
	array[n_lines++] = next_line;
	prev_line = -next_line;
    }

    return 0;
}
Exemple #14
0
/*!
 * \brief Find number line of next angle to follow an line
 *
 * Assume that lines are sorted in increasing angle order and angles
 * of points and degenerated lines are set to 9 (ignored).
 *
 * \param[in] plus pointer to Plus_head structure
 * \param[in] current_line current line id, negative if request for node 2
 * \param[in] side side GV_RIGHT or GV_LEFT
 * \param[in] type line type (GV_LINE, GV_BOUNDARY or both)
 *
 * \return line number of next angle to follow an line (negative if connected by node2)
 *               (number of current line may be return if dangle - this is used in build)
 * \return 0 on error or not found
 */
int
dig_angle_next_line(struct Plus_head *plus, plus_t current_line, int side,
		    int type)
{
    int i, next;
    int current;
    int line;
    plus_t node;
    struct P_node *Node;
    struct P_line *Line;

    if (debug_level == -1) {
	const char *dstr = G__getenv("DEBUG");

	if (dstr != NULL)
	    debug_level = atoi(dstr);
	else
	    debug_level = 0;
    }

    G_debug(3, "dig__angle_next_line: line = %d, side = %d, type = %d",
	    current_line, side, type);

    Line = plus->Line[abs(current_line)];
    
    if (!(Line->type & GV_LINES))
	return 0;

    node = 0;
    if (current_line > 0) {
	if (Line->type == GV_LINE) {
	    struct P_topo_l *topo = (struct P_topo_l *)Line->topo;
	    node = topo->N1;
	}
	else if (Line->type == GV_BOUNDARY) {
	    struct P_topo_b *topo = (struct P_topo_b *)Line->topo;
	    node = topo->N1;
	}
    }
    else {
	if (Line->type == GV_LINE) {
	    struct P_topo_l *topo = (struct P_topo_l *)Line->topo;
	    node = topo->N2;
	}
	else if (Line->type == GV_BOUNDARY) {
	    struct P_topo_b *topo = (struct P_topo_b *)Line->topo;
	    node = topo->N2;
	}
    }

    G_debug(3, " node = %d", node);

    Node = plus->Node[node];
    G_debug(3, "  n_lines = %d", Node->n_lines);
    /* avoid loop when not debugging */
    if (debug_level > 2) {
	for (i = 0; i < Node->n_lines; i++) {
	    G_debug(3, "  i = %d line = %d angle = %f", i, Node->lines[i],
		    Node->angles[i]);
	}
    }

    /* first find index for that line */
    next = -1;
    for (current = 0; current < Node->n_lines; current++) {
	if (Node->lines[current] == current_line)
	    next = current;
    }
    if (next == -1)
	return 0;		/* not found */

    G_debug(3, "  current position = %d", next);
    while (1) {
	if (side == GV_RIGHT) {	/* go up (greater angle) */
	    if (next == Node->n_lines - 1)
		next = 0;
	    else
		next++;
	}
	else {			/* go down (smaller angle) */
	    if (next == 0)
		next = Node->n_lines - 1;
	    else
		next--;
	}
	G_debug(3, "  next = %d line = %d angle = %f", next,
		Node->lines[next], Node->angles[next]);

	if (Node->angles[next] == -9.) {	/* skip points and degenerated */
	    G_debug(3, "  point/degenerated -> skip");
	    if (Node->lines[next] == current_line)
		break;		/* Yes, that may happen if input line is degenerated and isolated and this breaks loop */
	    else
		continue;
	}

	line = abs(Node->lines[next]);
	Line = plus->Line[line];

	if (Line->type & type) {	/* line found */
	    G_debug(3, "  this one");
	    return (Node->lines[next]);
	}

	/* input line reached, this must be last, because current_line may be correct return value (dangle) */
	if (Node->lines[next] == current_line)
	    break;
    }
    G_debug(3, "  Line NOT found at node %d", (int)node);
    return 0;
}
Exemple #15
0
/*!
  \brief Open display driver

  Default display driver is Cairo, if not available PNG is used.

  \return 0 on success
  \return 1 no monitor defined
*/
int D_open_driver(void)
{
    const char *p, *m;
    
    G_debug(1, "D_open_driver():");
    p = getenv("GRASS_RENDER_IMMEDIATE");
    m = G__getenv("MONITOR");
    
    if (m && G_strncasecmp(m, "wx", 2) == 0) {
	/* wx monitors always use GRASS_RENDER_IMMEDIATE. */
	p = NULL; /* use default display driver */
    } else if (m) {
	char *env;
	const char *v;
	char *u_m;
	
	if (p)
	    G_warning(_("%s variable defined, %s ignored"),
		      "MONITOR", "GRASS_RENDER_IMMEDIATE");
	/* GRASS variable names should be upper case. */
	u_m = G_store_upper(m);

	env = NULL;
	G_asprintf(&env, "MONITOR_%s_MAPFILE", u_m);
	v = G__getenv(env);
	p = m;

	if (v) {
	    if (G_strcasecmp(p, "ps") == 0)
		G_putenv("GRASS_PSFILE", v);
	    else
		G_putenv("GRASS_PNGFILE", v);
	}
	
	G_asprintf(&env, "MONITOR_%s_ENVFILE", u_m);
	v = G__getenv(env);
	if (v) 
	    read_env_file(v);
    }
    
    const struct driver *drv =
	(p && G_strcasecmp(p, "PNG")   == 0) ? PNG_Driver() :
	(p && G_strcasecmp(p, "PS")    == 0) ? PS_Driver() :
	(p && G_strcasecmp(p, "HTML")  == 0) ? HTML_Driver() :
#ifdef USE_CAIRO
	(p && G_strcasecmp(p, "cairo") == 0) ? Cairo_Driver() :
	Cairo_Driver();
#else
	PNG_Driver();
#endif
	
    if (p && G_strcasecmp(drv->name, p) != 0)
	G_warning(_("Unknown display driver <%s>"), p);
    G_verbose_message(_("Using display driver <%s>..."), drv->name);
    LIB_init(drv);

    init();

    if (!getenv("GRASS_RENDER_IMMEDIATE") && !m)
	return 1;

    return 0;
}
Exemple #16
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

    int fdi,			/* input map file descriptor    */
      fdo,			/* output map file descriptor   */
      method,			/* position of method in table  */
      permissions,		/* mapset permissions           */
      cell_type,		/* output celltype              */
      cell_size,		/* size of a cell in bytes      */
      row, col,			/* counters                     */
      irows, icols,		/* original rows, cols          */
      orows, ocols, have_colors,	/* Input map has a colour table */
      overwrite,		/* Overwrite                    */
      curr_proj;		/* output projection (see gis.h) */

    void *obuffer,		/* buffer that holds one output row     */
     *obufptr;			/* column ptr in output buffer  */
    struct cache *ibuffer;	/* buffer that holds the input map      */
    func interpolate;		/* interpolation routine        */

    double xcoord1, xcoord2,	/* temporary x coordinates      */
      ycoord1, ycoord2,		/* temporary y coordinates      */
      col_idx,			/* column index in input matrix */
      row_idx,			/* row index in input matrix    */
      onorth, osouth,		/* save original border coords  */
      oeast, owest, inorth, isouth, ieast, iwest;
    char north_str[30], south_str[30], east_str[30], west_str[30];

    struct Colors colr;		/* Input map colour table       */
    struct History history;

    struct pj_info iproj,	/* input map proj parameters    */
      oproj;			/* output map proj parameters   */

    struct Key_Value *in_proj_info,	/* projection information of    */
     *in_unit_info,		/* input and output mapsets     */
     *out_proj_info, *out_unit_info;

    struct GModule *module;

    struct Flag *list,		/* list files in source location */
     *nocrop,			/* don't crop output map        */
     *print_bounds,		/* print output bounds and exit */
     *gprint_bounds;		/* same but print shell style	*/

    struct Option *imapset,	/* name of input mapset         */
     *inmap,			/* name of input layer          */
     *inlocation,		/* name of input location       */
     *outmap,			/* name of output layer         */
     *indbase,			/* name of input database       */
     *interpol,			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
     *memory,			/* amount of memory for cache   */
     *res;			/* resolution of target map     */
    struct Cell_head incellhd,	/* cell header of input map     */
      outcellhd;		/* and output map               */


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    module->description =
	_("Re-projects a raster map from given location to the current location.");

    inmap = G_define_standard_option(G_OPT_R_INPUT);
    inmap->description = _("Name of input raster map to re-project");
    inmap->required = NO;
    inmap->guisection = _("Source");

    inlocation = G_define_option();
    inlocation->key = "location";
    inlocation->type = TYPE_STRING;
    inlocation->required = YES;
    inlocation->description = _("Location containing input raster map");
    inlocation->gisprompt = "old,location,location";
    inlocation->key_desc = "name";

    imapset = G_define_standard_option(G_OPT_M_MAPSET);
    imapset->label = _("Mapset containing input raster map");
    imapset->description = _("default: name of current mapset");
    imapset->guisection = _("Source");

    indbase = G_define_option();
    indbase->key = "dbase";
    indbase->type = TYPE_STRING;
    indbase->required = NO;
    indbase->description = _("Path to GRASS database of input location");
    indbase->gisprompt = "old,dbase,dbase";
    indbase->key_desc = "path";
    indbase->guisection = _("Source");

    outmap = G_define_standard_option(G_OPT_R_OUTPUT);
    outmap->required = NO;
    outmap->description = _("Name for output raster map (default: same as 'input')");
    outmap->guisection = _("Target");

    ipolname = make_ipol_list();
    
    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");
    interpol->guisection = _("Target");
    interpol->descriptions = make_ipol_desc();

    memory = G_define_option();
    memory->key = "memory";
    memory->type = TYPE_INTEGER;
    memory->required = NO;
    memory->description = _("Cache size (MiB)");

    res = G_define_option();
    res->key = "resolution";
    res->type = TYPE_DOUBLE;
    res->required = NO;
    res->description = _("Resolution of output raster map");
    res->guisection = _("Target");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List raster maps in input location and exit");

    nocrop = G_define_flag();
    nocrop->key = 'n';
    nocrop->description = _("Do not perform region cropping optimization");

    print_bounds = G_define_flag();
    print_bounds->key = 'p';
    print_bounds->description =
	_("Print input map's bounds in the current projection and exit");
    print_bounds->guisection = _("Target");
    
    gprint_bounds = G_define_flag();
    gprint_bounds->key = 'g';
    gprint_bounds->description =
	_("Print input map's bounds in the current projection and exit (shell style)");
    gprint_bounds->guisection = _("Target");

    /* The parser checks if the map already exists in current mapset,
       we switch out the check and do it
       in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

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


    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    mapname = outmap->answer ? outmap->answer : inmap->answer;
    if (mapname && !list->answer && !overwrite &&
	G_find_raster(mapname, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);

    setname = imapset->answer ? imapset->answer : G_store(G_mapset());
    if (strcmp(inlocation->answer, G_location()) == 0 &&
        (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
#if 0
	G_fatal_error(_("Input and output locations can not be the same"));
#else
	G_warning(_("Input and output locations are the same"));
#endif
    G_get_window(&outcellhd);

    if(gprint_bounds->answer && !print_bounds->answer)
	print_bounds->answer = gprint_bounds->answer;
    curr_proj = G_projection();

    /* Get projection info for output mapset */
    if ((out_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of output raster map"));

    if ((out_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of output raster map"));

    if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of output raster map"));

    /* Change the location           */
    G__create_alt_env();
    G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
    G__setenv("LOCATION_NAME", inlocation->answer);

    permissions = G__mapset_permissions(setname);
    if (permissions < 0)	/* can't access mapset       */
	G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
		      setname, inlocation->answer,
		      permissions == 0 ? _("permission denied")
		      : _("not found"));

    /* if requested, list the raster maps in source location - MN 5/2001 */
    if (list->answer) {
	int i;
	char **list;
	G_verbose_message(_("Checking location <%s> mapset <%s>"),
			  inlocation->answer, setname);
	list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
		      G__getenv("LOCATION_NAME"), setname);
	for (i = 0; list[i]; i++) {
	    fprintf(stdout, "%s\n", list[i]);
	}
	fflush(stdout);
	exit(EXIT_SUCCESS);	/* leave r.proj after listing */
    }

    if (!inmap->answer)
	G_fatal_error(_("Required parameter <%s> not set"), inmap->key);

    if (!G_find_raster(inmap->answer, setname))
	G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
		      inmap->answer, inlocation->answer, setname);

    /* Read input map colour table */
    have_colors = Rast_read_colors(inmap->answer, setname, &colr);

    /* Get projection info for input mapset */
    if ((in_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of input map"));

    if ((in_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of input map"));

    if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of input map"));

    G_free_key_value(in_proj_info);
    G_free_key_value(in_unit_info);
    G_free_key_value(out_proj_info);
    G_free_key_value(out_unit_info);
    if (G_verbose() > G_verbose_std())
	pj_print_proj_params(&iproj, &oproj);

    /* this call causes r.proj to read the entire map into memeory */
    Rast_get_cellhd(inmap->answer, setname, &incellhd);

    Rast_set_input_window(&incellhd);

    if (G_projection() == PROJECTION_XY)
	G_fatal_error(_("Unable to work with unprojected data (xy location)"));

    /* Save default borders so we can show them later */
    inorth = incellhd.north;
    isouth = incellhd.south;
    ieast = incellhd.east;
    iwest = incellhd.west;
    irows = incellhd.rows;
    icols = incellhd.cols;

    onorth = outcellhd.north;
    osouth = outcellhd.south;
    oeast = outcellhd.east;
    owest = outcellhd.west;
    orows = outcellhd.rows;
    ocols = outcellhd.cols;


    if (print_bounds->answer) {
	G_message(_("Input map <%s@%s> in location <%s>:"),
	    inmap->answer, setname, inlocation->answer);

	if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
	if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));

	G_format_northing(inorth, north_str, curr_proj);
	G_format_northing(isouth, south_str, curr_proj);
	G_format_easting(ieast, east_str, curr_proj);
	G_format_easting(iwest, west_str, curr_proj);

	if(gprint_bounds->answer) {
	    fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
		north_str, south_str, west_str, east_str, irows, icols);
	}
	else {
	    fprintf(stdout, "Source cols: %d\n", icols);
	    fprintf(stdout, "Source rows: %d\n", irows);
	    fprintf(stdout, "Local north: %s\n",  north_str);
	    fprintf(stdout, "Local south: %s\n", south_str);
	    fprintf(stdout, "Local west: %s\n", west_str);
	    fprintf(stdout, "Local east: %s\n", east_str);
	}

	/* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */

	exit(EXIT_SUCCESS);
    }


    /* Cut non-overlapping parts of input map */
    if (!nocrop->answer)
	bordwalk(&outcellhd, &incellhd, &oproj, &iproj);

    /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
    /* (should probably be a factor based on input and output resolution) */
    incellhd.north += 2 * incellhd.ns_res;
    incellhd.east += 2 * incellhd.ew_res;
    incellhd.south -= 2 * incellhd.ns_res;
    incellhd.west -= 2 * incellhd.ew_res;
    if (incellhd.north > inorth)
	incellhd.north = inorth;
    if (incellhd.east > ieast)
	incellhd.east = ieast;
    if (incellhd.south < isouth)
	incellhd.south = isouth;
    if (incellhd.west < iwest)
	incellhd.west = iwest;

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

    if (!nocrop->answer)
	bordwalk(&incellhd, &outcellhd, &iproj, &oproj);

#if 0
    outcellhd.west = outcellhd.south = HUGE_VAL;
    outcellhd.east = outcellhd.north = -HUGE_VAL;
    for (row = 0; row < incellhd.rows; row++) {
	ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
	for (col = 0; col < incellhd.cols; col++) {
	    xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
	    pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
	    if (xcoord1 > outcellhd.east)
		outcellhd.east = xcoord1;
	    if (ycoord1 > outcellhd.north)
		outcellhd.north = ycoord1;
	    if (xcoord1 < outcellhd.west)
		outcellhd.west = xcoord1;
	    if (ycoord1 < outcellhd.south)
		outcellhd.south = ycoord1;
	}
    }
#endif

    if (res->answer != NULL)	/* set user defined resolution */
	outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);

    G_adjust_Cell_head(&outcellhd, 0, 0);
    Rast_set_output_window(&outcellhd);

    G_message(" ");
    G_message(_("Input:"));
    G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
    G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
    G_message(_("North: %f (%f)"), incellhd.north, inorth);
    G_message(_("South: %f (%f)"), incellhd.south, isouth);
    G_message(_("West: %f (%f)"), incellhd.west, iwest);
    G_message(_("East: %f (%f)"), incellhd.east, ieast);
    G_message(_("EW-res: %f"), incellhd.ew_res);
    G_message(_("NS-res: %f"), incellhd.ns_res);
    G_message(" ");

    G_message(_("Output:"));
    G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
    G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
    G_message(_("North: %f (%f)"), outcellhd.north, onorth);
    G_message(_("South: %f (%f)"), outcellhd.south, osouth);
    G_message(_("West: %f (%f)"), outcellhd.west, owest);
    G_message(_("East: %f (%f)"), outcellhd.east, oeast);
    G_message(_("EW-res: %f"), outcellhd.ew_res);
    G_message(_("NS-res: %f"), outcellhd.ns_res);
    G_message(" ");

    /* open and read the relevant parts of the input map and close it */
    G__switch_env();
    Rast_set_input_window(&incellhd);
    fdi = Rast_open_old(inmap->answer, setname);
    cell_type = Rast_get_map_type(fdi);
    ibuffer = readcell(fdi, memory->answer);
    Rast_close(fdi);

    G__switch_env();
    Rast_set_output_window(&outcellhd);

    if (strcmp(interpol->answer, "nearest") == 0) {
	fdo = Rast_open_new(mapname, cell_type);
	obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
    }
    else {
	fdo = Rast_open_fp_new(mapname);
	cell_type = FCELL_TYPE;
	obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
    }

    cell_size = Rast_cell_size(cell_type);

    xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
    /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
    /**/ G_important_message(_("Projecting..."));
    G_percent(0, outcellhd.rows, 2);

    for (row = 0; row < outcellhd.rows; row++) {
	obufptr = obuffer;

	for (col = 0; col < outcellhd.cols; col++) {
	    /* project coordinates in output matrix to       */
	    /* coordinates in input matrix                   */
	    if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
		Rast_set_null_value(obufptr, 1, cell_type);
	    else {
		/* convert to row/column indices of input matrix */
		col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
		row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;

		/* and resample data point               */
		interpolate(ibuffer, obufptr, cell_type,
			    &col_idx, &row_idx, &incellhd);
	    }

	    obufptr = G_incr_void_ptr(obufptr, cell_size);
	    xcoord2 += outcellhd.ew_res;
	    xcoord1 = xcoord2;
	    ycoord1 = ycoord2;
	}

	Rast_put_row(fdo, obuffer, cell_type);

	xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
	ycoord2 -= outcellhd.ns_res;
	ycoord1 = ycoord2;
	G_percent(row, outcellhd.rows - 1, 2);
    }

    Rast_close(fdo);

    if (have_colors > 0) {
	Rast_write_colors(mapname, G_mapset(), &colr);
	Rast_free_colors(&colr);
    }

    Rast_short_history(mapname, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(mapname, &history);

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
Exemple #17
0
int db__driver_open_database(dbHandle * handle)
{
    const char *name;
    int len;
    dbConnection connection;
    char buf[1024];
    DIR *dir;
    struct dirent *ent;
    char **tokens;
    int no_tokens, n;

    G_debug(2, "DBF: db__driver_open_database() name = '%s'",
	    db_get_handle_dbname(handle));

    db.name[0] = '\0';
    db.tables = NULL;
    db.atables = 0;
    db.ntables = 0;

    db_get_connection(&connection);
    name = db_get_handle_dbname(handle);

    /* if name is empty use connection.databaseName */
    if (strlen(name) == 0) {
	name = connection.databaseName;
    }

    strcpy(db.name, name);

    /* open database dir and read table ( *.dbf files ) names 
     * to structure */

    /* parse variables in db.name if present */
    if (db.name[0] == '$') {
	tokens = G_tokenize(db.name, "/");
	no_tokens = G_number_of_tokens(tokens);
	db.name[0] = '\0';	/* re-init */

	for (n = 0; n < no_tokens; n++) {
	    G_debug(3, "tokens[%d] = %s", n, tokens[n]);
	    if (tokens[n][0] == '$') {
		G_strchg(tokens[n], '$', ' ');
		G_chop(tokens[n]);
		strcat(db.name, G__getenv(tokens[n]));
		G_debug(3, "   -> %s", G__getenv(tokens[n]));
	    }
	    else
		strcat(db.name, tokens[n]);

	    strcat(db.name, "/");
	}
	G_free_tokens(tokens);
    }

    G_debug(2, "db.name = %s", db.name);

    errno = 0;
    dir = opendir(db.name);
    if (dir == NULL) {
	if (errno == ENOENT) {
	    int status;

	    status = G_mkdir(db.name);
	    if (status != 0) {	/* mkdir failed */
		append_error("Cannot create dbf database: %s\n", name);
		report_error();
		return DB_FAILED;
	    }
	}
	else {			/* some other problem */
	    append_error("Cannot open dbf database: %s\n", name);
	    report_error();
	    return DB_FAILED;
	}
    }

    while ((ent = readdir(dir))) {
	len = strlen(ent->d_name) - 4;
	if ((len > 0) && (G_strcasecmp(ent->d_name + len, ".dbf") == 0)) {
	    strcpy(buf, ent->d_name);
	    buf[len] = '\0';
	    add_table(buf, ent->d_name);
	}
    }

    closedir(dir);
    return DB_OK;
}