void bluetoothHandler(bool connected) 
{
  APP_LOG(DebugLevel, "bluetoothHandler: start connected :%s:",connected ? "true" : "false");
  bool prevConnected=false;
  if(persist_exists(BT_STATUS)){
    prevConnected = persist_read_bool(BT_STATUS);
	APP_LOG(DebugLevel, "bluetoothHandler: initial key");
  }
	APP_LOG(DebugLevel, "bluetoothHandler: prevConnected :%s:",prevConnected ? "true" : "false");

  if(connected && prevConnected) {
     bitmap_layer_set_bitmap(GET_LAYER(BLUETOOTH_LAYER), bluetoothImageOn);
	  APP_LOG(DebugLevel, "bluetoothHandler: both true turned on connection");
  }
  if(!connected && !prevConnected) {
     bitmap_layer_set_bitmap(GET_LAYER(BLUETOOTH_LAYER), bluetoothImageOff);
	  APP_LOG(DebugLevel, "bluetoothHandler: both false turned off connection");
  }

  if(connected && !prevConnected) {
     bitmap_layer_set_bitmap(GET_LAYER(BLUETOOTH_LAYER), bluetoothImageOn);
	  APP_LOG(DebugLevel, "bluetoothHandler: turned on connection");
     vibes_short_pulse();
  }

  if(!connected && prevConnected) {
  	  bitmap_layer_set_bitmap(GET_LAYER(BLUETOOTH_LAYER), bluetoothImageOff);
	  APP_LOG(DebugLevel, "bluetoothHandler: turned off connection");
     vibes_long_pulse();
     btBuzzerTimer = app_timer_register(BUZZER_INTERVAL, buzzer2,NULL);
  }
  persist_write_bool(BT_STATUS, connected);
  APP_LOG(DebugLevel, "bluetoothHandler: done saved :%s:",connected ? "true" : "false");
} // bluetoothHandler
Exemple #2
0
layerObj *msRemoveLayer(mapObj *map, int nIndex) 
{
    int i;
    int order_index;
    layerObj *layer;
    
    if (nIndex < 0 || nIndex >= map->numlayers) {
        msSetError(MS_CHILDERR, "Cannot remove Layer, invalid index %d",
                   "msRemoveLayer()", nIndex);
        return NULL;
    }
    else {
    	layer=GET_LAYER(map, nIndex);
        /* msCopyLayer(layer, (GET_LAYER(map, nIndex))); */
        
        /* Iteratively copy the higher index layers down one index */
        for (i=nIndex; i<map->numlayers-1; i++) {
            /* freeLayer((GET_LAYER(map, i))); */
            /* initLayer((GET_LAYER(map, i)), map); */
            /* msCopyLayer(GET_LAYER(map, i), GET_LAYER(map, i+1)); */
	    GET_LAYER(map, i)=GET_LAYER(map, i+1);
            GET_LAYER(map, i)->index = i;
        }
        /* Free the extra layer at the end */
        /* freeLayer((GET_LAYER(map, map->numlayers-1))); */
        GET_LAYER(map, map->numlayers-1)=NULL;
        
        /* Adjust drawing order */
        order_index = 0;
        for (i=0; i<map->numlayers; i++) {
            if (map->layerorder[i] > nIndex) map->layerorder[i]--;
            if (map->layerorder[i] == nIndex) {
                order_index = i;
                break;
            }
        }
        for (i=order_index; i<map->numlayers-1; i++) {
            map->layerorder[i] = map->layerorder[i+1];
            if (map->layerorder[i] > nIndex) map->layerorder[i]--;
        }
        
        /* decrement number of layers and return copy of removed layer */
        map->numlayers--;
	layer->map=NULL;
	MS_REFCNT_DECR(layer);
        return layer;
    }
}
Exemple #3
0
int KmlRenderer::checkProjection(mapObj *map)
{
    projectionObj *projection= &map->projection;
#ifdef USE_PROJ
    if (projection && projection->numargs > 0 && pj_is_latlong(projection->proj))
    {
        return MS_SUCCESS;
    }
    else
    {
        char epsg_string[100];
        rectObj sRect;
        projectionObj out;

        /* for layer the do not have any projection set, set them with the current map
           projection*/
        if (projection && projection->numargs > 0)
        {
            layerObj *lp = NULL;
            int i =0;
            char *pszMapProjectString = msGetProjectionString(projection);
            if (pszMapProjectString)
            {
                for(i=0; i<map->numlayers; i++)
                {
                    lp = GET_LAYER(map, i);
                    if (lp->projection.numargs == 0 && lp->transform == MS_TRUE)
                    {
                        msFreeProjection(&lp->projection);
                        msLoadProjectionString(&lp->projection, pszMapProjectString);
                    }
                }
                msFree(pszMapProjectString);
            }
        }
        strcpy(epsg_string, "epsg:4326" );
        msInitProjection(&out);
        msLoadProjectionString(&out, epsg_string);

        sRect = map->extent;
        msProjectRect(projection, &out, &sRect);
        msFreeProjection(projection);
        msLoadProjectionString(projection, epsg_string);

        /*change also units and extents*/
        map->extent = sRect;
        map->units = MS_DD;


        if (map->debug)
          msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");

        return MS_SUCCESS;
    }

#else
    msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
    return MS_FAILURE;
#endif
}
void updateDate() 
{
  time_t temp = time(NULL); 
  struct tm *tickTime = localtime(&temp);
  static char dateBuffer[] = "Wednesday 31 September 2015";

  strftime(dateBuffer, sizeof(dateBuffer), "%a %e %B %n %Y", tickTime);

  // Display this time on the TextLayer
  text_layer_set_text(GET_LAYER(DATE_LAYER), dateBuffer);
} // updateDate
Exemple #5
0
int msMapSetFakedExtent( mapObj *map )

{
  int i;
  /* -------------------------------------------------------------------- */
  /*      Remember the original map extents so we can restore them        */
  /*      later.                                                          */
  /* -------------------------------------------------------------------- */
  map->saved_extent = map->extent;

  /* -------------------------------------------------------------------- */
  /*      Set extents such that the bottom left corner is 0,0 and the     */
  /*      top right is width,height.  Note this is upside down from       */
  /*      the normal sense of pixel/line coordiantes, but we do this      */
  /*      so that the normal "extent" concept of coordinates              */
  /*      increasing to the right, and up is maintained (like in          */
  /*      georeferenced coordinate systems).                              */
  /* -------------------------------------------------------------------- */
  map->extent.minx = 0;
  map->extent.maxx = map->width;
  map->extent.miny = 0;
  map->extent.maxy = map->height;
  map->cellsize = 1.0;

  /* -------------------------------------------------------------------- */
  /*      When we copy the geotransform into the projection object we     */
  /*      have to flip it to account for the preceeding upside-down       */
  /*      coordinate system.                                              */
  /* -------------------------------------------------------------------- */
  map->projection.gt = map->gt;

  map->projection.gt.geotransform[0]
  += map->height * map->gt.geotransform[2];
  map->projection.gt.geotransform[3]
  += map->height * map->gt.geotransform[5];

  map->projection.gt.geotransform[2] *= -1;
  map->projection.gt.geotransform[5] *= -1;

  for(i=0; i<map->numlayers; i++)
    GET_LAYER(map, i)->project = MS_TRUE;

  return InvGeoTransform( map->projection.gt.geotransform,
                          map->projection.gt.invgeotransform );
}
void updateTime() 
{
  time_t temp = time(NULL); 
  struct tm *tickTime = localtime(&temp);
  static char timeBuffer[] = "00:00";

  if (HourFormat == 24) {
    strftime(timeBuffer, sizeof("00:00"), "%H:%M", tickTime);
  } else {
    strftime(timeBuffer, sizeof("00:00"), "%l:%M", tickTime);
  }

  // Write the current hours and minutes into the buffer

  // Display this time on the TextLayer
  //APP_LOG(DebugLevel, "updateTime: setting text");
  text_layer_set_text(GET_LAYER(TIME_LAYER), timeBuffer);
  //APP_LOG(DebugLevel, "updateTime: text set");
} // updateTime
void handleBattery(BatteryChargeState charge_state)
{
	static char battery_text[] = "100%";
	//APP_LOG(DebugLevel, "handleBattery start");
	if(persist_exists(KEY_SHOW_BATTERY)){
  		bool value = persist_read_bool(KEY_SHOW_BATTERY);
		if (!value) {
			return;
		}
	}

  if (charge_state.is_charging) {
    snprintf(battery_text, sizeof(battery_text), "chg");
  } else {
    snprintf(battery_text, sizeof(battery_text), "%d%%", charge_state.charge_percent);
  }
  text_layer_set_text(GET_LAYER(BATTERY_LAYER), battery_text);
  //APP_LOG(DebugLevel, "batteryCheck");
} //handleBattery
Exemple #8
0
int msEmbedScalebar(mapObj *map, imageObj *img)
{
    int l,index,s;
    pointObj point;
    imageObj *image = NULL;
    rendererVTableObj *renderer = MS_MAP_RENDERER(map);
    symbolObj *embededSymbol;

    if( ! renderer ) {
        msSetError(MS_MISCERR,"unsupported outputformat","msEmbedScalebar()");
        return MS_FAILURE;
    }
    index = msGetSymbolIndex(&(map->symbolset), "scalebar", MS_FALSE);
    if(index != -1)
        msRemoveSymbol(&(map->symbolset), index); /* remove cached symbol in case the function is called multiple
                      times with different zoom levels */

    if((embededSymbol=msGrowSymbolSet(&map->symbolset)) == NULL)
        return MS_FAILURE;
    s = map->symbolset.numsymbols;
    map->symbolset.numsymbols++;

    image = msDrawScalebar(map);
    if(!image) {
        return MS_FAILURE;
    }
    embededSymbol->pixmap_buffer = calloc(1,sizeof(rasterBufferObj));
    MS_CHECK_ALLOC(embededSymbol->pixmap_buffer, sizeof(rasterBufferObj), MS_FAILURE);

    if(MS_SUCCESS != renderer->getRasterBufferCopy(image,embededSymbol->pixmap_buffer)) {
        return MS_FAILURE;
    }

    embededSymbol->type = MS_SYMBOL_PIXMAP; /* intialize a few things */
    embededSymbol->name = msStrdup("scalebar");
    embededSymbol->sizex = embededSymbol->pixmap_buffer->width;
    embededSymbol->sizey = embededSymbol->pixmap_buffer->height;
    if(map->scalebar.transparent) {
        embededSymbol->transparent = MS_TRUE;
        embededSymbol->transparentcolor = 0;
    }

    switch(map->scalebar.position) {
    case(MS_LL):
        point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
        point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    case(MS_LR):
        point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
        point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    case(MS_LC):
        point.x = MS_NINT(map->width/2.0);
        point.y = map->height - MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    case(MS_UR):
        point.x = map->width - MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
        point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    case(MS_UL):
        point.x = MS_NINT(embededSymbol->pixmap_buffer->width/2.0);
        point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    case(MS_UC):
        point.x = MS_NINT(map->width/2.0);
        point.y = MS_NINT(embededSymbol->pixmap_buffer->height/2.0);
        break;
    }

    l = msGetLayerIndex(map, "__embed__scalebar");
    if(l == -1) {
        if (msGrowMapLayers(map) == NULL)
            return(-1);
        l = map->numlayers;
        map->numlayers++;
        if(initLayer((GET_LAYER(map, l)), map) == -1) return(-1);
        GET_LAYER(map, l)->name = msStrdup("__embed__scalebar");
        GET_LAYER(map, l)->type = MS_LAYER_POINT;

        if (msGrowLayerClasses( GET_LAYER(map, l) ) == NULL)
            return(-1);

        if(initClass(GET_LAYER(map, l)->class[0]) == -1) return(-1);
        GET_LAYER(map, l)->numclasses = 1; /* so we make sure to free it */

        /* update the layer order list with the layer's index. */
        map->layerorder[l] = l;
    }

    GET_LAYER(map, l)->status = MS_ON;
    if(map->scalebar.postlabelcache) { /* add it directly to the image */
        if(msMaybeAllocateClassStyle(GET_LAYER(map, l)->class[0], 0)==MS_FAILURE) return MS_FAILURE;
        GET_LAYER(map, l)->class[0]->styles[0]->symbol = s;
        msDrawMarkerSymbol(&map->symbolset, img, &point, GET_LAYER(map, l)->class[0]->styles[0], 1.0);
    } else {
        if(!GET_LAYER(map, l)->class[0]->labels) {
Exemple #9
0
int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params,
                           cgiRequestObj *req, owsRequestObj *ows_request)
{
  xmlDocPtr psDoc = NULL;       /* document pointer */
  xmlNodePtr psRootNode, psMainNode, psNode, psFtNode;
  const char *updatesequence=NULL;
  xmlNsPtr psNsOws, psNsXLink, psNsOgc;
  char *schemalocation = NULL;
  char *xsi_schemaLocation = NULL;
  const char *user_namespace_prefix = NULL;
  const char *user_namespace_uri = NULL;
  gmlNamespaceListObj *namespaceList=NULL; /* for external application schema support */

  char *script_url=NULL, *formats_list;
  const char *value = NULL;

  xmlChar *buffer = NULL;
  int size = 0, i;
  msIOContext *context = NULL;

  int ows_version = OWS_1_0_0;
  int ret;

  /* -------------------------------------------------------------------- */
  /*      Handle updatesequence                                           */
  /* -------------------------------------------------------------------- */
  ret = msWFSHandleUpdateSequence(map, params, "msWFSGetCapabilities11()");
  if( ret != MS_SUCCESS )
      return ret;

  /* -------------------------------------------------------------------- */
  /*      Create document.                                                */
  /* -------------------------------------------------------------------- */
  psDoc = xmlNewDoc(BAD_CAST "1.0");

  psRootNode = xmlNewNode(NULL, BAD_CAST "WFS_Capabilities");

  xmlDocSetRootElement(psDoc, psRootNode);

  /* -------------------------------------------------------------------- */
  /*      Name spaces                                                     */
  /* -------------------------------------------------------------------- */
  /*default name space*/
  xmlNewProp(psRootNode, BAD_CAST "xmlns", BAD_CAST "http://www.opengis.net/wfs");

  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wfs", BAD_CAST "wfs"));

  psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
  psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );

  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_uri");
  if(value) user_namespace_uri = value;

  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");
  if(value) user_namespace_prefix = value;
  if(user_namespace_prefix != NULL && msIsXMLTagValid(user_namespace_prefix) == MS_FALSE)
    msIO_printf("<!-- WARNING: The value '%s' is not valid XML namespace. -->\n", user_namespace_prefix);
  else
    xmlNewNs(psRootNode, BAD_CAST user_namespace_uri, BAD_CAST user_namespace_prefix);

  /* any additional namespaces */
  namespaceList = msGMLGetNamespaces(&(map->web), "G");
  for(i=0; i<namespaceList->numnamespaces; i++) {
    if(namespaceList->namespaces[i].uri) {
      xmlNewNs(psRootNode, BAD_CAST namespaceList->namespaces[i].uri, BAD_CAST namespaceList->namespaces[i].prefix);
    }
  }
  msGMLFreeNamespaces(namespaceList);
  

  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->pszVersion );

  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");

  if (updatesequence)
    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);

  /*schema*/
  schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
  xsi_schemaLocation = msStrdup("http://www.opengis.net/wfs");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wfs/1.1.0/wfs.xsd");
  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);

  /* -------------------------------------------------------------------- */
  /*      Service metadata.                                               */
  /* -------------------------------------------------------------------- */

  xmlAddChild(psRootNode,
                          msOWSCommonServiceIdentification(psNsOws, map, "OGC WFS", params->pszVersion, "FO", NULL));

  /*service provider*/
  xmlAddChild(psRootNode, msOWSCommonServiceProvider(
                            psNsOws, psNsXLink, map, "FO", NULL));

  /*operation metadata */
  if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL) {
    msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities11()");
    return msWFSException11(map, "mapserv", MS_OWS_ERROR_NO_APPLICABLE_CODE, params->pszVersion);
  }

  /* -------------------------------------------------------------------- */
  /*      Operations metadata.                                            */
  /* -------------------------------------------------------------------- */
  psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psNsOws));

  /* -------------------------------------------------------------------- */
  /*      GetCapabilities                                                 */
  /* -------------------------------------------------------------------- */
  psNode = xmlAddChild(psMainNode,
                       msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities",
                           OWS_METHOD_GETPOST, script_url));

  xmlAddChild(psMainNode, psNode);
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                ows_version, psNsOws, "Parameter", "service", "WFS"));
  /*accept version*/
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
              "Parameter", "AcceptVersions",
              "1.0.0,1.1.0"));
  /*format*/
  xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
              "Parameter", "AcceptFormats",
              "text/xml"));


  /* -------------------------------------------------------------------- */
  /*      DescribeFeatureType                                             */
  /* -------------------------------------------------------------------- */
  if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) {
    psNode = xmlAddChild(psMainNode,
                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeFeatureType",
                             OWS_METHOD_GETPOST, script_url));
    xmlAddChild(psMainNode, psNode);

    /*output format*/
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "outputFormat",
                "XMLSCHEMA,text/xml; subtype=gml/2.1.2,text/xml; subtype=gml/3.1.1"));
  }

  /* -------------------------------------------------------------------- */
  /*      GetFeature                                                      */
  /* -------------------------------------------------------------------- */
  if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) {

    psNode = xmlAddChild(psMainNode,
                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetFeature",
                             OWS_METHOD_GETPOST, script_url));
    xmlAddChild(psMainNode, psNode);

    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "resultType",
                "results,hits"));

    formats_list = msWFSGetOutputFormatList( map, NULL, OWS_1_1_0 );
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                "Parameter", "outputFormat",
                formats_list));
    msFree( formats_list );

    value = msOWSLookupMetadata(&(map->web.metadata), "FO", "maxfeatures");

    if (value) {
      xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                  "Constraint", "DefaultMaxFeatures",
                  (char *)value));
    }
  }

  /* -------------------------------------------------------------------- */
  /*      FeatureTypeList                                                 */
  /* -------------------------------------------------------------------- */

  psFtNode = xmlNewNode(NULL, BAD_CAST "FeatureTypeList");
  xmlAddChild(psRootNode, psFtNode);
  psNode = xmlNewChild(psFtNode, NULL, BAD_CAST "Operations", NULL);
  xmlNewChild(psNode, NULL, BAD_CAST "Operation", BAD_CAST "Query");

  for(i=0; i<map->numlayers; i++) {
    layerObj *lp;
    lp = GET_LAYER(map, i);

    if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
      continue;

    /* List only vector layers in which DUMP=TRUE */
    if (msWFSIsLayerSupported(lp))
      xmlAddChild(psFtNode, msWFSDumpLayer11(map, lp, psNsOws, OWS_1_1_0, NULL));
  }





  /* -------------------------------------------------------------------- */
  /*      Filter capabilities.                                            */
  /* -------------------------------------------------------------------- */

  psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
  xmlAddChild(psRootNode, FLTGetCapabilities(psNsOgc, psNsOgc, MS_FALSE));
  /* -------------------------------------------------------------------- */
  /*      Write out the document.                                         */
  /* -------------------------------------------------------------------- */

  if( msIO_needBinaryStdout() == MS_FAILURE )
    return MS_FAILURE;

  msIO_setHeader("Content-Type","text/xml; charset=UTF-8");
  msIO_sendHeaders();

  context = msIO_getHandler(stdout);

  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, ("UTF-8"), 1);
  msIO_contextWrite(context, buffer, size);
  xmlFree(buffer);

  /*free buffer and the document */
  /*xmlFree(buffer);*/
  xmlFreeDoc(psDoc);
  xmlFreeNs(psNsOgc);

  free(script_url);
  free(xsi_schemaLocation);
  free(schemalocation);

  xmlCleanupParser();

  return(MS_SUCCESS);
}
Exemple #10
0
static int
load_project(char *filename)
{
	char	buf[PATH_MAX];
	char	*tok[PCB_MAX_TOKENS];
	FILE	*f;
	char	*s;
	int	tokens = 0;
	int	state = 0, line = 1, layer = 0;

#define EXPECT(t, s)							\
	if (t != tokens) {						\
		g_error("%s line %d: Expected %d tokens, got %d\n",	\
		   filename, line, t, tokens);				\
		goto Error;						\
	}								\
	if (strcmp(tok[0], s)) {					\
		g_error("%s line %d: Expected %s, got %s\n",		\
		   filename, line, s, tok[0]);				\
		goto Error;						\
	}
#define PARSE_ERROR()							\
	do {								\
		g_error("%s line %d: Parse error\n", filename, line);	\
		goto Error;						\
	} while (0)
#define GET_LAYER(l, s)							\
	l = strtoull(s, NULL, 16);					\
	if (!l || (l & ~ALL_LAYERS()))					\
		PARSE_ERROR();
#define GET_COORD(c, x0, y0)						\
	(c).x = atof(x0);						\
	(c).y = atof(y0);						\
	if ((c).x < 0 || (c).x > pcb.width ||				\
	    (c).y < 0 || (c).y > pcb.height)				\
		PARSE_ERROR();

	pcb.filename = filename;
	if (!(f = fopen(pcb.filename, "r"))) {
		g_error("Can't open file: %s: %s\n", pcb.filename,
		    strerror(errno));
		return -1;
	}
	while (fgets(buf, sizeof(buf), f)) {
		if (state != 0 && state != 4)
			tokenize(buf, tok, &tokens);
		switch (state) {
		case 0:
			if (strcmp(buf, "depcb-project-0\n")) {
				g_error("Not a project file: %s\n%s%s",
				    pcb.filename, "depcb-project-0\n", buf);
				goto Error;
			}
			state++;
			break;
		case 1:
			EXPECT(2, "layers");
			pcb.layers = atoi(tok[1]);
			if (pcb.layers < 1 || pcb.layers > 64)
				PARSE_ERROR();
			pcb.layer = g_malloc0(pcb.layers * sizeof(*pcb.layer));
			pcb.action = g_malloc0(sizeof(PcbAction));
			state++;
			break;
		case 2:
			EXPECT(2, "curlayer");
			pcb.curlayer = atoi(tok[1]);
			if (pcb.curlayer < 0 || pcb.curlayer >= pcb.layers)
				PARSE_ERROR();
			state++;
			break;
		case 3:
			EXPECT(3, "size");
			pcb.width = atof(tok[1]);
			pcb.height = atof(tok[2]);
			state++;
			break;
		case 4:
			if (strncmp(buf, "imagefile ", 10)) {
				g_error("expected imagefile, got %s", buf);
				goto Error;
			}
			s = buf + strlen(buf) - 1;
			if (*s == '\n')
				*s = 0;
			pcb.layer[layer].filename = strdup(buf + 10);
			if (++layer == pcb.layers)
				state++;
			break;
		case 5:
			if (tokens == 5 && !strcmp(tok[0], "point")) {
				pcb.action->act = PCB_ADD | PCB_POINT;
				GET_LAYER(pcb.action->layers, tok[1]);
				GET_COORD(pcb.action->c, tok[2], tok[3]);
				pcb.action->flags = strtol(tok[4], NULL, 16);
				if (!play_action(PCB_DO))
					PARSE_ERROR();
				break;
			}
			if (tokens == 6 && !strcmp(tok[0], "line")) {
				pcb.action->act = PCB_ADD | PCB_LINE;
				GET_LAYER(pcb.action->layers, tok[1]);
				GET_COORD(pcb.action->c, tok[2], tok[3]);
				GET_COORD(pcb.action->l, tok[4], tok[5]);
				if (!play_action(PCB_DO))
					PARSE_ERROR();
				break;
			}
			bzero(pcb.action, sizeof(*pcb.action));
			state++;
			/* FALLTHRU */
		case 6:
			g_error("garbage at eof");
			break;
		}
		line++;
	}
	return 0;
Error:
	fclose(f);
	return -1;
}
int msAddLabel(mapObj *map, labelObj *label, int layerindex, int classindex, shapeObj *shape, pointObj *point, labelPathObj *labelpath, double featuresize)
{
  int i;
  labelCacheSlotObj *cacheslot;

  labelCacheMemberObj *cachePtr=NULL;
  layerObj *layerPtr=NULL;
  classObj *classPtr=NULL;

  if(!label) return(MS_FAILURE); // RFC 77 TODO: set a proper message
  if(label->status == MS_OFF) return(MS_SUCCESS); /* not an error */
  if(!label->annotext) {
    /* check if we have a labelpnt style */
    for(i=0; i<label->numstyles; i++) {
      if(label->styles[i]->_geomtransform.type == MS_GEOMTRANSFORM_LABELPOINT)
        break;
    }
    if(i==label->numstyles) {
      /* label has no text or marker symbols */
      return MS_SUCCESS;
    }
  }

  layerPtr = (GET_LAYER(map, layerindex)); /* set up a few pointers for clarity */
  classPtr = GET_LAYER(map, layerindex)->class[classindex];

  if(classPtr->leader.maxdistance) {
    if (layerPtr->type == MS_LAYER_ANNOTATION) {
      msSetError(MS_MISCERR, "LEADERs are not supported on annotation layers", "msAddLabel()");
      return MS_FAILURE;
    }
    if(labelpath) {
      msSetError(MS_MISCERR, "LEADERs are not supported on ANGLE FOLLOW labels", "msAddLabel()");
      return MS_FAILURE;
    }
  }
  /* check that the label intersects the layer mask */

  if (layerPtr->mask) {
    int maskLayerIdx = msGetLayerIndex(map, layerPtr->mask);
    layerObj *maskLayer = GET_LAYER(map, maskLayerIdx);
    unsigned char *alphapixptr;
    if (maskLayer->maskimage && MS_IMAGE_RENDERER(maskLayer->maskimage)->supports_pixel_buffer) {
      rasterBufferObj rb;
      memset(&rb, 0, sizeof (rasterBufferObj));
      MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage, &rb);
      if (point) {
        int x = MS_NINT(point->x);
        int y = MS_NINT(point->y);
        /* Using label repeatdistance, we might have a point with x/y below 0. See #4764 */
        if (x >= 0 && x < rb.width && y >= 0 && y < rb.height) {
#ifdef USE_GD
          if(rb.type == MS_BUFFER_BYTE_RGBA) {
            alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
            if(!*alphapixptr) {
              /* label point does not intersect mask */
              return MS_SUCCESS;
            }
          } else {
            if(!gdImageGetPixel(rb.data.gd_img,x,y)) {
              return MS_SUCCESS;
            }
          }
#else
          assert(rb.type == MS_BUFFER_BYTE_RGBA);
          alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
          if(!*alphapixptr) {
            /* label point does not intersect mask */
            return MS_SUCCESS;
          }
#endif
        }
      } else if (labelpath) {
        int i = 0;
        for (i = 0; i < labelpath->path.numpoints; i++) {
          int x = MS_NINT(labelpath->path.point[i].x);
          int y = MS_NINT(labelpath->path.point[i].y);
          /* Using label repeatdistance, we might have a point with x/y below 0. See #4764 */
          if (x >= 0 && x < rb.width && y >= 0 && y < rb.height) {
#ifdef USE_GD
            if (rb.type == MS_BUFFER_BYTE_RGBA) {
              alphapixptr = rb.data.rgba.a + rb.data.rgba.row_step * y + rb.data.rgba.pixel_step*x;
              if (!*alphapixptr) {
                /* label point does not intersect mask */
                msFreeLabelPathObj(labelpath);
                return MS_SUCCESS;
              }
            } else {
              if (!gdImageGetPixel(rb.data.gd_img, x, y)) {
                msFreeLabelPathObj(labelpath);
                return MS_SUCCESS;
              }
            }
#else
            assert(rb.type == MS_BUFFER_BYTE_RGBA);
            alphapixptr = rb.data.rgba.a + rb.data.rgba.row_step * y + rb.data.rgba.pixel_step*x;
            if (!*alphapixptr) {
              /* label point does not intersect mask */
              msFreeLabelPathObj(labelpath);
              return MS_SUCCESS;
            }
#endif
          }
        }
      }
    } else {
      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msAddLabel()", layerPtr->name);
      return (MS_FAILURE);
    }
  }



  /* Validate label priority value and get ref on label cache for it */
  if (label->priority < 1)
    label->priority = 1;
  else if (label->priority > MS_MAX_LABEL_PRIORITY)
    label->priority = MS_MAX_LABEL_PRIORITY;

  cacheslot = &(map->labelcache.slots[label->priority-1]);

  if(cacheslot->numlabels == cacheslot->cachesize) { /* just add it to the end */
    cacheslot->labels = (labelCacheMemberObj *) realloc(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
    MS_CHECK_ALLOC(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
    cacheslot->cachesize += MS_LABELCACHEINCREMENT;
  }

  cachePtr = &(cacheslot->labels[cacheslot->numlabels]);

  cachePtr->layerindex = layerindex; /* so we can get back to this *raw* data if necessary */
  cachePtr->classindex = classindex;
  if(shape) {
    cachePtr->shapetype = shape->type;
  } else {
    cachePtr->shapetype = MS_SHAPE_POINT;
  }
  cachePtr->leaderline = NULL;
  cachePtr->leaderbbox = NULL;

  /* Store the label point or the label path (Bug #1620) */
  if ( point ) {
    cachePtr->point = *point; /* the actual label point */
    cachePtr->labelpath = NULL;
  } else {
    assert(labelpath);
    cachePtr->labelpath = labelpath;
    /* Use the middle point of the labelpath for mindistance calculations */
    cachePtr->point = labelpath->path.point[labelpath->path.numpoints / 2];
  }

  /* TODO: perhaps we can get rid of this next section and just store a marker size? Why do we cache the styles for a point layer? */

  /* copy the styles (only if there is an accompanying marker)
   * We cannot simply keeep refs because the rendering code alters some members of the style objects
   */
  cachePtr->styles = NULL;
  cachePtr->numstyles = 0;
  if(layerPtr->type == MS_LAYER_ANNOTATION && classPtr->numstyles > 0) {
    cachePtr->numstyles = classPtr->numstyles;
    cachePtr->styles = (styleObj *) msSmallMalloc(sizeof(styleObj)*classPtr->numstyles);
    if (classPtr->numstyles > 0) {
      for(i=0; i<classPtr->numstyles; i++) {
        initStyle(&(cachePtr->styles[i]));
        msCopyStyle(&(cachePtr->styles[i]), classPtr->styles[i]);
      }
    }
  }

  /* copy the label */
  cachePtr->numlabels = 1;
  cachePtr->labels = (labelObj *) msSmallMalloc(sizeof(labelObj));
  initLabel(cachePtr->labels);
  msCopyLabel(cachePtr->labels, label);

  cachePtr->markerid = -1;

  cachePtr->featuresize = featuresize;

  //cachePtr->poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
  //msInitShape(cachePtr->poly);
  cachePtr->poly = NULL;

  cachePtr->status = MS_FALSE;

  if(layerPtr->type == MS_LAYER_POINT && classPtr->numstyles > 0) { /* cache the marker placement, it's already on the map */
    rectObj rect;
    double w, h;

    if(cacheslot->nummarkers == cacheslot->markercachesize) { /* just add it to the end */
      cacheslot->markers = (markerCacheMemberObj *) realloc(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
      MS_CHECK_ALLOC(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
      cacheslot->markercachesize+=MS_LABELCACHEINCREMENT;
    }

    i = cacheslot->nummarkers;

    cacheslot->markers[i].poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
    msInitShape(cacheslot->markers[i].poly);

    /* TO DO: at the moment only checks the bottom style, perhaps should check all of them */
    /* #2347: after RFC-24 classPtr->styles could be NULL so we check it */
    if(classPtr->styles != NULL) {
      if(msGetMarkerSize(&map->symbolset, classPtr->styles[0], &w, &h, layerPtr->scalefactor) != MS_SUCCESS)
        return(MS_FAILURE);
      rect.minx = point->x - .5 * w;
      rect.miny = point->y - .5 * h;
      rect.maxx = rect.minx + (w-1);
      rect.maxy = rect.miny + (h-1);
      msRectToPolygon(rect, cacheslot->markers[i].poly);
      cacheslot->markers[i].id = cacheslot->numlabels;

      cachePtr->markerid = i;

      cacheslot->nummarkers++;
    }
  }

  cacheslot->numlabels++;

  /* Maintain main labelCacheObj.numlabels only for backwards compatibility */
  map->labelcache.numlabels++;

  return(MS_SUCCESS);
}
int msAddLabelGroup(mapObj *map, int layerindex, int classindex, shapeObj *shape, pointObj *point, double featuresize)
{
  int i, priority, numactivelabels=0;
  labelCacheSlotObj *cacheslot;

  labelCacheMemberObj *cachePtr=NULL;
  layerObj *layerPtr=NULL;
  classObj *classPtr=NULL;

  layerPtr = (GET_LAYER(map, layerindex)); /* set up a few pointers for clarity */
  classPtr = GET_LAYER(map, layerindex)->class[classindex];

  if(classPtr->numlabels == 0) return MS_SUCCESS; /* not an error just nothing to do */
  for(i=0; i<classPtr->numlabels; i++) {
    if(classPtr->labels[i]->status == MS_ON) {
      numactivelabels++;
    }
  }
  if(numactivelabels == 0) return MS_SUCCESS;

  /* if the number of labels is 1 then call msAddLabel() accordingly */
  if(numactivelabels == 1) {
    for(i=0; i<classPtr->numlabels; i++) {
      if(classPtr->labels[i]->status == MS_ON)
        return msAddLabel(map, classPtr->labels[i], layerindex, classindex, shape, point, NULL, featuresize);
    }
  }

  if (layerPtr->type == MS_LAYER_ANNOTATION && (classPtr->numlabels > 1 || classPtr->leader.maxdistance)) {
    msSetError(MS_MISCERR, "Multiple Labels and/or LEADERs are not supported with annotation layers", "msAddLabelGroup()");
    return MS_FAILURE;
  }

  /* check that the label intersects the layer mask */
  if(layerPtr->mask) {
    int maskLayerIdx = msGetLayerIndex(map,layerPtr->mask);
    layerObj *maskLayer = GET_LAYER(map,maskLayerIdx);
    unsigned char *alphapixptr;
    if(maskLayer->maskimage && MS_IMAGE_RENDERER(maskLayer->maskimage)->supports_pixel_buffer) {
      rasterBufferObj rb;
      int x,y;
      memset(&rb,0,sizeof(rasterBufferObj));
      MS_IMAGE_RENDERER(maskLayer->maskimage)->getRasterBufferHandle(maskLayer->maskimage,&rb);
      x = MS_NINT(point->x);
      y = MS_NINT(point->y);
      /* Using label repeatdistance, we might have a point with x/y below 0. See #4764 */
      if (x >= 0 && x < rb.width && y >= 0 && y < rb.height) {
#ifdef USE_GD
        if(rb.type == MS_BUFFER_BYTE_RGBA) {
          alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
          if(!*alphapixptr) {
            /* label point does not intersect mask */
            return MS_SUCCESS;
          }
        } else {
          if(!gdImageGetPixel(rb.data.gd_img,x,y))
            return MS_SUCCESS;
        }
#else
        assert(rb.type == MS_BUFFER_BYTE_RGBA);
        alphapixptr = rb.data.rgba.a+rb.data.rgba.row_step*y + rb.data.rgba.pixel_step*x;
        if(!*alphapixptr) {
          /* label point does not intersect mask */
          return MS_SUCCESS;
        }
#endif
      }
    } else {
      msSetError(MS_MISCERR, "Layer (%s) references references a mask layer, but the selected renderer does not support them", "msAddLabelGroup()", layerPtr->name);
      return (MS_FAILURE);
    }
  }



  /* Validate label priority value and get ref on label cache for it */
  priority = classPtr->labels[0]->priority; /* take priority from the first label */
  if (priority < 1)
    priority = 1;
  else if (priority > MS_MAX_LABEL_PRIORITY)
    priority = MS_MAX_LABEL_PRIORITY;

  cacheslot = &(map->labelcache.slots[priority-1]);

  if(cacheslot->numlabels == cacheslot->cachesize) { /* just add it to the end */
    cacheslot->labels = (labelCacheMemberObj *) realloc(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
    MS_CHECK_ALLOC(cacheslot->labels, sizeof(labelCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
    cacheslot->cachesize += MS_LABELCACHEINCREMENT;
  }

  cachePtr = &(cacheslot->labels[cacheslot->numlabels]);

  cachePtr->layerindex = layerindex; /* so we can get back to this *raw* data if necessary */
  cachePtr->classindex = classindex;
  if(shape) {
    cachePtr->shapetype = shape->type;
  } else {
    cachePtr->shapetype = MS_SHAPE_POINT;
  }

  cachePtr->point = *point; /* the actual label point */
  cachePtr->labelpath = NULL;

  cachePtr->leaderline = NULL;
  cachePtr->leaderbbox = NULL;

  // cachePtr->text = msStrdup(string); /* the actual text */

  /* TODO: perhaps we can get rid of this next section and just store a marker size? Why do we cache the styles for a point layer? */

  /* copy the styles (only if there is an accompanying marker)
   * We cannot simply keep refs because the rendering code  might alters some members of the style objects
   */
  cachePtr->styles = NULL;
  cachePtr->numstyles = 0;
  if(layerPtr->type == MS_LAYER_ANNOTATION && classPtr->numstyles > 0) {
    cachePtr->numstyles = classPtr->numstyles;
    cachePtr->styles = (styleObj *) msSmallMalloc(sizeof(styleObj)*classPtr->numstyles);
    if (classPtr->numstyles > 0) {
      for(i=0; i<classPtr->numstyles; i++) {
        initStyle(&(cachePtr->styles[i]));
        msCopyStyle(&(cachePtr->styles[i]), classPtr->styles[i]);
      }
    }
  }

  /*
  ** copy the labels (we are guaranteed to have more than one):
  **   we cannot simply keep refs because the rendering code alters some members of the style objects
  */

  cachePtr->numlabels = 0;
  cachePtr->labels = (labelObj *) msSmallMalloc(sizeof(labelObj)*numactivelabels);
  for(i=0; i<classPtr->numlabels; i++) {
    if(classPtr->labels[i]->status == MS_OFF) continue;
    initLabel(&(cachePtr->labels[cachePtr->numlabels]));
    msCopyLabel(&(cachePtr->labels[cachePtr->numlabels]), classPtr->labels[i]);
    cachePtr->numlabels++;
  }
  assert(cachePtr->numlabels == numactivelabels);

  cachePtr->markerid = -1;

  cachePtr->featuresize = featuresize;

  //cachePtr->poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
  //msInitShape(cachePtr->poly);
  cachePtr->poly = NULL;

  cachePtr->status = MS_FALSE;

  if(layerPtr->type == MS_LAYER_POINT && classPtr->numstyles > 0) {
    /* cache the marker placement, it's already on the map */
    /* TO DO: at the moment only checks the bottom style, perhaps should check all of them */
    /* #2347: after RFC-24 classPtr->styles could be NULL so we check it */
    rectObj rect;
    double w, h;
    if(msGetMarkerSize(&map->symbolset, classPtr->styles[0], &w, &h, layerPtr->scalefactor) != MS_SUCCESS)
      return(MS_FAILURE);

    if(cacheslot->nummarkers == cacheslot->markercachesize) { /* just add it to the end */
      cacheslot->markers = (markerCacheMemberObj *) realloc(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT));
      MS_CHECK_ALLOC(cacheslot->markers, sizeof(markerCacheMemberObj)*(cacheslot->cachesize+MS_LABELCACHEINCREMENT), MS_FAILURE);
      cacheslot->markercachesize+=MS_LABELCACHEINCREMENT;
    }

    i = cacheslot->nummarkers;

    cacheslot->markers[i].poly = (shapeObj *) msSmallMalloc(sizeof(shapeObj));
    msInitShape(cacheslot->markers[i].poly);

    rect.minx = (point->x - .5 * w);
    rect.miny = (point->y - .5 * h);
    rect.maxx = rect.minx + (w-1);
    rect.maxy = rect.miny + (h-1);
    msRectToPolygon(rect, cacheslot->markers[i].poly);
    cacheslot->markers[i].id = cacheslot->numlabels;

    cachePtr->markerid = i;

    cacheslot->nummarkers++;
  }

  cacheslot->numlabels++;

  /* Maintain main labelCacheObj.numlabels only for backwards compatibility */
  map->labelcache.numlabels++;

  return(MS_SUCCESS);
}
Exemple #13
0
int updateMap(mapservObj *mapserv, mapObj *map) {
  int i, j;

  if(!msLookupHashTable(&(map->web.validation), "immutable")) {
    /* check for any %variable% substitutions here, also do any map_ changes, we do this here so WMS/WFS  */
    /* services can take advantage of these "vendor specific" extensions */
    for(i=0; i<mapserv->request->NumParams; i++) {
      /*
       ** a few CGI variables should be skipped altogether
       **
       ** qstring: there is separate per layer validation for attribute queries and the substitution checks
       **          below conflict with that so we avoid it here
       */
      if(strncasecmp(mapserv->request->ParamNames[i],"qstring",7) == 0) continue;

      /* check to see if there are any additions to the mapfile */
      if(strncasecmp(mapserv->request->ParamNames[i],"map_",4) == 0 || strncasecmp(mapserv->request->ParamNames[i],"map.",4) == 0) {
        msAcquireLock( TLOCK_PARSER );
        if(msUpdateMapFromURL(map, mapserv->request->ParamNames[i], mapserv->request->ParamValues[i]) != MS_SUCCESS) {
          msReleaseLock( TLOCK_PARSER );
          return MS_FAILURE;
        }
        msReleaseLock( TLOCK_PARSER );

        continue;
      }

      if(strncasecmp(mapserv->request->ParamNames[i],"classgroup",10) == 0) { /* #4207 */
        for(j=0; j<map->numlayers; j++) {
          setClassGroup(GET_LAYER(map, j), mapserv->request->ParamValues[i]);
        }
        continue;
      }
    }

    msApplySubstitutions(map, mapserv->request->ParamNames, mapserv->request->ParamValues, mapserv->request->NumParams);
    msApplyDefaultSubstitutions(map);

    /* check to see if a ogc map context is passed as argument. if there */
    /* is one load it */

    for(i=0; i<mapserv->request->NumParams; i++) {
      if(strcasecmp(mapserv->request->ParamNames[i],"context") == 0) {
        if(mapserv->request->ParamValues[i] && strlen(mapserv->request->ParamValues[i]) > 0) {
          if(strncasecmp(mapserv->request->ParamValues[i],"http",4) == 0) {
            if(msGetConfigOption(map, "CGI_CONTEXT_URL"))
              msLoadMapContextURL(map, mapserv->request->ParamValues[i], MS_FALSE);
          } else
            msLoadMapContext(map, mapserv->request->ParamValues[i], MS_FALSE);
        }
      }
    }
  }

  /*
   * RFC-42 HTTP Cookie Forwarding
   * Here we set the http_cookie_data metadata to handle the
   * HTTP Cookie Forwarding. The content of this metadata is the cookie
   * content. In the future, this metadata will probably be replaced
   * by an object that is part of the mapObject that would contain
   * information on the application status (such as cookie).
   */
  if( mapserv->request->httpcookiedata != NULL ) {
    msInsertHashTable( &(map->web.metadata), "http_cookie_data",
                       mapserv->request->httpcookiedata );
  }

  return MS_SUCCESS;
}
Exemple #14
0
int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
                             httpRequestObj *pasReqInfo, int *numRequests)
{
#ifdef USE_WFS_LYR
  char *pszURL = NULL;
  const char *pszTmp;
  rectObj bbox;
  int nTimeout;
  int nStatus = MS_SUCCESS;
  msWFSLayerInfo *psInfo = NULL;
  int bPostRequest = 0;
  wfsParamsObj *psParams = NULL;
  char *pszHTTPCookieData = NULL;


  if (lp->connectiontype != MS_WFS || lp->connection == NULL)
    return MS_FAILURE;

  /* ------------------------------------------------------------------
   * Build a params object that will be used by to build the request,
    this will also set layer projection and compute BBOX in that projection.
   * ------------------------------------------------------------------ */
  psParams = msBuildRequestParams(map, lp, &bbox);
  if (!psParams)
    return MS_FAILURE;

  /* -------------------------------------------------------------------- */
  /*      Depending on the metadata wfs_request_method, build a Get or    */
  /*      a Post URL.                                                     */
  /*    If it is a Get request the URL would contain all the parameters in*/
  /*      the string;                                                     */
  /*      If it is a Post request, the URL will only contain the          */
  /*      connection string comming from the layer.                       */
  /* -------------------------------------------------------------------- */
  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
                                    "FO", "request_method")) != NULL) {
    if (strncmp(pszTmp, "GET", 3) ==0) {
      pszURL = msBuildWFSLayerGetURL(map, lp, &bbox, psParams);
      if (!pszURL) {
        /* an error was already reported. */
        return MS_FAILURE;
      }
    }
  }
  /* else it is a post request and just get the connection string */
  if (!pszURL) {
    bPostRequest = 1;
    pszURL = msStrdup(lp->connection);
  }

  /* ------------------------------------------------------------------
   * check to see if a the metadata wfs_connectiontimeout is set. If it is
   * the case we will use it, else we use the default which is 30 seconds.
   * First check the metadata in the layer object and then in the map object.
   * ------------------------------------------------------------------ */
  nTimeout = 30;  /* Default is 30 seconds  */
  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
                                    "FO", "connectiontimeout")) != NULL) {
    nTimeout = atoi(pszTmp);
  }

  /*------------------------------------------------------------------
   * Check to see if there's a HTTP Cookie to forward
   * If Cookie differ between the two connection, it's NOT OK to merge
   * the connection
   * ------------------------------------------------------------------ */
  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
                                    "FO", "http_cookie")) != NULL) {
    if(strcasecmp(pszTmp, "forward") == 0) {
      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
      if(pszTmp != NULL) {
        pszHTTPCookieData = msStrdup(pszTmp);
      }
    } else {
      pszHTTPCookieData = msStrdup(pszTmp);
    }
  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
                       "FO", "http_cookie")) != NULL) {
    if(strcasecmp(pszTmp, "forward") == 0) {
      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
      if(pszTmp != NULL) {
        pszHTTPCookieData = msStrdup(pszTmp);
      }
    } else {
      pszHTTPCookieData = msStrdup(pszTmp);
    }
  }

  /* ------------------------------------------------------------------
   * If nLayerId == -1 then we need to figure it
   * ------------------------------------------------------------------ */
  if (nLayerId == -1) {
    int iLayer;
    for(iLayer=0; iLayer < map->numlayers; iLayer++) {
      if (GET_LAYER(map, iLayer) == lp) {
        nLayerId = iLayer;
        break;
      }
    }
  }

  /* ------------------------------------------------------------------
   * Add a request to the array (already preallocated)
   * ------------------------------------------------------------------ */
  pasReqInfo[(*numRequests)].nLayerId = nLayerId;
  pasReqInfo[(*numRequests)].pszGetUrl = pszURL;

  if (bPostRequest) {
    pasReqInfo[(*numRequests)].pszPostRequest =
      msBuildWFSLayerPostRequest(map, lp, &bbox, psParams);
    pasReqInfo[(*numRequests)].pszPostContentType =
      msStrdup("text/xml");
  }


  /* We'll store the remote server's response to a tmp file. */
  pasReqInfo[(*numRequests)].pszOutputFile = msTmpFile(map, map->mappath, NULL, "tmp.gml");

  /* TODO: Implement Caching of GML responses. There was an older caching
   * method, but it suffered from a race condition. See #3137.
   */

  pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
  pszHTTPCookieData = NULL;
  pasReqInfo[(*numRequests)].nStatus = 0;
  pasReqInfo[(*numRequests)].nTimeout = nTimeout;
  pasReqInfo[(*numRequests)].bbox = bbox;
  pasReqInfo[(*numRequests)].debug = lp->debug;

  if (msHTTPAuthProxySetup(&(map->web.metadata), &(lp->metadata),
                           pasReqInfo, *numRequests, map, "FO") != MS_SUCCESS) {
    if (psParams) {
      msWFSFreeParamsObj(psParams);
    }
    return MS_FAILURE;
  }
  
  /* ------------------------------------------------------------------
   * Pre-Open the layer now, (i.e. alloc and fill msWFSLayerInfo inside
   * layer obj).  Layer will be ready for use when the main mapserver
   * code calls msLayerOpen().
   * ------------------------------------------------------------------ */
  if (lp->wfslayerinfo != NULL) {
    psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
  } else {
    lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
  }

  if (psInfo->pszGMLFilename)
    free(psInfo->pszGMLFilename);
  psInfo->pszGMLFilename=msStrdup(pasReqInfo[(*numRequests)].pszOutputFile);

  psInfo->rect = pasReqInfo[(*numRequests)].bbox;

  if (psInfo->pszGetUrl)
    free(psInfo->pszGetUrl);
  psInfo->pszGetUrl = msStrdup(pasReqInfo[(*numRequests)].pszGetUrl);

  psInfo->nStatus = 0;

  (*numRequests)++;

  if (psParams) {
    msWFSFreeParamsObj(psParams);
  }
  return nStatus;

#else
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
             "msPrepareWFSLayerRequest");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */

}
Exemple #15
0
void msFreeMap(mapObj *map)
{
  int i;

  if(!map) return;

  /* printf("msFreeMap(): maybe freeing map at %p count=%d.\n",map, map->refcount); */
  if(MS_REFCNT_DECR_IS_NOT_ZERO(map)) {
    return;
  }
  if(map->debug >= MS_DEBUGLEVEL_VV)
    msDebug("msFreeMap(): freeing map at %p.\n",map);

  msCloseConnections(map);

  msFree(map->name);
  msFree(map->shapepath);
  msFree(map->mappath);

  msFreeProjection(&(map->projection));
  msFreeProjection(&(map->latlon));

  msFreeLabelCache(&(map->labelcache));

  msFree(map->imagetype);

  msFreeFontSet(&(map->fontset));

  msFreeSymbolSet(&map->symbolset); /* free symbols */
  msFree(map->symbolset.filename);

  freeWeb(&(map->web));

  freeScalebar(&(map->scalebar));
  freeReferenceMap(&(map->reference));
  freeLegend(&(map->legend));

  for(i=0; i<map->maxlayers; i++) {
    if(GET_LAYER(map, i) != NULL) {
      GET_LAYER(map, i)->map = NULL;
      if(freeLayer((GET_LAYER(map, i))) == MS_SUCCESS)
        free(GET_LAYER(map, i));
    }
  }
  msFree(map->layers);

  if(map->layerorder)
    free(map->layerorder);

  msFree(map->templatepattern);
  msFree(map->datapattern);
  msFreeHashItems(&(map->configoptions));
  if(map->outputformat && map->outputformat->refcount > 0 && --map->outputformat->refcount < 1)
    msFreeOutputFormat(map->outputformat);

  for(i=0; i<map->numoutputformats; i++ ) {
    if(map->outputformatlist[i]->refcount > 0 && --map->outputformatlist[i]->refcount < 1)
      msFreeOutputFormat(map->outputformatlist[i]);
  }
  if(map->outputformatlist != NULL)
    msFree(map->outputformatlist);

  msFreeQuery(&(map->query));

#ifdef USE_V8_MAPSCRIPT
  if (map->v8context)
    msV8FreeContext(map);
#endif

  msFree(map);
}
void BatteryStatusOn() 
{
	APP_LOG(DebugLevel, "BatteryStatusOn");
	layer_set_hidden(GET_LAYER(BATTERY_LAYER), false);
} // BatteryStatusOn 
Exemple #17
0
int msWFSGetCapabilities11(mapObj *map, wfsParamsObj *params, 
                           cgiRequestObj *req, owsRequestObj *ows_request) 
{
    xmlDocPtr psDoc = NULL;       /* document pointer */
    xmlNodePtr psRootNode, psMainNode, psNode, psFtNode;
    xmlNodePtr psTmpNode;
    const char *updatesequence=NULL;
    xmlNsPtr psNsOws, psNsXLink, psNsOgc;
    char *schemalocation = NULL;
    char *xsi_schemaLocation = NULL;

    char *script_url=NULL, *script_url_encoded=NULL, *formats_list;
    const char *value = NULL;
    const char *encoding;

    xmlChar *buffer = NULL;
    int size = 0, i;
    msIOContext *context = NULL;

    int ows_version = OWS_1_0_0;

/* -------------------------------------------------------------------- */
/*      Handle updatesequence                                           */
/* -------------------------------------------------------------------- */

    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");

    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");

    if (params->pszUpdateSequence != NULL) {
      i = msOWSNegotiateUpdateSequence(params->pszUpdateSequence, updatesequence);
      if (i == 0) { /* current */
          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
          return msWFSException11(map, "updatesequence", "CurrentUpdateSequence", params->pszVersion);
      }
      if (i > 0) { /* invalid */
          msSetError(MS_WFSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWFSGetCapabilities11()", params->pszUpdateSequence, updatesequence);
          return msWFSException11(map, "updatesequence", "InvalidUpdateSequence", params->pszVersion);
      }
    }

/* -------------------------------------------------------------------- */
/*      Create document.                                                */
/* -------------------------------------------------------------------- */
    psDoc = xmlNewDoc(BAD_CAST "1.0");

    psRootNode = xmlNewNode(NULL, BAD_CAST "WFS_Capabilities");

    xmlDocSetRootElement(psDoc, psRootNode);

/* -------------------------------------------------------------------- */
/*      Name spaces                                                     */
/* -------------------------------------------------------------------- */
    /*default name space*/      
    xmlNewProp(psRootNode, BAD_CAST "xmlns", BAD_CAST "http://www.opengis.net/wfs");
    
    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/gml", BAD_CAST "gml"));
    xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wfs", BAD_CAST "wfs"));
    
    psNsOws = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
    psNsXLink = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
    xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );

    xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->pszVersion );

    updatesequence = msOWSLookupMetadata(&(map->web.metadata), "FO", "updatesequence");

    if (updatesequence)
      xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);

    /*schema*/
    schemalocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
    xsi_schemaLocation = msStrdup("http://www.opengis.net/wfs");
    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemalocation);
    xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wfs/1.1.0/wfs.xsd");
    xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);

/* -------------------------------------------------------------------- */
/*      Service metadata.                                               */
/* -------------------------------------------------------------------- */

    psTmpNode = xmlAddChild(psRootNode, 
                            msOWSCommonServiceIdentification(psNsOws, map, "OGC WFS", params->pszVersion, "FO"));

    /*service provider*/
    psTmpNode = xmlAddChild(psRootNode, msOWSCommonServiceProvider(
                                psNsOws, psNsXLink, map, "FO"));

    /*operation metadata */
    if ((script_url=msOWSGetOnlineResource(map, "FO", "onlineresource", req)) == NULL 
        || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL)
    {
        msSetError(MS_WFSERR, "Server URL not found", "msWFSGetCapabilities11()");
        return msWFSException11(map, "mapserv", "NoApplicableCode", params->pszVersion);
    }

/* -------------------------------------------------------------------- */
/*      Operations metadata.                                            */
/* -------------------------------------------------------------------- */
    psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psNsOws));

/* -------------------------------------------------------------------- */
/*      GetCapabilities                                                 */
/* -------------------------------------------------------------------- */
    psNode = xmlAddChild(psMainNode, 
                         msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetCapabilities", 
                                                                OWS_METHOD_GETPOST, script_url_encoded));
    
    xmlAddChild(psMainNode, psNode);
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psNsOws, "Parameter", "service", "WFS"));
    /*accept version*/
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
                                                                "Parameter", "AcceptVersions", 
                                                                "1.0.0,1.1.0"));
    /*format*/
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
                                                                "Parameter", "AcceptFormats", 
                                                                "text/xml"));


/* -------------------------------------------------------------------- */
/*      DescribeFeatureType                                             */
/* -------------------------------------------------------------------- */
    if (msOWSRequestIsEnabled(map, NULL, "F", "DescribeFeatureType", MS_TRUE)) 
    {
        psNode = xmlAddChild(psMainNode, 
                             msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"DescribeFeatureType", 
                                                                 OWS_METHOD_GETPOST, script_url_encoded));
        xmlAddChild(psMainNode, psNode);
        
        /*output format*/
        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
                                                                    "Parameter", "outputFormat", 
                                                                    "XMLSCHEMA,text/xml; subtype=gml/2.1.2,text/xml; subtype=gml/3.1.1"));
    }

/* -------------------------------------------------------------------- */
/*      GetFeature                                                      */
/* -------------------------------------------------------------------- */
    if (msOWSRequestIsEnabled(map, NULL, "F", "GetFeature", MS_TRUE)) 
    {

        psNode = xmlAddChild(psMainNode, 
                             msOWSCommonOperationsMetadataOperation(psNsOws,psNsXLink,"GetFeature", 
                                                                 OWS_METHOD_GETPOST, script_url_encoded));
        xmlAddChild(psMainNode, psNode);
        
        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                                                                    "Parameter", "resultType", 
                                                                    "results,hits"));

        formats_list = msWFSGetOutputFormatList( map, NULL, "1.1.0" );
        xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws, 
                                                                    "Parameter", "outputFormat", 
                                                                    formats_list));
        msFree( formats_list );

        value = msOWSLookupMetadata(&(map->web.metadata), "FO", "maxfeatures");

        if (value) {
            xmlAddChild(psMainNode, msOWSCommonOperationsMetadataDomainType(ows_version, psNsOws,
                                                                            "Constraint", "DefaultMaxFeatures",
                                                                            (char *)value));
        }
    }

/* -------------------------------------------------------------------- */
/*      FeatureTypeList                                                 */
/* -------------------------------------------------------------------- */
     
     psFtNode = xmlNewNode(NULL, BAD_CAST "FeatureTypeList");
     xmlAddChild(psRootNode, psFtNode);
     psNode = xmlNewChild(psFtNode, NULL, BAD_CAST "Operations", NULL);
     xmlNewChild(psNode, NULL, BAD_CAST "Operation", BAD_CAST "Query");
     
     for(i=0; i<map->numlayers; i++)
     {
         layerObj *lp;
         lp = GET_LAYER(map, i);
         
         if (!msIntegerInArray(lp->index, ows_request->enabled_layers, ows_request->numlayers))
             continue;

         /* List only vector layers in which DUMP=TRUE */
         if (msWFSIsLayerSupported(lp))
           xmlAddChild(psFtNode, msWFSDumpLayer11(map, lp, psNsOws));
     }
     
     
     
     
     
/* -------------------------------------------------------------------- */
/*      Filter capabilities.                                            */
/* -------------------------------------------------------------------- */

     psNsOgc = xmlNewNs(NULL, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX);
     xmlAddChild(psRootNode, FLTGetCapabilities(psNsOgc, psNsOgc, MS_FALSE));
/* -------------------------------------------------------------------- */
/*      Write out the document.                                         */
/* -------------------------------------------------------------------- */

    if( msIO_needBinaryStdout() == MS_FAILURE )
        return MS_FAILURE;
     
    if (encoding)
        msIO_printf("Content-type: text/xml; charset=%s%c%c", encoding,10,10);
    else
        msIO_printf("Content-type: text/xml%c%c",10,10);
    
    context = msIO_getHandler(stdout);

    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
    msIO_contextWrite(context, buffer, size);
    xmlFree(buffer);

    /*free buffer and the document */
    /*xmlFree(buffer);*/
    xmlFreeDoc(psDoc);
    xmlFreeNs(psNsOgc);

    free(script_url);	
     free(script_url_encoded);
    free(xsi_schemaLocation);
    free(schemalocation);

    xmlCleanupParser();

    return(MS_SUCCESS);
}
void BatteryStatusOff() 
{
	APP_LOG(DebugLevel, "BatteryStatusOff");
	layer_set_hidden(GET_LAYER(BATTERY_LAYER), true);
} // BatteryStatusOff 
Exemple #19
0
int main(int argc, char *argv[])
{
  int i,j,k;

  mapObj    	   *map=NULL;
  imageObj         *image = NULL;
     
  char **layers=NULL;
  int num_layers=0;

  int layer_found=0;

  char *outfile=NULL; /* no -o sends image to STDOUT */

  int iterations = 1;
  int draws = 0;

  for(i=1;i<argc;i++) { 
    if (strcmp(argv[i],"-c") == 0) { /* user specified number of draws */
      iterations = atoi(argv[i+1]);
      printf("We will draw %d times...\n", iterations);
      continue;
    }

    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
    {
        int debug_level = atoi(argv[++i]);

        msSetGlobalDebugLevel(debug_level);

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);

        continue;
    }
    
  }
  
  for(draws=0; draws<iterations; draws++) {

  struct mstimeval requeststarttime, requestendtime;

  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) 
      msGettimeofday(&requeststarttime, NULL);
      
  if(argc > 1 && strcmp(argv[1], "-v") == 0) {
    printf("%s\n", msGetVersion());
    exit(0);
  }

  /* ---- check the number of arguments, return syntax if not correct ---- */
  if( argc < 3 ) {
    fprintf(stdout, "\nPurpose: convert a mapfile to an image\n\n");
    fprintf(stdout,
            "Syntax: shp2img -m mapfile [-o image] [-e minx miny maxx maxy] [-s sizex sizey]\n"
            "               [-l \"layer1 [layers2...]\"] [-i format]\n"
            "               [-all_debug n] [-map_debug n] [-layer_debug n] [-p n] [-c n] [-d layername datavalue]\n");


    fprintf(stdout,"  -m mapfile: Map file to operate on - required\n" );
    fprintf(stdout,"  -i format: Override the IMAGETYPE value to pick output format\n" );
    fprintf(stdout,"  -o image: output filename (stdout if not provided)\n");
    fprintf(stdout,"  -e minx miny maxx maxy: extents to render\n");
    fprintf(stdout,"  -s sizex sizey: output image size\n");
    fprintf(stdout,"  -l layers: layers / groups to enable - make sure they are quoted and space seperated if more than one listed\n" );
    fprintf(stdout,"  -all_debug n: Set debug level for map and all layers\n" );
    fprintf(stdout,"  -map_debug n: Set map debug level\n" );
    fprintf(stdout,"  -layer_debug layer_name n: Set layer debug level\n" );
    fprintf(stdout,"  -c n: draw map n number of times\n" );
    fprintf(stdout,"  -p n: pause for n seconds after reading the map\n" );
    fprintf(stdout,"  -d layername datavalue: change DATA value for layer\n" );


    exit(0);
  }

  if ( msSetup() != MS_SUCCESS )
  {
      msWriteError(stderr);
      exit(1);
  }
 
  /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
  if ( msDebugInitFromEnv() != MS_SUCCESS )
  {
      msWriteError(stderr);
      msCleanup(0);
      exit(1);
  }

  for(i=1;i<argc;i++) { /* Step though the user arguments, 1st to find map file */
 
    if(strcmp(argv[i],"-m") == 0) {
      map = msLoadMap(argv[i+1], NULL);
      if(!map) {
	msWriteError(stderr);
        msCleanup(0);
	exit(1);
      }
      msApplyDefaultSubstitutions(map);
    }
  }

  if(!map) {
    fprintf(stderr, "Mapfile (-m) option not specified.\n");
    msCleanup(0);
    exit(1);
  }


  for(i=1;i<argc;i++) { /* Step though the user arguments */

    if(strcmp(argv[i],"-m") == 0) { /* skip it */
      i+=1;
    }

    if(strcmp(argv[i],"-p") == 0) {
        int pause_length = atoi(argv[i+1]);
        time_t start_time = time(NULL);

        printf( "Start pause of %d seconds.\n", pause_length );
        while( time(NULL) < start_time + pause_length ) {}
        printf( "Done pause.\n" );
            
        i+=1;
    }

    if(strcmp(argv[i],"-o") == 0) { /* load the output image filename */
      outfile = argv[i+1];
      i+=1;
    }
    
    if(strcmp(argv[i],"-i") == 0) { 
      outputFormatObj *format;

      format = msSelectOutputFormat( map, argv[i+1] );

      if( format == NULL )
          printf( "No such OUTPUTFORMAT as %s.\n", argv[i+1] );
      else
      {
          msFree( (char *) map->imagetype );
          map->imagetype = msStrdup( argv[i+1] );
          msApplyOutputFormat( &(map->outputformat), format, 
                               map->transparent, map->interlace, 
                               map->imagequality );
      }
      i+=1;
    }

    if(strcmp(argv[i],"-d") == 0) { /* swap layer data */
      for(j=0; j<map->numlayers; j++) {
	 if(strcmp(GET_LAYER(map, j)->name, argv[i+1]) == 0) {
	   free(GET_LAYER(map, j)->data);
	   GET_LAYER(map, j)->data = msStrdup(argv[i+2]);
	   break;
	 }
      }
      i+=2;
    }

    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
    {
        int debug_level = atoi(argv[++i]);

        /* msSetGlobalDebugLevel() already called. Just need to force debug
         * level in map and all layers
         */
        map->debug = debug_level;
        for(j=0; j<map->numlayers; j++) {
            GET_LAYER(map, j)->debug = debug_level;
        }

    }
    
    if(strcmp(argv[i], "-map_debug") == 0 && i < argc-1 ) /* debug */
    {
        map->debug = atoi(argv[++i]);

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);
    }
    
    if(strcmp(argv[i], "-layer_debug") == 0 && i < argc-1 ) /* debug */
    {
        const char *layer_name = argv[++i];
        int debug_level = atoi(argv[++i]);
        int got_layer = 0;

        for(j=0; j<map->numlayers; j++) {
            if(strcmp(GET_LAYER(map, j)->name,layer_name) == 0 ) {
                GET_LAYER(map, j)->debug = debug_level;
                got_layer = 1;
            }
        }
        if( !got_layer )
            fprintf( stderr, 
                     " Did not find layer '%s' from -layer_debug switch.\n", 
                     layer_name );

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);
    }
    
    if(strcmp(argv[i],"-e") == 0) { /* change extent */
        if( argc <= i+4 ) {
            fprintf( stderr, 
                     "Argument -e needs 4 space separated numbers as argument.\n" ); 
            msCleanup(0);
            exit(1);
        }
      map->extent.minx = atof(argv[i+1]);
      map->extent.miny = atof(argv[i+2]);
      map->extent.maxx = atof(argv[i+3]);
      map->extent.maxy = atof(argv[i+4]);
      i+=4;
    }

    if (strcmp(argv[i], "-s") == 0) {
      msMapSetSize(map, atoi(argv[i+1]), atoi(argv[i+2]));
      i+=2;
    }    

    if(strcmp(argv[i],"-l") == 0) { /* load layer list */
      layers = msStringSplit(argv[i+1], ' ', &(num_layers));

      for(j=0; j<num_layers; j++) { /* loop over -l */
          layer_found=0;
          for(k=0; k<map->numlayers; k++) {
              if((GET_LAYER(map, k)->name && strcasecmp(GET_LAYER(map, k)->name, layers[j]) == 0) || (GET_LAYER(map, k)->group && strcasecmp(GET_LAYER(map, k)->group, layers[j]) == 0)) {
                  layer_found = 1;
                  break;
              }
          }
          if (layer_found==0) {
              fprintf(stderr, "Layer (-l) \"%s\" not found\n", layers[j]);
              msCleanup(0);
              exit(1);
          }
      }

      for(j=0; j<map->numlayers; j++) {
          if(GET_LAYER(map, j)->status == MS_DEFAULT)
              continue;
          else {
              GET_LAYER(map, j)->status = MS_OFF;
              for(k=0; k<num_layers; k++) {
                  if((GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
                     (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0)) {
                      GET_LAYER(map, j)->status = MS_ON;
                      break;
                  }
              }
          }
      }

      msFreeCharArray(layers, num_layers);

      i+=1;
     }
  }
  
  image = msDrawMap(map, MS_FALSE);

  if(!image) {
    msWriteError(stderr);

    msFreeMap(map);
    msCleanup(0);
    exit(1);
  }

  if( msSaveImage(map, image, outfile) != MS_SUCCESS ) {
    msWriteError(stderr);
  }

  msFreeImage(image);
  msFreeMap(map);

  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
    msGettimeofday(&requestendtime, NULL);
    msDebug("shp2img total time: %.3fs\n", 
            (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
            (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
  }

  msCleanup(0);

} /*   for(draws=0; draws<iterations; draws++) { */
  return(0);
} /* ---- END Main Routine ---- */
Exemple #20
0
int msUVRASTERLayerGetExtent(layerObj *layer, rectObj *extent)

{
  char szPath[MS_MAXPATHLEN];
  mapObj *map = layer->map;
  double adfGeoTransform[6];
  int nXSize, nYSize;
  GDALDatasetH hDS;
  shapefileObj *tileshpfile;
  int tilelayerindex = -1;
  CPLErr eErr = CE_Failure;
  char *decrypted_path;

  if( (!layer->data || strlen(layer->data) == 0)
      && layer->tileindex == NULL) {
    /* should we be issuing a specific error about not supporting
       extents for tileindexed raster layers? */
    return MS_FAILURE;
  }

  if( map == NULL )
    return MS_FAILURE;

  /* If the layer use a tileindex, return the extent of the tileindex shapefile/referenced layer */
  if (layer->tileindex) {
    tilelayerindex = msGetLayerIndex(map, layer->tileindex);
    if(tilelayerindex != -1) /* does the tileindex reference another layer */
      return msLayerGetExtent(GET_LAYER(map, tilelayerindex), extent);
    else {
      tileshpfile = (shapefileObj *) malloc(sizeof(shapefileObj));
      MS_CHECK_ALLOC(tileshpfile, sizeof(shapefileObj), MS_FAILURE);

      if(msShapefileOpen(tileshpfile, "rb", msBuildPath3(szPath, map->mappath, map->shapepath, layer->tileindex), MS_TRUE) == -1)
        if(msShapefileOpen(tileshpfile, "rb", msBuildPath(szPath, map->mappath, layer->tileindex), MS_TRUE) == -1)
          return MS_FAILURE;

      *extent = tileshpfile->bounds;
      msShapefileClose(tileshpfile);
      free(tileshpfile);
      return MS_SUCCESS;
    }
  }

  msTryBuildPath3(szPath, map->mappath, map->shapepath, layer->data);
  decrypted_path = msDecryptStringTokens( map, szPath );

  msAcquireLock( TLOCK_GDAL );
  if( decrypted_path ) {
    hDS = GDALOpen(decrypted_path, GA_ReadOnly );
    msFree( decrypted_path );
  } else
    hDS = NULL;

  if( hDS != NULL ) {
    nXSize = GDALGetRasterXSize( hDS );
    nYSize = GDALGetRasterYSize( hDS );
    eErr = GDALGetGeoTransform( hDS, adfGeoTransform );

    GDALClose( hDS );
  }

  msReleaseLock( TLOCK_GDAL );

  if( hDS == NULL || eErr != CE_None ) {
    return MS_FAILURE;
  }

  /* If this appears to be an ungeoreferenced raster than flip it for
     mapservers purposes. */
  if( adfGeoTransform[5] == 1.0 && adfGeoTransform[3] == 0.0 ) {
    adfGeoTransform[5] = -1.0;
    adfGeoTransform[3] = nYSize;
  }

  extent->minx = adfGeoTransform[0];
  extent->maxy = adfGeoTransform[3];

  extent->maxx = adfGeoTransform[0] + nXSize * adfGeoTransform[1];
  extent->miny = adfGeoTransform[3] + nYSize * adfGeoTransform[5];

  return MS_SUCCESS;
}
Exemple #21
0
int msInsertLayer(mapObj *map, layerObj *layer, int nIndex)
{
  if (!layer) {
    msSetError(MS_CHILDERR, "Can't insert a NULL Layer", "msInsertLayer()");
    return -1;
  }

  /* Ensure there is room for a new layer */
  if (map->numlayers == map->maxlayers) {
    if (msGrowMapLayers(map) == NULL)
      return -1;
  }

  /* msGrowMapLayers allocates the new layer which we don't need to do since we have 1 that we are inserting
                  not sure if it is possible for this to be non null otherwise, but better to check since this function
                  replaces the value */
  if (map->layers[map->numlayers]!=NULL)
    free(map->layers[map->numlayers]);

  /* Catch attempt to insert past end of layers array */
  if (nIndex >= map->numlayers) {
    msSetError(MS_CHILDERR, "Cannot insert layer beyond index %d",
               "msInsertLayer()", map->numlayers-1);
    return -1;
  } else if (nIndex < 0) { /* Insert at the end by default */
    map->layerorder[map->numlayers] = map->numlayers;
    GET_LAYER(map, map->numlayers) = layer;
    GET_LAYER(map, map->numlayers)->index = map->numlayers;
    GET_LAYER(map, map->numlayers)->map = map;
    MS_REFCNT_INCR(layer);
    map->numlayers++;
    return map->numlayers-1;
  } else if (nIndex >= 0 && nIndex < map->numlayers) {
    /* Move existing layers at the specified nIndex or greater */
    /* to an index one higher */
    int i;
    for (i=map->numlayers; i>nIndex; i--) {
      GET_LAYER(map, i)=GET_LAYER(map, i-1);
      GET_LAYER(map, i)->index = i;
    }

    /* assign new layer to specified index */
    GET_LAYER(map, nIndex)=layer;
    GET_LAYER(map, nIndex)->index = nIndex;
    GET_LAYER(map, nIndex)->map = map;

    /* adjust layers drawing order */
    for (i=map->numlayers; i>nIndex; i--) {
      map->layerorder[i] = map->layerorder[i-1];
      if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
    }
    for (i=0; i<nIndex; i++) {
      if (map->layerorder[i] >= nIndex) map->layerorder[i]++;
    }
    map->layerorder[nIndex] = nIndex;

    /* increment number of layers and return */
    MS_REFCNT_INCR(layer);
    map->numlayers++;
    return nIndex;
  } else {
    msSetError(MS_CHILDERR, "Invalid index", "msInsertLayer()");
    return -1;
  }
}