예제 #1
0
파일: network.cpp 프로젝트: statek/gis2014l
void Network::show(std::string filename, const char* filetype) {
    GVC_t *gvc;
    Agraph_t *g;
    std::stringstream sStream;
    std::vector<Agnode_t *> vNodes;
    std::vector<Agedge_t *> vEdges;
    int i = 0;

    if (v < 1) return;
    
    gvc = gvContext();
    g = agopen("g", Agundirected, 0);

    while (i < v) {
        sStream.str("");
        sStream << i++;
        vNodes.push_back(agnode(g, sStream.str().c_str(), 1));
        agsafeset(vNodes[vNodes.size()-1], "height", "0.4", "");
        agsafeset(vNodes[vNodes.size()-1], "width", "0.4", "");
        agsafeset(vNodes[vNodes.size()-1], "fixedsize", "true", "");
    }

    for (std::set<Edge>::iterator x = e.begin(); x != e.end(); ++x) {
        sStream.str("");
        sStream << ((*x).wage * scale);
        vEdges.push_back(agedge(g, vNodes[(*x).v1], vNodes[(*x).v2], sStream.str().c_str(), 1));
        agsafeset(vEdges[vEdges.size()-1], "len", sStream.str().c_str(), "");
    }

    gvLayout(gvc, g, "fdp");
    gvRenderFilename(gvc, g, filetype, filename.c_str());

    gvFreeLayout(gvc, g);
    agclose(g);
    gvFreeContext(gvc);

    return;

};
예제 #2
0
void CFrmSettings::doPreview(QString fileName)
{
    if (getActiveWindow()->previewFrm) {
	getActiveWindow()->parentFrm->mdiArea->
	    removeSubWindow(getActiveWindow()->previewFrm->subWindowRef);
	delete getActiveWindow()->previewFrm;
	getActiveWindow()->previewFrm = NULL;
    }

    if ((fileName.isNull()) || !(getActiveWindow()->loadPreview(fileName))) {	//create preview
	QString prevFile(buildTempFile());
	gvRenderFilename(gvc, graph, "png",
			 (char *) prevFile.toUtf8().constData());
	getActiveWindow()->loadPreview(prevFile);
#if 0
	if (!this->getActiveWindow()->loadPreview(prevFile))
	    QMessageBox::information(this, tr("GVEdit"),
				     tr
				     ("Preview file can not be opened."));
#endif
    }
}
예제 #3
0
void graph2png(const agent *a, const agent *n, const contr c, const contr r, const contr d, const char* filename) {

	const agent *p = n + N + 1;
	agent m = n[N];
	GVC_t *gvc = gvContext();
	Agraph_t* g = agopen("test", Agstrictundirected, 0);
	agsafeset(g, "overlap", "false", "");
	Agnode_t* nodes[N];

	do { nodes[*p] = agnode(g, names[*p], 1); p++; }
	while (--m);

	for (agent i = 1; i < E + 1; i++) if (!ISSET(c, i) && !ISSET(d, i)) {
		Agedge_t *e = agedge(g, nodes[X(a, i)], nodes[Y(a, i)], "", 1);
		if (ISSET(r, i)) agsafeset(e, "color", "red", "");
	}

	gvLayout(gvc, g, "neato");
	gvRenderFilename(gvc, g, "png", filename);
	gvFreeLayout(gvc, g);
	agclose(g);
	gvFreeContext(gvc);
}
예제 #4
0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d D O T I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadDOTImage() reads a Graphviz image file and returns it.  It allocates
%  the memory necessary for the new Image structure and returns a pointer to
%  the new image.
%
%  The format of the ReadDOTImage method is:
%
%      Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    command[MagickPathExtent];

  const char
    *option;

  graph_t
    *graph;

  Image
    *image;

  ImageInfo
    *read_info;

  MagickBooleanType
    status;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  assert(graphic_context != (GVC_t *) NULL);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    return(DestroyImageList(image));
  read_info=CloneImageInfo(image_info);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  (void) CopyMagickString(read_info->magick,"SVG",MagickPathExtent);
  (void) AcquireUniqueFilename(read_info->filename);
  (void) FormatLocaleString(command,MagickPathExtent,"-Tsvg -o%s %s",
    read_info->filename,image_info->filename);
#if !defined(WITH_CGRAPH)
  graph=agread(GetBlobFileHandle(image));
#else
  graph=agread(GetBlobFileHandle(image),(Agdisc_t *) NULL);
#endif
  if (graph == (graph_t *) NULL)
    {
      (void) RelinquishUniqueFileResource(read_info->filename);
      return(DestroyImageList(image));
    }
  option=GetImageOption(image_info,"dot:layout-engine");
  if (option == (const char *) NULL)
    gvLayout(graphic_context,graph,(char *) "dot");
  else
    gvLayout(graphic_context,graph,(char *) option);
  gvRenderFilename(graphic_context,graph,(char *) "svg",read_info->filename);
  gvFreeLayout(graphic_context,graph);
  agclose(graph);
  image=DestroyImageList(image);
  /*
    Read SVG graph.
  */
  (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent);
  image=ReadImage(read_info,exception);
  (void) RelinquishUniqueFileResource(read_info->filename);
  read_info=DestroyImageInfo(read_info);
  if (image == (Image *) NULL)
    return((Image *) NULL);
  return(GetFirstImageInList(image));
}
예제 #5
0
void*
AI_alert_correlation_thread ( void *arg )
{
	int                       i;
	struct stat               st;

	char                      corr_dot_file[4096]   = { 0 };

#ifdef HAVE_LIBGVC
	char                      corr_ps_file [4096]   = { 0 };
#endif

	double                    avg_correlation       = 0.0,
						 std_deviation         = 0.0,
						 corr_threshold        = 0.0,
						 kb_correlation        = 0.0,
						 bayesian_correlation  = 0.0,
						 neural_correlation    = 0.0;

	size_t                    n_correlations        = 0,
						 n_corr_functions      = 0,
						 n_corr_weights        = 0;

	FILE                      *fp                   = NULL;

	AI_alert_correlation_key  corr_key;
	AI_alert_correlation      *corr                 = NULL;

	AI_alert_type_pair_key    pair_key;
	AI_alert_type_pair        *pair                 = NULL,
						 *unpair               = NULL;

	AI_snort_alert            *alert_iterator       = NULL,
					      *alert_iterator2      = NULL;

	pthread_t                 manual_corr_thread;

	#ifdef                    HAVE_LIBGVC
	char                      corr_png_file[4096]   = { 0 };
	GVC_t                     *gvc                  = NULL;
	graph_t                   *g                    = NULL;
	#endif

	double (**corr_functions)( const AI_snort_alert*, const AI_snort_alert* ) = NULL;
	double (**corr_weights)() = NULL;

	#ifdef HAVE_LIBPYTHON2_6
	PyObject *pyA = NULL,
		    *pyB = NULL;

	PyObject *pArgs = NULL,
		    *pRet  = NULL;

	PyObject **py_corr_functions   = NULL;
	PyObject **py_weight_functions = NULL;

	size_t   n_py_corr_functions   = 0;
	size_t   n_py_weight_functions = 0;

	double   py_value  = 0.0,
		    py_weight = 0.0;

	py_corr_functions = AI_get_py_functions ( &n_py_corr_functions );
	py_weight_functions = AI_get_py_weights ( &n_py_weight_functions );
	#endif

	corr_functions = AI_get_corr_functions ( &n_corr_functions );
	corr_weights   = AI_get_corr_weights ( &n_corr_weights );

	pthread_mutex_init ( &mutex, NULL );

	/* Start the thread for parsing manual correlations from XML */
	if ( pthread_create ( &manual_corr_thread, NULL, AI_manual_correlations_parsing_thread, NULL ) != 0 )
	{
		AI_fatal_err ( "Failed to create the manual correlations parsing thread", __FILE__, __LINE__ );
	}

	while ( 1 )
	{
		sleep ( config->correlationGraphInterval );

		if ( stat ( config->corr_rules_dir, &st ) < 0 )
		{
			_dpd.errMsg ( "AIPreproc: Correlation rules directory '%s' not found, the correlation thread won't be active\n",
					config->corr_rules_dir );
			pthread_exit (( void* ) 0 );
			return ( void* ) 0;
		}

		/* Set the lock flag to true, and keep it this way until I've done with correlating alerts */
		pthread_mutex_lock ( &mutex );

		if ( alerts )
		{
			AI_free_alerts ( alerts );
			alerts = NULL;
		}

		if ( !( alerts = AI_get_clustered_alerts() ))
		{
			pthread_mutex_unlock ( &mutex );
			continue;
		}

		if ( config->use_knowledge_base_correlation_index != 0 )
		{
			AI_kb_index_init ( alerts );
		}

		__AI_correlation_table_cleanup();
		correlation_table = NULL;

		/* Fill the table of correlated alerts */
		for ( alert_iterator = alerts; alert_iterator; alert_iterator = alert_iterator->next )
		{
			for ( alert_iterator2 = alerts; alert_iterator2; alert_iterator2 = alert_iterator2->next )
			{
				if ( alert_iterator != alert_iterator2 && ! (
					alert_iterator->gid == alert_iterator2->gid &&
					alert_iterator->sid == alert_iterator2->sid &&
					alert_iterator->rev == alert_iterator2->rev ))
				{
					if ( !( corr = ( AI_alert_correlation* ) malloc ( sizeof ( AI_alert_correlation ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					corr_key.a = alert_iterator;
					corr_key.b = alert_iterator2;
					corr->key  = corr_key;
					corr->correlation = 0.0;
					n_correlations = 0;

					kb_correlation = AI_kb_correlation_coefficient ( corr_key.a, corr_key.b );
					bayesian_correlation = AI_alert_bayesian_correlation ( corr_key.a, corr_key.b );
					neural_correlation = AI_alert_neural_som_correlation ( corr_key.a, corr_key.b );

					/* Use the correlation indexes for which we have a value */
					if ( bayesian_correlation != 0.0 && config->bayesianCorrelationInterval != 0 )
					{
						corr->correlation += AI_bayesian_correlation_weight() * bayesian_correlation;
						n_correlations++;
					}

					if ( kb_correlation != 0.0 && config->use_knowledge_base_correlation_index )
					{
						corr->correlation += kb_correlation;
						n_correlations++;
					}

					if ( neural_correlation != 0.0 && config->neuralNetworkTrainingInterval != 0 )
					{
						corr->correlation += AI_neural_correlation_weight() * neural_correlation;
						n_correlations++;
					}

					/* Get the correlation indexes from extra correlation modules */
					if (( corr_functions ))
					{
						for ( i=0; i < n_corr_functions; i++ )
						{
							if ( corr_weights[i]() != 0.0 )
							{
								corr->correlation += corr_weights[i]() * corr_functions[i] ( corr_key.a, corr_key.b );
								n_correlations++;
							}
						}
					}

					#ifdef HAVE_LIBPYTHON2_6
					if (( py_corr_functions ))
					{
						pyA = AI_alert_to_pyalert ( corr_key.a );
						pyB = AI_alert_to_pyalert ( corr_key.b );

						if ( pyA && pyB )
						{
							for ( i=0; i < n_py_corr_functions; i++ )
							{
								if ( !( pArgs = Py_BuildValue ( "(OO)", pyA, pyB )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not initialize the Python arguments for the call", __FILE__, __LINE__ );
								}

								if ( !( pRet = PyEval_CallObject ( py_corr_functions[i], pArgs )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not call the correlation function from the Python module", __FILE__, __LINE__ );
								}

								if ( !( PyArg_Parse ( pRet, "d", &py_value )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not parse the correlation value out of the Python correlation function", __FILE__, __LINE__ );
								}

								Py_DECREF ( pRet );
								Py_DECREF ( pArgs );

								if ( !( pRet = PyEval_CallObject ( py_weight_functions[i], (PyObject*) NULL )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not call the correlation function from the Python module", __FILE__, __LINE__ );
								}

								if ( !( PyArg_Parse ( pRet, "d", &py_weight )))
								{
									PyErr_Print();
									AI_fatal_err ( "Could not parse the correlation weight out of the Python correlation function", __FILE__, __LINE__ );
								}

								Py_DECREF ( pRet );

								if ( py_weight != 0.0 )
								{
									corr->correlation += py_weight * py_value;
									n_correlations++;
								}
							}

							Py_DECREF ( pyA ); Py_DECREF ( pyB );
							/* free ( pyA ); free ( pyB ); */
							pyA = NULL; pyB = NULL;
						}
					}
					#endif

					if ( n_correlations != 0 )
					{
						corr->correlation /= (double) n_correlations;
					}

					HASH_ADD ( hh, correlation_table, key, sizeof ( AI_alert_correlation_key ), corr );
				}
			}
		}

		if ( HASH_COUNT ( correlation_table ) > 0 )
		{
			avg_correlation = 0.0;
			std_deviation   = 0.0;

			/* Compute the average correlation coefficient */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				avg_correlation += corr->correlation;
			}

			avg_correlation /= (double) HASH_COUNT ( correlation_table );

			/* Compute the standard deviation */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				std_deviation += ( corr->correlation - avg_correlation ) * ( corr->correlation - avg_correlation );
			}

			std_deviation = sqrt ( std_deviation / (double) HASH_COUNT ( correlation_table ));
			corr_threshold = avg_correlation + ( config->correlationThresholdCoefficient * std_deviation );
			snprintf ( corr_dot_file, sizeof ( corr_dot_file ), "%s/correlated_alerts.dot", config->corr_alerts_dir );
			
			if ( stat ( config->corr_alerts_dir, &st ) < 0 )
			{
				if ( mkdir ( config->corr_alerts_dir, 0755 ) < 0 )
				{
					AI_fatal_err ( "Unable to create directory the correlated alerts directory", __FILE__, __LINE__ );
				}
			} else if ( !S_ISDIR ( st.st_mode )) {
				AI_fatal_err ( "The specified directory for correlated alerts is not a directory", __FILE__, __LINE__ );
			}

			if ( !( fp = fopen ( corr_dot_file, "w" )))
				AI_fatal_err ( "Could not write on the correlated alerts .dot file", __FILE__, __LINE__ );
			fprintf ( fp, "digraph G  {\n" );

			/* Find correlated alerts */
			for ( corr = correlation_table; corr; corr = ( AI_alert_correlation* ) corr->hh.next )
			{
				pair_key.from_sid = corr->key.a->sid;
				pair_key.from_gid = corr->key.a->gid;
				pair_key.from_rev = corr->key.a->rev;
				pair_key.to_sid = corr->key.b->sid;
				pair_key.to_gid = corr->key.b->gid;
				pair_key.to_rev = corr->key.b->rev;

				HASH_FIND ( hh, manual_correlations, &pair_key, sizeof ( pair_key ), pair );
				HASH_FIND ( hh, manual_uncorrelations, &pair_key, sizeof ( pair_key ), unpair );

				/* Yes, BlackLight wrote this line of code in a pair of minutes and immediately
				 * compiled it without a single error */
				if ( !unpair && ( pair || (
						corr->correlation >= corr_threshold &&
						corr_threshold != 0.0 &&
						corr->key.a->timestamp <= corr->key.b->timestamp && ! (
						corr->key.a->gid == corr->key.b->gid &&
						corr->key.a->sid == corr->key.b->sid &&
						corr->key.a->rev == corr->key.b->rev ) && (
							corr->key.a->ip_src_addr == corr->key.b->ip_src_addr || (
								(corr->key.a->h_node[src_addr] && corr->key.b->h_node[src_addr]) ?
									( corr->key.a->h_node[src_addr]->max_val == corr->key.b->h_node[src_addr]->max_val &&
									corr->key.a->h_node[src_addr]->min_val == corr->key.b->h_node[src_addr]->min_val ) : 0
							)) && (
							corr->key.a->ip_dst_addr == corr->key.b->ip_dst_addr || (
								(corr->key.a->h_node[dst_addr] && corr->key.b->h_node[dst_addr]) ?
									( corr->key.a->h_node[dst_addr]->max_val == corr->key.b->h_node[dst_addr]->max_val &&
									corr->key.a->h_node[dst_addr]->min_val == corr->key.b->h_node[dst_addr]->min_val ) : 0
							))
						)
					)
				)  {
					if ( !( corr->key.a->derived_alerts = ( AI_snort_alert** ) realloc ( corr->key.a->derived_alerts,
									(++corr->key.a->n_derived_alerts) * sizeof ( AI_snort_alert* ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					if ( !( corr->key.b->parent_alerts = ( AI_snort_alert** ) realloc ( corr->key.b->parent_alerts,
									(++corr->key.b->n_parent_alerts) * sizeof ( AI_snort_alert* ))))
						AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

					corr->key.a->derived_alerts[ corr->key.a->n_derived_alerts - 1 ] = corr->key.b;
					corr->key.b->parent_alerts [ corr->key.b->n_parent_alerts  - 1 ] = corr->key.a;
					__AI_correlated_alerts_to_dot ( corr, fp );

					if ( config->outdbtype != outdb_none )
					{
						AI_store_correlation_to_db ( corr );
					}
				}
			}

			fprintf ( fp, "}\n" );
			fclose ( fp );

			#ifdef HAVE_LIBGVC
				snprintf ( corr_png_file, sizeof ( corr_png_file ), "%s/correlated_alerts.png", config->corr_alerts_dir );
				snprintf ( corr_ps_file , sizeof ( corr_ps_file  ), "%s/correlated_alerts.ps" , config->corr_alerts_dir );

				if ( !( gvc = gvContext() ))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				if ( !( fp = fopen ( corr_dot_file, "r" )))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				if ( !( g = agread ( fp )))
				{
					pthread_mutex_unlock ( &mutex );
					continue;
				}

				gvLayout ( gvc, g, "dot" );
				gvRenderFilename ( gvc, g, "png", corr_png_file );
				gvRenderFilename ( gvc, g, "ps" , corr_ps_file  );

				gvFreeLayout ( gvc, g );
				agclose ( g );
				fclose ( fp );
			#endif

			/* If no database output is defined, then the alerts have no alert_id, so we cannot use the
			 * web interface for correlating them, as they have no unique identifier */
			if ( config->outdbtype != outdb_none )
			{
				if ( strlen ( config->webserv_dir ) != 0 )
				{
					__AI_correlated_alerts_to_json ();
				}
			}
		}

		pthread_mutex_unlock ( &mutex );
	}

	pthread_exit (( void* ) 0 );
	return (void*) 0;
}		/* -----  end of function AI_alert_correlation_thread  ----- */
예제 #6
0
void GVSkeletonGraph::exportToPng() {
    	setlocale(LC_NUMERIC,"en_US.UTF-8");

	gvRenderFilename(_context,_graph,"png","out.png");
}
예제 #7
0
파일: gv.cpp 프로젝트: Goettsch/game-editor
// render to a filename
void render(Agraph_t *g, char *format, char *filename)
{
    int err;

    err = gvRenderFilename(gvc, g, format, filename);
}
예제 #8
0
void gates_save_layout (GQueue *gates, const char *mode, const char *format, const char *filename)
{
    Agraph_t *graph;
    GVC_t* context;

    if (!gates || g_queue_is_empty (gates))
        return;

    // create context (automatically calls aginit())
    context = gvContext();

    // open a graph
    graph = agopen((char*)"map", AGRAPHSTRICT); // strict, directed graph

    // add all gates to the graph
    //
    for (GList *iter=g_queue_peek_tail_link (gates);iter;iter=g_list_previous (iter)) {
        gate_t *gate = (gate_t*)iter->data;
        char name[5];
        sprintf (name, "%d", gate->uid);
        printf ("creating node with name %s\n", name);
        agnode (graph, name);
    }

    // create edges
    int count=0;
    for (GList *iter=g_queue_peek_tail_link (gates);iter;iter=g_list_previous (iter)) {
        gate_t *gate = (gate_t*)iter->data;
        // find corresponding node
        char name[5];
        sprintf (name, "%d", gate->uid);
        Agnode_t *n1 = agfindnode (graph, name);
        if (!n1) {
            dbg (DBG_ERROR, "failed to retrieve node from name %s", name);
            continue;
        }
        printf ("adding %d edges to node %d\n", gate->ng, gate->uid);
        for (int j=0;j<gate->ng;j++) {
            sprintf (name, "%d", gate->ng_names[j]);
            Agnode_t *n2 = agfindnode (graph, name);
            if (!n2) {
                dbg (DBG_ERROR, "failed to retrieve node from name %s", name);
                continue;
            }
            agedge (graph, n1, n2);
            count++;
        }
    }

    printf ("created %d edges.\n", count);

    // layout the graph
    // choices are: manual, fdp, dot, neato, twopi, circo
    dbg (DBG_CLASS, "rendering graph with graphviz. mode = %s", mode);

    if (strcmp (mode, "fdp")) {
        gvLayout (context, graph, (char*)"fdp");
    } 
    if (strcmp (mode, "dot")) {
        gvLayout (context, graph, (char*)"dot");
    }
    if (strcmp (mode, "neato")) {
        gvLayout (context, graph, (char*)"neato");
    }
    if (strcmp (mode, "twopi")) {
        gvLayout (context, graph, (char*)"twopi");
    }
    if (strcmp (mode, "circo")) {
        gvLayout (context, graph, (char*)"circo");
    }

    // render graph to file
    dbg (DBG_CLASS, "saving graph to file %s", filename);
    gvRenderFilename(context, graph, (char*)format, (char*)filename);
    dbg (DBG_CLASS, "done.");

    // free graph
    gvFreeLayout(context, graph);
    agclose (graph);
    gvFreeContext(context);
}
예제 #9
0
void GVSkeletonGraph::exportToPng() {
    setlocale(LC_NUMERIC,"en_US.UTF-8"); // Débug séparateur de décimales en version française
	gvRenderFilename(_context,_graph,"png","out.png");
}
예제 #10
0
bool
GxlFunction::LazyGxlSequence::InternalIterator::next(Item& aItem)
{
  if(!is_open)
  {
    GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "GxlFunction::LazyGxlSequence Iterator consumed without open");
  }
  Item              lItem;
  Agraph_t          *lGraph = 0;
  GVC_t             *lGvc = 0;
  std::fstream       lSVGFile;
  FILE              *lFile = 0;

  if (!arg_iter->next(lItem)) // exhausted
    return false;

  lGvc = gvContext();

  try {

    std::string lTmpFile = theItemSequence->theFunc->getGraphvizTmpFileName(theItemSequence->theFunc->theModule->getItemFactory());
    lSVGFile.open(lTmpFile.c_str(),
        std::fstream::in | std::fstream::out | std::fstream::trunc);

    gxl2dot(theItemSequence->theFunc->theModule->getItemFactory(), lItem, lSVGFile);
    lSVGFile.close();

    lFile = fopen(lTmpFile.c_str(), "r");
    if (!lFile) {
      std::ostringstream lErrorMsg;
      lErrorMsg << "could not read from file " << lTmpFile.c_str();
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", lErrorMsg.str());
    }
#ifdef GRAPHVIZ_USE_CGRAPH
    lGraph = agread(lFile, NULL);
#else
    lGraph = agread(lFile);
#endif    
    fclose(lFile);

    if (!lGraph) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not read input");
    }

    int blub =  gvLayout(lGvc, lGraph, const_cast<char*>("dot"));
    if ( blub != 0 ) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not generate layout");
    }

    if ( gvRenderFilename(lGvc, lGraph, const_cast<char*>("svg"),
                          const_cast<char*>(lTmpFile.c_str())) != 0 )  {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not render graph");
    }

    lSVGFile.open(lTmpFile.c_str(), std::ifstream::in);
    if (lSVGFile.bad()) {
      std::ostringstream lErrorMsg;
      lErrorMsg << "could not read from file " << lTmpFile.c_str();
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", lErrorMsg.str());
    }

    aItem = Zorba::getInstance(0)->getXmlDataManager()->parseXML(lSVGFile);

    gvFreeLayout(lGvc, lGraph);
    agclose(lGraph);
    gvFreeContext(lGvc);

    remove(lTmpFile.c_str());
  } catch (...) {
    if (lGraph) {
      gvFreeLayout(lGvc, lGraph);
      agclose(lGraph);
    }
    gvFreeContext(lGvc);
    throw;
  }

  return true;

} /* GxlFunction::LazyGxlSequence::next */
예제 #11
0
bool
DotFunction::LazyDotSequence::InternalIterator::next(Item& aItem)
{
  if(!is_open)
  {
    GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "DotFunction::LazyDotSequence Iterator consumed without open");
  }
  Item          lItem;
  Agraph_t      *lGraph = 0;
  String        lGraphInput;
  GVC_t         *lGvc = 0;
  std::ifstream lSVGFile;

  if (!arg_iter->next(lItem)) // exhausted
    return false;

  lGvc = gvContext();

  try {
    lGraphInput = lItem.getStringValue();

    lGraph = agmemread(const_cast<char*>(lGraphInput.c_str()));
    if (!lGraph) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not read input");
    }

    if ( gvLayout(lGvc, lGraph, const_cast<char*>("dot")) != 0 ) {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not generate layout");
    }

    std::string lTmpFile = theItemSequence->theFunc->getGraphvizTmpFileName(theItemSequence->theFunc->theModule->getItemFactory());

    if ( gvRenderFilename(lGvc, lGraph, const_cast<char*>("svg"),
                          const_cast<char*>(lTmpFile.c_str())) != 0 )  {
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", "could not render graph");
    }

    lSVGFile.open(lTmpFile.c_str());
    if (lSVGFile.bad()) {
      std::ostringstream lErrorMsg;
      lErrorMsg << "could not read from file "
                << lTmpFile.c_str();
      GraphvizFunction::throwErrorWithQName(theItemSequence->theFunc->theModule->getItemFactory(), "IM003", lErrorMsg.str());
    }

    aItem = Zorba::getInstance(0)->getXmlDataManager()->parseXML(lSVGFile);

    gvFreeLayout(lGvc, lGraph);
    agclose(lGraph);
    gvFreeContext(lGvc);

    remove(lTmpFile.c_str());
  } catch (...) {
    aItem = NULL;
    if (lGraph) {
      gvFreeLayout(lGvc, lGraph);
      agclose(lGraph);
    }
    gvFreeContext(lGvc);
    throw;
  }

  return true;

} /* DotFunction::LazyDotSequence::next */