void QgsGrass::setMapset( QString gisdbase, QString location, QString mapset ) { QgsDebugMsg( QString( "gisdbase = %1 location = %2 mapset = %3" ).arg( gisdbase ).arg( location ).arg( mapset ) ); init(); // Set principal GRASS variables (in memory) #ifdef Q_OS_WIN G__setenv( "GISDBASE", shortPath( gisdbase ).toUtf8().data() ); #else G__setenv( "GISDBASE", gisdbase.toUtf8().data() ); #endif G__setenv( "LOCATION_NAME", location.toUtf8().data() ); G__setenv( "MAPSET", mapset.toUtf8().data() ); // Add all available mapsets to search path char **ms = 0; G_TRY { ms = G_available_mapsets(); } G_CATCH( QgsGrass::Exception &e ) { Q_UNUSED( e ); QgsDebugMsg( QString( "No available mapsets found: %1" ).arg( e.what() ) ); return; }
CPLErr GRASSRasterBand::ResetReading ( struct Cell_head *sNewWindow ) { /* Check if the window has changed */ if ( sNewWindow->north != sOpenWindow.north || sNewWindow->south != sOpenWindow.south || sNewWindow->east != sOpenWindow.east || sNewWindow->west != sOpenWindow.west || sNewWindow->ew_res != sOpenWindow.ew_res || sNewWindow->ns_res != sOpenWindow.ns_res || sNewWindow->rows != sOpenWindow.rows || sNewWindow->cols != sOpenWindow.cols ) { if( hCell >= 0 ) { G_close_cell( hCell ); hCell = -1; } /* Set window */ G_set_window( sNewWindow ); /* Open raster */ G__setenv( "GISDBASE", ((GRASSDataset *)poDS)->pszGisdbase ); G__setenv( "LOCATION_NAME", ((GRASSDataset *)poDS)->pszLocation ); G__setenv( "MAPSET", pszMapset); G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); if ( (hCell = G_open_cell_old( pszCellName, pszMapset)) < 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName ); this->valid = false; return CE_Failure; } G_copy((void *) &sOpenWindow, (void *) sNewWindow, sizeof(struct Cell_head)); } else { /* The windows are identical, check current window */ struct Cell_head sCurrentWindow; G_get_window ( &sCurrentWindow ); if ( sNewWindow->north != sCurrentWindow.north || sNewWindow->south != sCurrentWindow.south || sNewWindow->east != sCurrentWindow.east || sNewWindow->west != sCurrentWindow.west || sNewWindow->ew_res != sCurrentWindow.ew_res || sNewWindow->ns_res != sCurrentWindow.ns_res || sNewWindow->rows != sCurrentWindow.rows || sNewWindow->cols != sCurrentWindow.cols ) { /* Reset window */ G_set_window( sNewWindow ); } } return CE_None; }
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; }
void QgsGrassRegion::accept() { // TODO: better repaint region QSettings settings; bool on = settings.value( "/GRASS/region/on", true ).toBool(); if ( on ) { mPlugin->switchRegion( false ); // delete } QgsGrass::setLocation( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation() ); G__setenv(( char * ) "MAPSET", QgsGrass::getDefaultMapset().toLatin1().data() ); if ( G_put_window( &mWindow ) == -1 ) { QMessageBox::warning( 0, tr( "Warning" ), tr( "Cannot write region" ) ); return; } if ( on ) { mPlugin->switchRegion( on ); // draw new } saveWindowLocation(); mCanvas->setMapTool( NULL ); QDialog::accept(); }
QString QgsGrass::closeMapset( ) { QgsDebugMsg( "entered." ); if ( mMapsetLock.length() > 0 ) { QFile file( mMapsetLock ); if ( !file.remove() ) { return QObject::tr( "Cannot remove mapset lock: %1" ).arg( mMapsetLock ); } mMapsetLock = ""; putenv(( char * ) "GISRC" ); // Reinitialize GRASS G__setenv( "GISRC", ( char * ) "" ); // Temporarily commented because of // http://trac.osgeo.org/qgis/ticket/1900 // http://trac.osgeo.org/gdal/ticket/3313 // it can be uncommented once GDAL with patch gets deployed (probably GDAL 1.8) //G__setenv( "GISDBASE", ( char * ) "" ); //G__setenv( "LOCATION_NAME", ( char * ) "" ); //G__setenv( "MAPSET", ( char * ) "" ); defaultGisdbase = ""; defaultLocation = ""; defaultMapset = ""; active = 0; // Delete temporary dir // To be sure that we don't delete '/' for example if ( mTmp.left( 4 ) == "/tmp" ) { QDir dir( mTmp ); for ( unsigned int i = 0; i < dir.count(); i++ ) { if ( dir[i] == "." || dir[i] == ".." ) continue; dir.remove( dir[i] ); if ( dir.remove( dir[i] ) ) { QgsDebugMsg( QString( "Cannot remove temporary file %1" ).arg( dir[i] ) ); } } if ( !dir.rmdir( mTmp ) ) { QgsDebugMsg( QString( "Cannot remove temporary directory %1" ).arg( mTmp ) ); } } } return NULL; }
void QgsGrass::setMapset( QString gisdbase, QString location, QString mapset ) { QgsDebugMsg( QString( "gisdbase = %1 location = %2 mapset = %3" ).arg( gisdbase ).arg( location ).arg( mapset ) ); init(); // Set principal GRASS variables (in memory) #if defined(WIN32) G__setenv( "GISDBASE", shortPath( gisdbase ).toUtf8().data() ); #else G__setenv( "GISDBASE", gisdbase.toUtf8().data() ); #endif G__setenv( "LOCATION_NAME", location.toUtf8().data() ); G__setenv( "MAPSET", mapset.toUtf8().data() ); // Add all available mapsets to search path char **ms = G_available_mapsets(); for ( int i = 0; ms[i]; i++ ) G_add_mapset_to_search_path( ms[i] ); }
int G__make_location(const char *location_name, struct Cell_head *wind, struct Key_Value *proj_info, struct Key_Value *proj_units, FILE * report_file) { char path[GPATH_MAX]; int out_stat; /* Try to create the location directory, under the gisdbase. */ sprintf(path, "%s/%s", G_gisdbase(), location_name); if (G_mkdir(path) != 0) return -1; /* Make the PERMANENT mapset. */ sprintf(path, "%s/%s/%s", G_gisdbase(), location_name, "PERMANENT"); if (G_mkdir(path) != 0) return -1; /* make these the new current location and mapset */ G__setenv("LOCATION_NAME", location_name); G__setenv("MAPSET", "PERMANENT"); /* Create the default, and current window files */ G__put_window(wind, "", "DEFAULT_WIND"); G__put_window(wind, "", "WIND"); /* Write out the PROJ_INFO, and PROJ_UNITS if available. */ if (proj_info != NULL) { G__file_name(path, "", "PROJ_INFO", "PERMANENT"); G_write_key_value_file(path, proj_info, &out_stat); if (out_stat != 0) return -2; } if (proj_units != NULL) { G__file_name(path, "", "PROJ_UNITS", "PERMANENT"); G_write_key_value_file(path, proj_units, &out_stat); if (out_stat != 0) return -2; } return 0; }
void QgsGrass::setLocation( QString gisdbase, QString location ) { QgsDebugMsg( QString( "gisdbase = %1 location = %2" ).arg( gisdbase ).arg( location ) ); init(); // Set principal GRASS variables (in memory) #if defined(WIN32) G__setenv( "GISDBASE", shortPath( gisdbase ).toLocal8Bit().data() ); #else // This does not work for GISBASE with non ascii chars on Windows XP, // gives error 'LOCATION ... not available': G__setenv( "GISDBASE", gisdbase.toUtf8().constData() ); #endif G__setenv( "LOCATION_NAME", location.toUtf8().constData() ); G__setenv( "MAPSET", "PERMANENT" ); // PERMANENT must always exist // Add all available mapsets to search path char **ms = G_available_mapsets(); for ( int i = 0; ms[i]; i++ ) G_add_mapset_to_search_path( ms[i] ); }
int G__make_mapset(const char *gisdbase_name, const char *location_name, const char *mapset_name) { char path[GPATH_MAX]; struct Cell_head default_window; /* Get location */ if (location_name == NULL) location_name = G_location(); /* Get GISDBASE */ if (gisdbase_name == NULL) gisdbase_name = G_gisdbase(); /* TODO: Should probably check that user specified location and gisdbase are valid */ /* Make the mapset. */ sprintf(path, "%s/%s/%s", gisdbase_name, location_name, mapset_name); if (G_mkdir(path) != 0) return -1; G__create_alt_env(); /* Get PERMANENT default window */ G__setenv("GISDBASE", gisdbase_name); G__setenv("LOCATION", location_name); G__setenv("MAPSET", "PERMANENT"); G_get_default_window(&default_window); /* Change to the new mapset */ G__setenv("MAPSET", mapset_name); /* Copy default window/regions to new mapset */ G__put_window(&default_window, "", "WIND"); /* And switch back to original environment */ G__switch_env(); return 0; }
int get_target(void) { char location[GNAME_MAX]; char mapset[GMAPSET_MAX]; char buf[1024]; int stat; if (!I_get_target(group.name, location, mapset)) { sprintf(buf, "Target information for group [%s] missing\n", group.name); goto error; } sprintf(buf, "%s/%s", G_gisdbase(), location); if (access(buf, 0) != 0) { sprintf(buf, "Target location [%s] not found\n", location); goto error; } G_create_alt_env(); G__setenv("LOCATION_NAME", location); stat = G__mapset_permissions(mapset); if (stat > 0) { G__setenv("MAPSET", mapset); G_create_alt_search_path(); G_switch_env(); G_switch_search_path(); which_env = 0; return 1; } sprintf(buf, "Mapset [%s] in target location [%s] - ", mapset, location); strcat(buf, stat == 0 ? "permission denied\n" : "not found\n"); error: strcat(buf, "Please run i.target for group "); strcat(buf, group.name); G_fatal_error(buf); return -1; }
void QgsGrassNewMapset::createMapset() { QgsDebugMsg( "entered." ); // TODO: handle all possible errors better, especially // half created location/mapset QString location; if ( mCreateLocationRadioButton->isChecked() ) { location = mLocationLineEdit->text().trimmed(); // TODO: add QgsGrass::setLocation or G_make_location with // database path QgsGrass::activeMode(); // because it calls private gsGrass::init() #if defined(WIN32) G__setenv(( char * ) "GISDBASE", QgsGrass::shortPath( mDatabaseLineEdit->text() ).toUtf8().data() ); #else G__setenv(( char * ) "GISDBASE", mDatabaseLineEdit->text().toUtf8().data() ); #endif int ret = 0; try { ret = G_make_location( location.toUtf8().data(), &mCellHead, mProjInfo, mProjUnits, stdout ); } catch ( QgsGrass::Exception &e ) { ret = -1; Q_UNUSED( e ); } if ( ret != 0 ) { QMessageBox::warning( this, tr( "Create location" ), tr( "Cannot create new location: %1" ).arg( QgsGrass::errorMessage() ) ); return; } // Location created -> reset widgets setLocations(); mSelectLocationRadioButton->setChecked( true ); mLocationComboBox->setItemText( mLocationComboBox->currentIndex(), location ); mLocationLineEdit->setText( "" ); locationRadioSwitched(); // calls also checkLocation() } else { location = mLocationComboBox->currentText(); } // Create mapset QString mapset = mMapsetLineEdit->text().trimmed(); if ( mapset != "PERMANENT" ) { QString locationPath = mDatabaseLineEdit->text() + "/" + location; QDir d( locationPath ); if ( !d.mkdir( mapset ) ) { QMessageBox::warning( this, tr( "Create mapset" ), tr( "Cannot create new mapset directory" ) ); return; } // Copy WIND Better way to copy file in Qt? QStringList lines; QFile in( locationPath + "/PERMANENT/DEFAULT_WIND" ); if ( !in.open( QIODevice::ReadOnly ) ) { QMessageBox::warning( this, tr( "Create mapset" ), tr( "Cannot open DEFAULT_WIND" ) ); return; } QFile out( locationPath + "/" + mapset + "/WIND" ); if ( !out.open( QIODevice::WriteOnly ) ) { QMessageBox::warning( this, tr( "Create mapset" ), tr( "Cannot open WIND" ) ); return; } QTextStream stream( &out ); //QTextStream stream( &file ); QString line; char buf[100]; while ( in.readLine( buf, 100 ) != -1 ) { stream << buf; } in.close(); out.close(); } QString err = QgsGrass::openMapset( mDatabaseLineEdit->text(), location, mapset ); if ( err.length() > 0 ) { QMessageBox::information( this, tr( "New mapset" ), tr( "New mapset successfully created, but cannot be opened: %1" ).arg( err ) ); } else { QMessageBox::information( this, tr( "New mapset" ), tr( "New mapset successfully created and set as current working mapset." ) ); mPlugin->mapsetChanged(); } deleteLater(); }
int OGRGRASSDataSource::Open( const char * pszNewName, int /*bUpdate*/, int bTestOpen, int /*bSingleNewFileIn*/ ) { VSIStatBuf stat; CPLAssert( nLayers == 0 ); pszName = CPLStrdup( pszNewName ); // Released by destructor /* -------------------------------------------------------------------- */ /* Do the given path contains 'vector' and 'head'? */ /* -------------------------------------------------------------------- */ if ( strstr(pszName,"vector") == NULL || strstr(pszName,"head") == NULL ) { if( !bTestOpen ) { CPLError( CE_Failure, CPLE_AppDefined, "%s is not GRASS vector, access failed.\n", pszName ); } return FALSE; } /* -------------------------------------------------------------------- */ /* Is the given a regular file? */ /* -------------------------------------------------------------------- */ if( CPLStat( pszName, &stat ) != 0 || !VSI_ISREG(stat.st_mode) ) { if( !bTestOpen ) { CPLError( CE_Failure, CPLE_AppDefined, "%s is not GRASS vector, access failed.\n", pszName ); } return FALSE; } /* -------------------------------------------------------------------- */ /* Parse datasource name */ /* -------------------------------------------------------------------- */ if ( !SplitPath(pszName, &pszGisdbase, &pszLocation, &pszMapset, &pszMap) ) { if( !bTestOpen ) { CPLError( CE_Failure, CPLE_AppDefined, "%s is not GRASS datasource name, access failed.\n", pszName ); } return FALSE; } CPLDebug ( "GRASS", "Gisdbase: %s", pszGisdbase ); CPLDebug ( "GRASS", "Location: %s", pszLocation ); CPLDebug ( "GRASS", "Mapset: %s", pszMapset ); CPLDebug ( "GRASS", "Map: %s", pszMap ); /* -------------------------------------------------------------------- */ /* Init GRASS library */ /* -------------------------------------------------------------------- */ // GISBASE is path to the directory where GRASS is installed, // it is necessary because there are database drivers. if ( !getenv( "GISBASE" ) ) { static char* gisbaseEnv = NULL; const char *gisbase = GRASS_GISBASE; CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE " "environment variable was not set, using:\n%s", gisbase ); char buf[2000]; snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase ); buf[sizeof(buf)-1] = '\0'; CPLFree(gisbaseEnv); gisbaseEnv = CPLStrdup ( buf ); putenv( gisbaseEnv ); } // Don't use GISRC file and read/write GRASS variables // (from location G_VAR_GISRC) to memory only. G_set_gisrc_mode ( G_GISRC_MODE_MEMORY ); // Init GRASS libraries (required). G_no_gisinit() doesn't check // write permissions for mapset compare to G_gisinit() G_no_gisinit(); // Set error function G_set_error_routine ( (GrassErrorHandler) Grass2OGRErrorHook ); /* -------------------------------------------------------------------- */ /* Set GRASS variables */ /* -------------------------------------------------------------------- */ G__setenv( "GISDBASE", pszGisdbase ); G__setenv( "LOCATION_NAME", pszLocation ); G__setenv( "MAPSET", pszMapset); G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); /* -------------------------------------------------------------------- */ /* Open GRASS vector map */ /* -------------------------------------------------------------------- */ #if GRASS_VERSION_MAJOR < 7 Vect_set_fatal_error ( GV_FATAL_PRINT ); // Print error and continue #endif Vect_set_open_level (2); int level = Vect_open_old ( &map, pszMap, pszMapset); if ( level < 2 ) { CPLError( CE_Failure, CPLE_AppDefined, "Cannot open GRASS vector %s on level 2.\n", pszName ); return FALSE; } CPLDebug ( "GRASS", "Num lines = %d", Vect_get_num_lines(&map) ); /* -------------------------------------------------------------------- */ /* Build a list of layers. */ /* -------------------------------------------------------------------- */ int ncidx = Vect_cidx_get_num_fields ( &map ); CPLDebug ( "GRASS", "Num layers = %d", ncidx ); for ( int i = 0; i < ncidx; i++ ) { // Create the layer object OGRGRASSLayer *poLayer = new OGRGRASSLayer( i, &map ); // Add layer to data source layer list papoLayers = (OGRGRASSLayer **) CPLRealloc( papoLayers, sizeof(OGRGRASSLayer *) * (nLayers+1) ); papoLayers[nLayers++] = poLayer; } bOpened = TRUE; return TRUE; }
QString GRASS_EXPORT QgsGrass::openMapset( QString gisdbase, QString location, QString mapset ) { QgsDebugMsg( QString( "gisdbase = %1" ).arg( gisdbase.toUtf8().constData() ) ); QgsDebugMsg( QString( "location = %1" ).arg( location.toUtf8().constData() ) ); QgsDebugMsg( QString( "mapset = %1" ).arg( mapset.toUtf8().constData() ) ); QString mapsetPath = gisdbase + "/" + location + "/" + mapset; // Check if the mapset is in use QString gisBase = getenv( "GISBASE" ); if ( gisBase.isEmpty() ) return QObject::tr( "GISBASE is not set." ); QFileInfo fi( mapsetPath + "/WIND" ); if ( !fi.exists() ) { return QObject::tr( "%1 is not a GRASS mapset." ).arg( mapsetPath ); } QString lock = mapsetPath + "/.gislock"; #ifndef _MSC_VER int pid = getpid(); #else int pid = GetCurrentProcessId(); #endif QgsDebugMsg( QString( "pid = %1" ).arg( pid ) ); #ifndef Q_OS_WIN QFile lockFile( lock ); QProcess *process = new QProcess(); QString lockProgram( gisBase + "/etc/lock" ); QgsDebugMsg( QString( "pid = %1" ).arg( pid ) ); process->start( lockProgram, QStringList() << lock << QString::number( pid ) ); if ( !process->waitForStarted() ) { delete process; return QObject::tr( "Cannot start %1/etc/lock" ).arg( gisBase ); } process->waitForFinished( -1 ); int status = process->exitStatus(); QgsDebugMsg( QString( "status = %1" ).arg( status ) ); delete process; if ( status > 0 ) return QObject::tr( "Mapset is already in use." ); #endif // !WIN32 // Create temporary directory QFileInfo info( mapsetPath ); QString user = info.owner(); mTmp = QDir::tempPath() + "/grass6-" + user + "-" + QString::number( pid ); QDir dir( mTmp ); if ( dir.exists() ) { QFileInfo dirInfo( mTmp ); if ( !dirInfo.isWritable() ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Temporary directory %1 exists but is not writable" ).arg( mTmp ); } } else if ( !dir.mkdir( mTmp ) ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Cannot create temporary directory %1" ).arg( mTmp ); } // Create GISRC file QString globalGisrc = QDir::home().path() + "/.grassrc6"; mGisrc = mTmp + "/gisrc"; QgsDebugMsg( QString( "globalGisrc = %1" ).arg( globalGisrc ) ); QgsDebugMsg( QString( "mGisrc = %1" ).arg( mGisrc ) ); QFile out( mGisrc ); if ( !out.open( QIODevice::WriteOnly ) ) { #ifndef Q_OS_WIN lockFile.remove(); #endif return QObject::tr( "Cannot create %1" ).arg( mGisrc ); } QTextStream stream( &out ); QFile in( globalGisrc ); QString line; bool guiSet = false; char buf[1000]; if ( in.open( QIODevice::ReadOnly ) ) { while ( in.readLine( buf, 1000 ) != -1 ) { line = buf; if ( line.contains( "GISDBASE:" ) || line.contains( "LOCATION_NAME:" ) || line.contains( "MAPSET:" ) ) { continue; } if ( line.contains( "GRASS_GUI:" ) ) guiSet = true; stream << line; } in.close(); } line = "GISDBASE: " + gisdbase + "\n"; stream << line; line = "LOCATION_NAME: " + location + "\n"; stream << line; line = "MAPSET: " + mapset + "\n"; stream << line; if ( !guiSet ) { stream << "GRASS_GUI: wxpython\n"; } out.close(); // Set GISRC environment variable /* _Correct_ putenv() implementation is not making copy! */ putEnv( "GISRC", mGisrc ); // Reinitialize GRASS G__setenv( "GISRC", mGisrc.toUtf8().data() ); #if defined(WIN32) G__setenv( "GISDBASE", shortPath( gisdbase ).toLocal8Bit().data() ); #else G__setenv( "GISDBASE", gisdbase.toUtf8().data() ); #endif G__setenv( "LOCATION_NAME", location.toLocal8Bit().data() ); G__setenv( "MAPSET", mapset.toLocal8Bit().data() ); defaultGisdbase = gisdbase; defaultLocation = location; defaultMapset = mapset; active = true; #ifndef Q_OS_WIN // Close old mapset if ( mMapsetLock.length() > 0 ) { QFile file( mMapsetLock ); file.remove(); } #endif mMapsetLock = lock; return NULL; }
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); }
GDALDataset *GRASSDataset::Open( GDALOpenInfo * poOpenInfo ) { char *pszGisdb = NULL, *pszLoc = NULL; char *pszMapset = NULL, *pszElem = NULL, *pszName = NULL; char **papszCells = NULL; char **papszMapsets = NULL; /* -------------------------------------------------------------------- */ /* Does this even look like a grass file path? */ /* -------------------------------------------------------------------- */ if( strstr(poOpenInfo->pszFilename,"/cellhd/") == NULL && strstr(poOpenInfo->pszFilename,"/group/") == NULL ) return NULL; /* Always init, if no rasters are opened G_no_gisinit resets the projection and * rasters in different projection may be then opened */ // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only. G_set_gisrc_mode ( G_GISRC_MODE_MEMORY ); // Init GRASS libraries (required) G_no_gisinit(); // Doesn't check write permissions for mapset compare to G_gisinit // Set error function G_set_error_routine ( (GrassErrorHandler) Grass2CPLErrorHook ); // GISBASE is path to the directory where GRASS is installed, if ( !getenv( "GISBASE" ) ) { static char* gisbaseEnv = NULL; const char *gisbase = GRASS_GISBASE; CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE " "enviroment variable was not set, using:\n%s", gisbase ); char buf[2000]; snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase ); buf[sizeof(buf)-1] = '\0'; CPLFree(gisbaseEnv); gisbaseEnv = CPLStrdup ( buf ); putenv( gisbaseEnv ); } if ( !SplitPath( poOpenInfo->pszFilename, &pszGisdb, &pszLoc, &pszMapset, &pszElem, &pszName) ) { return NULL; } /* -------------------------------------------------------------------- */ /* Check element name */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") != 0 && strcmp(pszElem,"group") != 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } /* -------------------------------------------------------------------- */ /* Set GRASS variables */ /* -------------------------------------------------------------------- */ G__setenv( "GISDBASE", pszGisdb ); G__setenv( "LOCATION_NAME", pszLoc ); G__setenv( "MAPSET", pszMapset); // group is searched only in current mapset G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); /* -------------------------------------------------------------------- */ /* Check if this is a valid grass cell. */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") == 0 ) { if ( G_find_file2("cell", pszName, pszMapset) == NULL ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } papszMapsets = CSLAddString( papszMapsets, pszMapset ); papszCells = CSLAddString( papszCells, pszName ); } /* -------------------------------------------------------------------- */ /* Check if this is a valid GRASS imagery group. */ /* -------------------------------------------------------------------- */ else { struct Ref ref; I_init_group_ref( &ref ); if ( I_get_group_ref( pszName, &ref ) == 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } for( int iRef = 0; iRef < ref.nfiles; iRef++ ) { papszCells = CSLAddString( papszCells, ref.file[iRef].name ); papszMapsets = CSLAddString( papszMapsets, ref.file[iRef].mapset ); G_add_mapset_to_search_path ( ref.file[iRef].mapset ); } I_free_group_ref( &ref ); } G_free( pszMapset ); G_free( pszName ); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GRASSDataset *poDS; poDS = new GRASSDataset(); /* notdef: should only allow read access to an existing cell, right? */ poDS->eAccess = poOpenInfo->eAccess; poDS->pszGisdbase = pszGisdb; poDS->pszLocation = pszLoc; poDS->pszElement = pszElem; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ #if GRASS_VERSION_MAJOR >= 7 Rast_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ); #else if( G_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ) != 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster header"); delete poDS; return NULL; } #endif poDS->nRasterXSize = poDS->sCellInfo.cols; poDS->nRasterYSize = poDS->sCellInfo.rows; poDS->adfGeoTransform[0] = poDS->sCellInfo.west; poDS->adfGeoTransform[1] = poDS->sCellInfo.ew_res; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = poDS->sCellInfo.north; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -1 * poDS->sCellInfo.ns_res; /* -------------------------------------------------------------------- */ /* Try to get a projection definition. */ /* -------------------------------------------------------------------- */ struct Key_Value *projinfo, *projunits; projinfo = G_get_projinfo(); projunits = G_get_projunits(); poDS->pszProjection = GPJ_grass_to_wkt ( projinfo, projunits, 0, 0); if (projinfo) G_free_key_value(projinfo); if (projunits) G_free_key_value(projunits); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; papszCells[iBand] != NULL; iBand++ ) { GRASSRasterBand *rb = new GRASSRasterBand( poDS, iBand+1, papszMapsets[iBand], papszCells[iBand] ); if ( !rb->valid ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster band %d", iBand); delete rb; delete poDS; return NULL; } poDS->SetBand( iBand+1, rb ); } CSLDestroy(papszCells); CSLDestroy(papszMapsets); /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { delete poDS; CPLError( CE_Failure, CPLE_NotSupported, "The GRASS driver does not support update access to existing" " datasets.\n" ); return NULL; } return poDS; }
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); }
/*! \brief Get driver (?) \param argc, argv arguments \return 0 on success \return 1 on failure */ int db_driver(int argc, char *argv[]) { int stat; int procnum; int i; int rfd, wfd; FILE *send, *recv; char *modestr; /* Read and set environment variables, see dbmi_client/start.c */ if ((modestr = getenv("GRASS_DB_DRIVER_GISRC_MODE"))) { int mode; mode = atoi(modestr); if (mode == G_GISRC_MODE_MEMORY) { G_set_gisrc_mode(G_GISRC_MODE_MEMORY); G__setenv("DEBUG", getenv("DEBUG")); G__setenv("GISDBASE", getenv("GISDBASE")); G__setenv("LOCATION_NAME", getenv("LOCATION_NAME")); G__setenv("MAPSET", getenv("MAPSET")); G_debug(3, "Driver GISDBASE set to '%s'", G_getenv("GISDBASE")); } } #ifdef __MINGW32__ /* TODO: */ /* We should close everything except stdin, stdout but _fcloseall() * closes open streams not file descriptors. _getmaxstdio too big number. * * Because the pipes were created just before this driver was started * the file descriptors should not be above a closed descriptor * until it was run from a multithread application and some descriptors * were closed in the mean time. * Also Windows documentation does not say that new file descriptor is * the lowest available. */ { int err_count = 0; int cfd = 3; while (1) { if (close(cfd) == -1) err_count++; /* no good reason for 10 */ if (err_count > 10) break; cfd++; } } #endif send = stdout; recv = stdin; /* THIS CODE IS FOR DEBUGGING WITH CODECENTER */ /**********************************************/ if (argc == 3) { rfd = wfd = -1; sscanf(argv[1], "%d", &rfd); sscanf(argv[2], "%d", &wfd); send = fdopen(wfd, "w"); if (send == NULL) { db_syserror(argv[1]); exit(1); } recv = fdopen(rfd, "r"); if (recv == NULL) { db_syserror(argv[2]); exit(1); } } /**********************************************/ db_clear_error(); db_auto_print_errors(0); db_auto_print_protocol_errors(1); db__init_driver_state(); #ifndef USE_BUFFERED_IO setbuf(recv, NULL); setbuf(send, NULL); #endif db__set_protocol_fds(send, recv); if (db_driver_init(argc, argv) == DB_OK) db__send_success(); else { db__send_failure(); exit(1); } stat = DB_OK; /* get the procedure number */ while (db__recv_procnum(&procnum) == DB_OK) { #ifdef __MINGW32__ if (procnum == DB_PROC_SHUTDOWN_DRIVER) { db__send_procedure_ok(procnum); break; } #endif db_clear_error(); /* find this procedure */ for (i = 0; procedure[i].routine; i++) if (procedure[i].procnum == procnum) break; /* if found, call it */ if (procedure[i].routine) { if ((stat = db__send_procedure_ok(procnum)) != DB_OK) break; /* while loop */ if ((stat = (*procedure[i].routine) ()) != DB_OK) break; } else if ((stat = db__send_procedure_not_implemented(procnum)) != DB_OK) break; } db_driver_finish(); exit(stat == DB_OK ? 0 : 1); }
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); }
int main(int argc, char *argv[]) { struct GModule *module; struct Option *group_opt; char location[GMAPSET_MAX]; char mapset[GMAPSET_MAX]; char group[GNAME_MAX]; char buf[100]; int stat; /* must run in a term window */ G_putenv("GRASS_UI_TERM", "1"); G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("imagery, orthorectify"); module->description = _("Interactively select or modify the target elevation model."); group_opt = G_define_standard_option(G_OPT_I_GROUP); group_opt->description = _("Name of imagery group for ortho-rectification"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); elev_layer = (char *)G_malloc(GNAME_MAX * sizeof(char)); mapset_elev = (char *)G_malloc(GMAPSET_MAX * sizeof(char)); tl = (char *)G_malloc(80 * sizeof(char)); math_exp = (char *)G_malloc(80 * sizeof(char)); units = (char *)G_malloc(80 * sizeof(char)); nd = (char *)G_malloc(80 * sizeof(char)); *elev_layer = 0; *mapset_elev = 0; *tl = 0; *math_exp = 0; *units = 0; *nd = 0; strcpy(group, group_opt->answer); G_suppress_warnings(1); if (!I_get_target(group, location, mapset)) { sprintf(buf, _("Target information for group [%s] missing\n"), group); goto error; } G_suppress_warnings(0); sprintf(buf, "%s/%s", G_gisdbase(), location); if (access(buf, 0) != 0) { sprintf(buf, _("Target location [%s] not found\n"), location); goto error; } I_get_group_elev(group, elev_layer, mapset_elev, tl, math_exp, units, nd); G__create_alt_env(); G__setenv("LOCATION_NAME", location); stat = G__mapset_permissions(mapset); if (stat > 0) { G__setenv("MAPSET", mapset); G__create_alt_search_path(); G__switch_env(); G__switch_search_path(); which_env = 0; /* get elevation layer raster map in target location */ select_target_env(); ask_elev(group, location, mapset); /* select current location */ select_current_env(); I_put_group_elev(group, elev_layer, mapset_elev, tl, math_exp, units, nd); exit(EXIT_SUCCESS); } sprintf(buf, _("Mapset [%s] in target location [%s] - "), mapset, location); strcat(buf, stat == 0 ? _("permission denied\n") : _("not found\n")); error: strcat(buf, _("Please select a target for group")); strcat(buf, group); G_suppress_warnings(0); G_fatal_error(buf); }