Ejemplo n.º 1
0
static int
app_help (gboolean     requested,
          const gchar *command)
{
  const struct help_topic *topic = NULL;
  GString *string;

  string = g_string_new (NULL);

  if (command)
    {
      gint i;

      for (i = 0; i < G_N_ELEMENTS (topics); i++)
        if (g_str_equal (topics[i].command, command))
          topic = &topics[i];

      if (!topic)
        {
          g_string_printf (string, _("Unknown command %s\n\n"), command);
          requested = FALSE;
        }
    }

  g_string_append (string, _("Usage:\n"));

  if (topic)
    {
      gint maxwidth;
      gint i;

      g_string_append_printf (string, "\n  %s %s %s\n\n", "gapplication",
                              topic->command, topic->synopsis ? _(topic->synopsis) : "");
      g_string_append_printf (string, "%s\n\n", _(topic->description));

      if (topic->synopsis)
        {
          g_string_append (string, _("Arguments:\n"));

          maxwidth = 0;
          for (i = 0; i < G_N_ELEMENTS (substvars); i++)
            if (strstr (topic->synopsis, substvars[i].var))
              maxwidth = MAX(maxwidth, strlen (_(substvars[i].var)));

          for (i = 0; i < G_N_ELEMENTS (substvars); i++)
            if (strstr (topic->synopsis, substvars[i].var))
              g_string_append_printf (string, "  %-*.*s   %s\n", maxwidth, maxwidth,
                                      _(substvars[i].var), _(substvars[i].description));
          g_string_append (string, "\n");
        }
    }
  else
    {
      gint maxwidth;
      gint i;

      g_string_append_printf (string, "\n  %s %s %s\n\n", "gapplication", _("COMMAND"), _("[ARGS...]"));
      g_string_append_printf (string, _("Commands:\n"));

      maxwidth = 0;
      for (i = 0; i < G_N_ELEMENTS (topics); i++)
        maxwidth = MAX(maxwidth, strlen (topics[i].command));

      for (i = 0; i < G_N_ELEMENTS (topics); i++)
        g_string_append_printf (string, "  %-*.*s   %s\n", maxwidth, maxwidth,
                                topics[i].command, _(topics[i].summary));

      g_string_append (string, "\n");
      /* Translators: do not translate 'help', but please translate 'COMMAND'. */
      g_string_append_printf (string, _("Use '%s help COMMAND' to get detailed help.\n\n"), "gapplication");
    }

  if (requested)
    g_print ("%s", string->str);
  else
    g_printerr ("%s\n", string->str);

  g_string_free (string, TRUE);

  return requested ? 0 : 1;
}
Ejemplo n.º 2
0
/**
 * Build a more complex string using array notation for up to 10 songs
 */
static gushort build_querystring_multi(gchar **qs)
{
	gchar *sig, *tmp;
	GString *nqs;
	GString *albums, *artists, *lengths, *timestamps, *titles;
	GString *tracks;
	gushort num = 0;
	queue_node *song = queue_peek_head();

	nqs = g_string_new("api_key=" API_KEY "&method=track.scrobble&sk=");
	g_string_append(nqs, as_conn.session_id);

	albums = g_string_new("");
	artists = g_string_new("");
	lengths = g_string_new("");
	timestamps = g_string_new("");
	titles = g_string_new("");
	tracks = g_string_new("");

	while (song && num < 10) {
		gchar *album, *artist, *title;

		g_string_append_printf(albums, "album[%d]%s", num, song->album);
		g_string_append_printf(artists, "artist[%d]%s", num,
				song->artist);
		g_string_append_printf(lengths, "duration[%d]%d", num,
				song->length);
		g_string_append_printf(timestamps, "timestamp[%d]%ld", num,
				song->date);
		g_string_append_printf(titles, "track[%d]%s", num, song->title);
		g_string_append_printf(tracks, "trackNumber[%d]%d", num,
				song->track);

		album = curl_easy_escape(as_conn.handle, song->album, 0);
		artist = curl_easy_escape(as_conn.handle, song->artist, 0);
		title = curl_easy_escape(as_conn.handle, song->title, 0);

		g_string_append_printf(nqs, "&album[%1$d]=%2$s"
				"&artist[%1$d]=%3$s&duration[%1$d]=%4$d"
				"&timestamp[%1$d]=%5$ld&track[%1$d]=%6$s"
				"&trackNumber[%1$d]=%7$d", num, album, artist,
				song->length, song->date, title, song->track);

		curl_free(album); curl_free(artist); curl_free(title);

		num++;
		song = queue_peek_nth(num);
	}

	tmp = g_strdup_printf("%sapi_key" API_KEY "%s%smethodtrack.scrobble"
			"sk%s%s%s%s" API_SECRET, albums->str, artists->str,
			lengths->str, as_conn.session_id, timestamps->str,
			tracks->str, titles->str);
	sig = g_compute_checksum_for_string(G_CHECKSUM_MD5, tmp, -1);
	g_free(tmp);
	g_string_free(albums, TRUE);
	g_string_free(artists, TRUE);
	g_string_free(lengths, TRUE);
	g_string_free(timestamps, TRUE);
	g_string_free(titles, TRUE);
	g_string_free(tracks, TRUE);

	g_string_append_printf(nqs, "&api_sig=%s", sig);
	g_free(sig);

	*qs = g_string_free(nqs, FALSE);
	return num;
}
Ejemplo n.º 3
0
Archivo: move.c Proyecto: bpa/cube
void g_string_add_solution(gpointer solution, gpointer str) {
	g_string_append_printf(str, "\n%s", (gchar*)solution);
}
Ejemplo n.º 4
0
gchar *
sim_event_get_insert_clause_values (SimEvent   *event)
{
  gchar  time[TIMEBUF_SIZE];
	gchar *timestamp = time;
  GString *query;
	gchar *values;
  gchar *e_rep_act_src = NULL;
  gchar *e_rep_act_dst = NULL;
  gchar *e_src_hostname = NULL;
  gchar *e_dst_hostname = NULL;
  gchar *src_mac = NULL, *dst_mac = NULL;
  GdaConnection *conn;

  g_return_val_if_fail (SIM_IS_EVENT (event), NULL);

  conn = sim_database_get_conn (ossim.dbossim);

	values =  sim_event_get_text_escape_fields_values  (event);

  // If we already have the timestamp we use it.. else we calculate it
  if(event->time_str)
    timestamp = event->time_str;
	else
    strftime (timestamp, TIMEBUF_SIZE, "%F %T", gmtime ((time_t *) &event->time));

  if (event->str_rep_act_src)
    e_rep_act_src = sim_str_escape (event->str_rep_act_src, conn, 0);
  if (event->str_rep_act_dst)
    e_rep_act_dst = sim_str_escape (event->str_rep_act_dst, conn, 0);

  if (event->src_hostname)
    e_src_hostname = sim_str_escape (event->src_hostname, conn, 0);
  if (event->dst_hostname)
    e_dst_hostname = sim_str_escape (event->dst_hostname, conn, 0);

  if (event->src_mac)
    src_mac = sim_mac_to_db_string (event->src_mac);
  if (event->dst_mac)
    dst_mac = sim_mac_to_db_string (event->dst_mac);

  query = g_string_new ("");
  g_string_append_printf (query, "(%s", sim_uuid_get_db_string (event->id));
  g_string_append_printf (query, ",%s", sim_uuid_get_db_string (sim_context_get_id (event->context)));
  g_string_append_printf (query, ",'%s'", timestamp);
  g_string_append_printf (query, ",%f", event->tzone);
  g_string_append_printf (query, ",%s", sim_uuid_get_db_string (event->sensor_id));
  g_string_append_printf (query, ",'%s'", (event->interface) ? event->interface : "");
  g_string_append_printf (query, ",%d", event->type);
  g_string_append_printf (query, ",%d", event->plugin_id);
  g_string_append_printf (query, ",%d", event->plugin_sid);
  g_string_append_printf (query, ",%d", event->protocol);
  g_string_append_printf (query, ",%s", sim_inet_get_db_string (event->src_ia));
  g_string_append_printf (query, ",%s", sim_inet_get_db_string (event->dst_ia));
  g_string_append_printf (query, ",%s", (event->src_net) ? sim_uuid_get_db_string (sim_net_get_id (event->src_net)) : "NULL");
  g_string_append_printf (query, ",%s", (event->dst_net) ? sim_uuid_get_db_string (sim_net_get_id (event->dst_net)) : "NULL");
  g_string_append_printf (query, ",%d", event->src_port);
  g_string_append_printf (query, ",%d", event->dst_port);
  g_string_append_printf (query, ",%d", event->condition);
  g_string_append_printf (query, ",%d", event->interval);
  g_string_append_printf (query, ",%d", 0); //FIXME event->absolute
  g_string_append_printf (query, ",%d", event->priority);
  g_string_append_printf (query, ",%d", event->reliability);
  g_string_append_printf (query, ",%d", event->asset_src);
  g_string_append_printf (query, ",%d", event->asset_dst);
  g_string_append_printf (query, ",%d", (gint) event->risk_c);
  g_string_append_printf (query, ",%d", (gint) event->risk_a);
  g_string_append_printf (query, ",%d", event->alarm);
  g_string_append_printf (query, ",%s", values);
  g_string_append_printf (query, ",%u", event->rep_prio_src);
  g_string_append_printf (query, ",%u", event->rep_prio_dst);
  g_string_append_printf (query, ",%u", event->rep_rel_src);
  g_string_append_printf (query, ",%u", event->rep_rel_dst);
  g_string_append_printf (query, ",'%s'", (e_rep_act_src) ? e_rep_act_src : "");
  g_string_append_printf (query, ",'%s'", (e_rep_act_dst) ? e_rep_act_dst : "");
  g_string_append_printf (query, ",'%s'", (e_src_hostname) ? e_src_hostname : "");
  g_string_append_printf (query, ",'%s'", (e_dst_hostname) ? e_dst_hostname : "");
  g_string_append_printf (query, ",%s", (src_mac) ? src_mac : "NULL");
  g_string_append_printf (query, ",%s", (dst_mac) ? dst_mac : "NULL");
  g_string_append_printf (query, ",%s", (event->src_id) ? sim_uuid_get_db_string (event->src_id) : "NULL");
  g_string_append_printf (query, ",%s)", (event->dst_id) ? sim_uuid_get_db_string (event->dst_id) : "NULL");

  g_free (values);

  return g_string_free (query, FALSE);
}
Ejemplo n.º 5
0
/**
 * sim_event_to_string:
 * @event: a #SimEvent object.
 *
 */
gchar *
sim_event_to_string (SimEvent * event)
{
  GString *str;
  gchar *ip;
  gchar * base64;
  gint    base64_len;
  SimUuid * net_id;

  g_return_val_if_fail(SIM_IS_EVENT (event), NULL);

  str = g_string_new("event ");

  g_string_append_printf(str, "event_id=\"%s\" ", sim_uuid_get_string (event->id));
  g_string_append_printf(str, "ctx=\"%s\" ", sim_uuid_get_string (sim_context_get_id (event->context)));
  g_string_append_printf(str, "alarm=\"%d\" ", event->alarm);
  str = g_string_append (str, "is_remote=\"1\" ");

  gchar *aux = sim_event_get_str_from_type(event->type);
  if (aux)
  {
    g_string_append_printf(str, "type=\"%s\" ", aux);
    g_free(aux);
  }

  g_string_append_printf(str, "date=\"%u\" ", (guint)event->time);
  g_string_append_printf(str, "tzone=\"%4.2f\" ", event->tzone);

  if (event->time_str)
    g_string_append_printf(str, "fdate=\"%s\" ", event->time_str);

  if (event->plugin_id)
    g_string_append_printf(str, "plugin_id=\"%d\" ", event->plugin_id);

  if (event->plugin_sid)
    g_string_append_printf(str, "plugin_sid=\"%d\" ", event->plugin_sid);

  if (event->src_ia)
  {
    ip = sim_inet_get_canonical_name (event->src_ia);
    g_string_append_printf (str, "src_ip=\"%s\" ", ip);
    g_free (ip);
  }

  if (event->src_port)
    g_string_append_printf(str, "src_port=\"%d\" ", event->src_port);

  if (event->dst_ia)
  {
    ip = sim_inet_get_canonical_name (event->dst_ia);
    g_string_append_printf (str, "dst_ip=\"%s\" ", ip);
    g_free (ip);
  }

  if (event->dst_port)
    g_string_append_printf(str, "dst_port=\"%d\" ", event->dst_port);

  if (event->src_net)
  {
    net_id = sim_net_get_id (event->src_net);
    g_string_append_printf (str, "src_net=\"%s\" ", sim_uuid_get_string (net_id));
  }

  if (event->dst_net)
  {
    net_id = sim_net_get_id (event->dst_net);
    g_string_append_printf (str, "dst_net=\"%s\" ", sim_uuid_get_string (net_id));
  }

  if (event->sensor)
  {
    ip = sim_inet_get_canonical_name (event->sensor);
    g_string_append_printf(str, "sensor=\"%s\" ", ip);
    g_free (ip);
  }
  if (event->sensor_id)
    g_string_append_printf(str, "sensor_id=\"%s\" ", sim_uuid_get_string (event->sensor_id));

  if (event->device)
  {
    ip = sim_inet_get_canonical_name (event->device);
    g_string_append_printf(str, "device=\"%s\" ", ip);
    g_free (ip);
  }

  if (event->device_id)
    g_string_append_printf (str, "device_id=\"%d\" ", event->device_id);

#if 0
  if (event->server)
    g_string_append_printf (str, "server=\"%s\" ", event->server);
#endif

  if (event->interface)
    g_string_append_printf(str, "interface=\"%s\" ", event->interface);

  if (event->protocol)
  {
    gchar *value = sim_protocol_get_str_from_type(event->protocol);
    g_string_append_printf(str, "protocol=\"%s\" ", value);
    g_free(value);
  }

  if (event->condition)
  {
    gchar *value = sim_condition_get_str_from_type(event->condition);
    g_string_append_printf(str, "condition=\"%s\" ", value);
    g_free(value);
  }
  if (event->value)
    g_string_append_printf(str, "value=\"%s\" ", event->value);
  if (event->interval)
    g_string_append_printf(str, "interval=\"%d\" ", event->interval);

  if (event->is_priority_set)
    g_string_append_printf(str, "priority=\"%d\" ", event->priority);
  if (event->is_reliability_set)
    g_string_append_printf(str, "reliability=\"%d\" ", event->reliability);

  g_string_append_printf(str, "asset_src=\"%d\" ", event->asset_src);
  g_string_append_printf(str, "asset_dst=\"%d\" ", event->asset_dst);

  if (event->risk_c)
    g_string_append_printf(str, "risk_a=\"%lf\" ", event->risk_a);
  if (event->risk_a)
    g_string_append_printf(str, "risk_c=\"%lf\" ", event->risk_c);

  // Only forward this field if this is a special event.
  if ((event->data) && sim_event_is_special (event))
  {
    gchar *base64;
    base64 = g_base64_encode ((guchar *)event->data, strlen(event->data));
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf (str, "data=\"%s\" ", base64);
    g_free (base64);
  }

  if (event->log)
  {
    base64 = g_base64_encode((guchar*)event->log->str, event->log->len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "log=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->filename && (base64_len = strlen(event->filename)))
  {
    base64 = g_base64_encode( (guchar*)event->filename, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "filename=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->username && (base64_len = strlen(event->username)))
  {
    base64 = g_base64_encode( (guchar*)event->username, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "username=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->password && (base64_len = strlen(event->password)))
  {
    base64 = g_base64_encode( (guchar*) event->password, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "password=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata1 && (base64_len = strlen(event->userdata1)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata1, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata1=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata2 && (base64_len = strlen(event->userdata2)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata2, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata2=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata3 && (base64_len = strlen(event->userdata3)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata3, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata3=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata4 && (base64_len = strlen(event->userdata4)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata4, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata4=\"%s\" ", base64);
    g_free (base64);
  }
  if (event->userdata5 && (base64_len = strlen(event->userdata5)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata5, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata5=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata6 && (base64_len = strlen(event->userdata6)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata6, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata6=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata7 && (base64_len = strlen(event->userdata7)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata7, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata7=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata8 && (base64_len = strlen(event->userdata8)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata8, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata8=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->userdata9 && (base64_len = strlen(event->userdata9)))
  {
    base64 = g_base64_encode( (guchar*)event->userdata9, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "userdata9=\"%s\" ", base64);
    g_free(base64);
  }
  if (event->src_username_raw && (base64_len = strlen(event->src_username_raw)))
  {
    base64 = g_base64_encode ((guchar *)event->src_username_raw, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "src_username=\"%s\" ", base64);
    g_free (base64);
  }
  if (event->dst_username_raw && (base64_len = strlen (event->dst_username_raw)))
  {
    base64 = g_base64_encode ((guchar *)event->dst_username_raw, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "dst_username=\"%s\" ", base64);
    g_free (base64);
  }
  if (event->src_id)
    g_string_append_printf(str, "src_id=\"%s\" ", sim_uuid_get_string (event->src_id));
  if (event->dst_id)
    g_string_append_printf(str, "dst_id=\"%s\" ", sim_uuid_get_string (event->dst_id));
  if (event->src_hostname)
    g_string_append_printf(str, "src_hostname=\"%s\" ", event->src_hostname);
  if (event->dst_hostname)
    g_string_append_printf(str, "dst_hostname=\"%s\" ", event->dst_hostname);
  if (event->src_mac)
    g_string_append_printf(str, "src_mac=\"%s\" ", event->src_mac);
  if (event->dst_mac)
    g_string_append_printf(str, "dst_mac=\"%s\" ", event->dst_mac);
  if (event->rep_prio_src)
    g_string_append_printf(str, "rep_prio_src=\"%u\" ", event->rep_prio_src);

  if (event->rep_prio_dst)
    g_string_append_printf(str, "rep_prio_dst=\"%u\" ", event->rep_prio_dst);

  if (event->rep_rel_src)
    g_string_append_printf(str, "rep_rel_src=\"%u\" ", event->rep_rel_src);

  if (event->rep_rel_dst)
    g_string_append_printf(str, "rep_rel_dst=\"%u\" ", event->rep_rel_dst);

  if (event->str_rep_act_src && (base64_len = strlen(event->str_rep_act_src)))
  {
    base64 = g_base64_encode( (guchar*)event->str_rep_act_src, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "rep_act_src=\"%s\" ", base64);
    g_free(base64);
  }

  if (event->str_rep_act_dst && (base64_len = strlen(event->str_rep_act_dst)))
  {
    base64 = g_base64_encode( (guchar*)event->str_rep_act_dst, base64_len);
    if(base64 == NULL)
      return g_string_free(str, TRUE);
    g_string_append_printf(str, "rep_act_dst=\"%s\" ", base64);
    g_free(base64);
  }

  /* We need to check that the */
  if (event->binary_data != NULL)
  {
    g_string_append_printf(str,"binary_data=\"%s\" ", event->binary_data);
  }

  g_string_append_printf(str, "\n");

  return g_string_free(str, FALSE);
}
Ejemplo n.º 6
0
static void
as_node_to_xml_string (GString *xml,
		       guint depth_offset,
		       const AsNode *n,
		       AsNodeToXmlFlags flags)
{
	AsNodeData *data = n->data;
	AsNode *c;
	const gchar *tag_str;
	const gchar *comment;
	guint depth = g_node_depth ((GNode *) n);
	gchar *attrs;

	/* comment */
	comment = as_node_get_comment (n);
	if (comment != NULL) {
		guint i;
		g_auto(GStrv) split = NULL;

		/* do not put additional spacing for the root node */
		if (depth_offset < g_node_depth ((GNode *) n) &&
		    (flags & AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE) > 0)
			g_string_append (xml, "\n");
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_INDENT) > 0)
			as_node_add_padding (xml, depth - depth_offset);

		/* add each comment section */
		split = g_strsplit (comment, "<&>", -1);
		for (i = 0; split[i] != NULL; i++) {
			g_string_append_printf (xml, "<!--%s-->", split[i]);
			if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE) > 0)
				g_string_append (xml, "\n");
		}
	}

	/* root node */
	if (data == NULL || as_node_get_tag (n) == AS_TAG_LAST) {
		if ((flags & AS_NODE_TO_XML_FLAG_SORT_CHILDREN) > 0)
			as_node_sort_children (n->children);
		for (c = n->children; c != NULL; c = c->next)
			as_node_to_xml_string (xml, depth_offset, c, flags);

	/* leaf node */
	} else if (n->children == NULL) {
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_INDENT) > 0)
			as_node_add_padding (xml, depth - depth_offset);
		attrs = as_node_get_attr_string (data);
		tag_str = as_tag_data_get_name (data);
		if (data->cdata == NULL || data->cdata[0] == '\0') {
			g_string_append_printf (xml, "<%s%s/>",
						tag_str, attrs);
		} else {
			as_node_cdata_to_escaped (data);
			g_string_append_printf (xml, "<%s%s>%s</%s>",
						tag_str,
						attrs,
						data->cdata,
						tag_str);
		}
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE) > 0)
			g_string_append (xml, "\n");
		g_free (attrs);

	/* node with children */
	} else {
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_INDENT) > 0)
			as_node_add_padding (xml, depth - depth_offset);
		attrs = as_node_get_attr_string (data);
		tag_str = as_tag_data_get_name (data);
		g_string_append_printf (xml, "<%s%s>", tag_str, attrs);
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE) > 0)
			g_string_append (xml, "\n");
		g_free (attrs);
		if ((flags & AS_NODE_TO_XML_FLAG_SORT_CHILDREN) > 0)
			as_node_sort_children (n->children);
		for (c = n->children; c != NULL; c = c->next)
			as_node_to_xml_string (xml, depth_offset, c, flags);

		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_INDENT) > 0)
			as_node_add_padding (xml, depth - depth_offset);
		g_string_append_printf (xml, "</%s>", tag_str);
		if ((flags & AS_NODE_TO_XML_FLAG_FORMAT_MULTILINE) > 0)
			g_string_append (xml, "\n");
	}
}
Ejemplo n.º 7
0
gchar *
wtap_get_debug_if_descr(const wtap_optionblock_t if_descr,
                        const int indent,
                        const char* line_end)
{
	char* tmp_content;
	wtapng_if_descr_mandatory_t* if_descr_mand;
	GString *info = g_string_new("");
	guint64 tmp64;
	gint8 itmp8;
	guint8 tmp8;
	wtapng_if_descr_filter_t* if_filter;

	g_assert(if_descr);

	if_descr_mand = (wtapng_if_descr_mandatory_t*)wtap_optionblock_get_mandatory_data(if_descr);
	wtap_optionblock_get_option_string(if_descr, OPT_IDB_NAME, &tmp_content);
	g_string_printf(info,
			"%*cName = %s%s", indent, ' ',
			tmp_content ? tmp_content : "UNKNOWN",
			line_end);

	wtap_optionblock_get_option_string(if_descr, OPT_IDB_DESCR, &tmp_content);
	g_string_append_printf(info,
			"%*cDescription = %s%s", indent, ' ',
			tmp_content ? tmp_content : "NONE",
			line_end);

	g_string_append_printf(info,
			"%*cEncapsulation = %s (%d/%u - %s)%s", indent, ' ',
			wtap_encap_string(if_descr_mand->wtap_encap),
			if_descr_mand->wtap_encap,
			if_descr_mand->link_type,
			wtap_encap_short_string(if_descr_mand->wtap_encap),
			line_end);

	wtap_optionblock_get_option_uint64(if_descr, OPT_IDB_SPEED, &tmp64);
	g_string_append_printf(info,
			"%*cSpeed = %" G_GINT64_MODIFIER "u%s", indent, ' ',
			tmp64,
			line_end);

	g_string_append_printf(info,
			"%*cCapture length = %u%s", indent, ' ',
			if_descr_mand->snap_len,
			line_end);

	wtap_optionblock_get_option_uint8(if_descr, OPT_IDB_FCSLEN, &itmp8);
	g_string_append_printf(info,
			"%*cFCS length = %d%s", indent, ' ',
			itmp8,
			line_end);

	g_string_append_printf(info,
			"%*cTime precision = %s (%d)%s", indent, ' ',
			wtap_tsprec_string(if_descr_mand->tsprecision),
			if_descr_mand->tsprecision,
			line_end);

	g_string_append_printf(info,
			"%*cTime ticks per second = %" G_GINT64_MODIFIER "u%s", indent, ' ',
			if_descr_mand->time_units_per_second,
			line_end);

	wtap_optionblock_get_option_uint8(if_descr, OPT_IDB_TSRESOL, &tmp8);
	g_string_append_printf(info,
			"%*cTime resolution = 0x%.2x%s", indent, ' ',
			tmp8,
			line_end);

	wtap_optionblock_get_option_custom(if_descr, OPT_IDB_FILTER, (void**)&if_filter);
	g_string_append_printf(info,
			"%*cFilter string = %s%s", indent, ' ',
			if_filter->if_filter_str ? if_filter->if_filter_str : "NONE",
			line_end);

	wtap_optionblock_get_option_string(if_descr, OPT_IDB_OS, &tmp_content);
	g_string_append_printf(info,
			"%*cOperating system = %s%s", indent, ' ',
			tmp_content ? tmp_content : "UNKNOWN",
			line_end);

	wtap_optionblock_get_option_string(if_descr, OPT_COMMENT, &tmp_content);
	g_string_append_printf(info,
			"%*cComment = %s%s", indent, ' ',
			tmp_content ? tmp_content : "NONE",
			line_end);

	g_string_append_printf(info,
			"%*cBPF filter length = %u%s", indent, ' ',
			if_filter->bpf_filter_len,
			line_end);

	g_string_append_printf(info,
			"%*cNumber of stat entries = %u%s", indent, ' ',
			if_descr_mand->num_stat_entries,
			line_end);

	return g_string_free(info, FALSE);
}
Ejemplo n.º 8
0
gchar *
gda_postgres_render_CREATE_USER (GdaServerProvider *provider, GdaConnection *cnc, 
				 GdaServerOperation *op, G_GNUC_UNUSED GError **error)
{
	GString *string;
	const GValue *value;
	gchar *sql = NULL;
	gchar *tmp;
	gboolean with = FALSE, first, use_role = TRUE;
	gint nrows, i;
	PostgresConnectionData *cdata = NULL;

	if (cnc) {
		g_return_val_if_fail (GDA_IS_CONNECTION (cnc), FALSE);
		g_return_val_if_fail (gda_connection_get_provider (cnc) == provider, FALSE);
		cdata = (PostgresConnectionData*) gda_connection_internal_get_provider_data_error (cnc, error);
	}
	if (cdata && (cdata->reuseable->version_float < 8.1))
		use_role = FALSE;

	if (use_role)
		string = g_string_new ("CREATE ROLE ");
	else
		string = g_string_new ("CREATE USER ");

	tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/USER_DEF_P/USER_NAME", error);
	if (!tmp) {
		g_string_free (string, TRUE);
		return NULL;
	}

	g_string_append (string, tmp);
	g_free (tmp);

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/PASSWORD");
	if (value && G_VALUE_HOLDS (value, G_TYPE_STRING) &&
	    g_value_get_string (value) && (*g_value_get_string (value))) {
		GdaDataHandler *dh;
		const GValue *value2;

		g_string_append (string, " WITH");
		with = TRUE;

		value2 = gda_server_operation_get_value_at (op, "/USER_DEF_P/PASSWORD_ENCRYPTED");
		if (value2 && G_VALUE_HOLDS (value2, G_TYPE_BOOLEAN) && g_value_get_boolean (value2))
			g_string_append (string, " ENCRYPTED");

		g_string_append (string, " PASSWORD ");
		dh = gda_server_provider_get_data_handler_g_type (provider, cnc, G_TYPE_STRING);
		if (!dh)
			dh = gda_data_handler_get_default (G_TYPE_STRING);

		tmp = gda_data_handler_get_sql_from_value (dh, value);
		g_string_append (string, tmp);
		g_free (tmp);
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/UID");
	if (value && G_VALUE_HOLDS (value, G_TYPE_UINT)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append_printf (string, "SYSID %u", g_value_get_uint (value));
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_SUPERUSER");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " SUPERUSER");
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_CREATEDB");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " CREATEDB");
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_CREATEROLE");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " CREATEROLE");
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_CREATEUSER");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " CREATEUSER");
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_INHERIT");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " INHERIT");
	}
	else {
		if (!with) {
			g_string_append (string, " WITH");
			with = TRUE;
		}
		g_string_append (string, " NOINHERIT");
	}

	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CAP_LOGIN");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
		g_string_append (string, " LOGIN");
		value = gda_server_operation_get_value_at (op, "/USER_DEF_P/CNX_LIMIT");
		if (value && G_VALUE_HOLDS (value, G_TYPE_INT))
			g_string_append_printf (string, " CONNECTION LIMIT %d",
						g_value_get_int (value));
	}

	
	nrows = gda_server_operation_get_sequence_size (op, "/GROUPS_S");
	for (first  = TRUE, i = 0; i < nrows; i++) {
		gchar *name;
		if (use_role)
			name = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/GROUPS_S/%d/ROLE",
									   error, i);
		else
			name = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/GROUPS_S/%d/USER",
									   error, i);

		if (name) {
			if (first) {
				first = FALSE;
				if (use_role)
					g_string_append (string, " IN ROLE ");
				else
					g_string_append (string, " IN GROUP ");
			}
			else
				g_string_append (string, ", ");

			g_string_append (string, name);
			g_free (name);
		}
		else {
			g_string_free (string, TRUE);
			return NULL;
		}
	}

	nrows = gda_server_operation_get_sequence_size (op, "/ROLES_S");
	for (first  = TRUE, i = 0; i < nrows; i++) {
		gchar *name;
		name = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/ROLES_S/%d/ROLE", error, i);
		if (name) {
			if (first) {
				first = FALSE;
				g_string_append (string, " ROLE ");
			}
			else
				g_string_append (string, ", ");

			g_string_append (string, name);
			g_free (name);
		}
		else {
			g_string_free (string, TRUE);
			return NULL;
		}
	}

	nrows = gda_server_operation_get_sequence_size (op, "/ADMINS_S");
	for (first  = TRUE, i = 0; i < nrows; i++) {
		gchar *name;
		name = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/ADMINS_S/%d/ROLE", error, i);
		if (name) {
			if (first) {
				first = FALSE;
				g_string_append (string, " ADMIN ");
			}
			else
				g_string_append (string, ", ");

			g_string_append (string, name);
			g_free (name);
		}
		else {
			g_string_free (string, TRUE);
			return NULL;
		}
	}
	
	value = gda_server_operation_get_value_at (op, "/USER_DEF_P/VALIDITY");
	if (value && G_VALUE_HOLDS (value, GDA_TYPE_TIMESTAMP)) {
		if (value) {
			GdaDataHandler *dh;
			if (!with) {
				g_string_append (string, " WITH");
				with = TRUE;
			}
			dh = gda_server_provider_get_data_handler_g_type (provider, cnc, GDA_TYPE_TIMESTAMP);
			if (!dh)
				dh = gda_data_handler_get_default (GDA_TYPE_TIMESTAMP);
			
			g_string_append (string, " VALID UNTIL ");
			tmp = gda_data_handler_get_sql_from_value (dh, value);
			g_string_append (string, tmp);
			g_free (tmp);
		}
	}

	sql = string->str;
	g_string_free (string, FALSE);

	return sql;
}
Ejemplo n.º 9
0
int
main(int argc, char *argv[])
{
  int                 opt;
  gboolean            do_append          = FALSE;
  gboolean            verbose            = FALSE;
  int                 in_file_count      = 0;
  guint               snaplen            = 0;
#ifdef PCAP_NG_DEFAULT
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
#else
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
#endif
  int                 frame_type         = -2;
  int                 out_fd;
  merge_in_file_t    *in_files           = NULL, *in_file;
  int                 i;
  struct wtap_pkthdr *phdr, snap_phdr;
  wtap_dumper        *pdh;
  int                 open_err, read_err = 0, write_err, close_err;
  gchar              *err_info;
  int                 err_fileno;
  char               *out_filename       = NULL;
  gboolean            got_read_error     = FALSE, got_write_error = FALSE;
  int                 count;

#ifdef _WIN32
  arg_list_utf_16to8(argc, argv);
  create_app_running_mutex();
#endif /* _WIN32 */

  /* Process the options first */
  while ((opt = getopt(argc, argv, "aF:hs:T:vw:")) != -1) {

    switch (opt) {
    case 'a':
      do_append = !do_append;
      break;

    case 'F':
      file_type = wtap_short_string_to_file_type_subtype(optarg);
      if (file_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
                optarg);
        list_capture_types();
        exit(1);
      }
      break;

    case 'h':
      usage(FALSE);
      exit(0);
      break;

    case 's':
      snaplen = get_positive_int(optarg, "snapshot length");
      break;

    case 'T':
      frame_type = wtap_short_string_to_encap(optarg);
      if (frame_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
                optarg);
        list_encap_types();
        exit(1);
      }
      break;

    case 'v':
      verbose = TRUE;
      break;

    case 'w':
      out_filename = optarg;
      break;

    case '?':              /* Bad options if GNU getopt */
      switch(optopt) {
      case'F':
        list_capture_types();
        break;
      case'T':
        list_encap_types();
        break;
      default:
        usage(TRUE);
      }
      exit(1);
      break;
    }
  }

  /* check for proper args; at a minimum, must have an output
   * filename and one input file
   */
  in_file_count = argc - optind;
  if (!out_filename) {
    fprintf(stderr, "mergecap: an output filename must be set with -w\n");
    fprintf(stderr, "          run with -h for help\n");
    return 1;
  }
  if (in_file_count < 1) {
    fprintf(stderr, "mergecap: No input files were specified\n");
    return 1;
  }

  /* open the input files */
  if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
                           &open_err, &err_info, &err_fileno)) {
    fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
            wtap_strerror(open_err));
    switch (open_err) {

    case WTAP_ERR_UNSUPPORTED:
    case WTAP_ERR_UNSUPPORTED_ENCAP:
    case WTAP_ERR_BAD_FILE:
      fprintf(stderr, "(%s)\n", err_info);
      g_free(err_info);
      break;
    }
    return 2;
  }

  if (verbose) {
    for (i = 0; i < in_file_count; i++)
      fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
              wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
  }

  if (snaplen == 0) {
    /*
     * Snapshot length not specified - default to the maximum of the
     * snapshot lengths of the input files.
     */
    snaplen = merge_max_snapshot_length(in_file_count, in_files);
  }

  /* set the outfile frame type */
  if (frame_type == -2) {
    /*
     * Default to the appropriate frame type for the input files.
     */
    frame_type = merge_select_frame_type(in_file_count, in_files);
    if (verbose) {
      if (frame_type == WTAP_ENCAP_PER_PACKET) {
        /*
         * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
         */
        int first_frame_type, this_frame_type;

        first_frame_type = wtap_file_encap(in_files[0].wth);
        for (i = 1; i < in_file_count; i++) {
          this_frame_type = wtap_file_encap(in_files[i].wth);
          if (first_frame_type != this_frame_type) {
            fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
            fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[0].filename,
                    wtap_encap_string(first_frame_type),
                    wtap_encap_short_string(first_frame_type));
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[i].filename,
                    wtap_encap_string(this_frame_type),
                    wtap_encap_short_string(this_frame_type));
            break;
          }
        }
      }
      fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
              wtap_encap_string(frame_type),
              wtap_encap_short_string(frame_type));
    }
  }

  /* open the outfile */
  if (strncmp(out_filename, "-", 2) == 0) {
    /* use stdout as the outfile */
    out_fd = 1 /*stdout*/;
  } else {
    /* open the outfile */
    out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
    if (out_fd == -1) {
      fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
              out_filename, g_strerror(errno));
      exit(1);
    }
  }

  /* prepare the outfile */
  if(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG ){
    wtapng_section_t *shb_hdr;
    GString *comment_gstr;

    shb_hdr = g_new(wtapng_section_t,1);
    comment_gstr = g_string_new("File created by merging: \n");

    for (i = 0; i < in_file_count; i++) {
      g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
    }
    shb_hdr->section_length = -1;
    /* options */
    shb_hdr->opt_comment   = comment_gstr->str; /* NULL if not available */
    shb_hdr->shb_hardware  = NULL;              /* NULL if not available, UTF-8 string containing the description of the hardware used to create this section. */
    shb_hdr->shb_os        = NULL;              /* NULL if not available, UTF-8 string containing the name of the operating system used to create this section. */
    shb_hdr->shb_user_appl = "mergecap";        /* NULL if not available, UTF-8 string containing the name of the application used to create this section. */

    pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
                              FALSE /* compressed */, shb_hdr, NULL /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
    g_string_free(comment_gstr, TRUE);
  } else {
    pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
  }
  if (pdh == NULL) {
    merge_close_in_files(in_file_count, in_files);
    g_free(in_files);
    fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
            wtap_strerror(open_err));
    exit(1);
  }

  /* do the merge (or append) */
  count = 1;
  for (;;) {
    if (do_append)
      in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
                                         &err_info);
    else
      in_file = merge_read_packet(in_file_count, in_files, &read_err,
                                  &err_info);
    if (in_file == NULL) {
      /* EOF */
      break;
    }

    if (read_err != 0) {
      /* I/O error reading from in_file */
      got_read_error = TRUE;
      break;
    }

    if (verbose)
      fprintf(stderr, "Record: %u\n", count++);

    /* We simply write it, perhaps after truncating it; we could do other
     * things, like modify it. */
    phdr = wtap_phdr(in_file->wth);
    if (snaplen != 0 && phdr->caplen > snaplen) {
      snap_phdr = *phdr;
      snap_phdr.caplen = snaplen;
      phdr = &snap_phdr;
    }

    if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), &write_err)) {
      got_write_error = TRUE;
      break;
    }
  }

  merge_close_in_files(in_file_count, in_files);
  if (!got_write_error) {
    if (!wtap_dump_close(pdh, &write_err))
      got_write_error = TRUE;
  } else {
    /*
     * We already got a write error; no need to report another
     * write error on close.
     *
     * Don't overwrite the earlier write error.
     */
    (void)wtap_dump_close(pdh, &close_err);
  }

  if (got_read_error) {
    /*
     * Find the file on which we got the error, and report the error.
     */
    for (i = 0; i < in_file_count; i++) {
      if (in_files[i].state == GOT_ERROR) {
        fprintf(stderr, "mergecap: Error reading %s: %s\n",
                in_files[i].filename, wtap_strerror(read_err));
        switch (read_err) {

        case WTAP_ERR_UNSUPPORTED:
        case WTAP_ERR_UNSUPPORTED_ENCAP:
        case WTAP_ERR_BAD_FILE:
          fprintf(stderr, "(%s)\n", err_info);
          g_free(err_info);
          break;
        }
      }
    }
  }

  if (got_write_error) {
    switch (write_err) {

    case WTAP_ERR_UNSUPPORTED_ENCAP:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_PACKET_TOO_LARGE:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" is too large for a \"%s\" file\n.",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    default:
      fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
              wtap_strerror(write_err));
      break;
    }
  }

  g_free(in_files);

  return (!got_read_error && !got_write_error) ? 0 : 2;
}
Ejemplo n.º 10
0
gchar *
gda_postgres_render_CREATE_TABLE (GdaServerProvider *provider, GdaConnection *cnc, 
				  GdaServerOperation *op, GError **error)
{
	GString *string;
	const GValue *value;
	gboolean hasfields = FALSE;
	gint nrows;
	gint i;
	gboolean first;
	GSList *pkfields = NULL; /* list of GValue* composing the pkey */
	gint nbpkfields = 0;
	gchar *sql = NULL;
	gchar *tmp;

	string = g_string_new ("CREATE ");
	value = gda_server_operation_get_value_at (op, "/TABLE_DEF_P/TABLE_TEMP");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, "TEMP ");
	g_string_append (string, "TABLE ");

	tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
							  "/TABLE_DEF_P/TABLE_NAME", error);
	if (!tmp) {
		g_string_free (string, TRUE);
		return NULL;
	}

	g_string_append (string, tmp);
	g_free (tmp);
	g_string_append (string, " (");
		
	/* FIELDS */
	GdaServerOperationNode *node;

	node = gda_server_operation_get_node_info (op, "/FIELDS_A");
	g_assert (node);

	/* finding if there is a composed primary key */
	nrows = gda_data_model_get_n_rows (node->model);
	for (i = 0; i < nrows; i++) {
		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_PKEY/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
			tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
									  "/FIELDS_A/@COLUMN_NAME/%d", error, i);
			if (!tmp) {
				g_string_free (string, TRUE);
				return NULL;
			}

			pkfields = g_slist_append (pkfields, tmp);
			nbpkfields ++;
		}
	}

	/* manually defined fields */
	first = TRUE;
	for (i = 0; i < nrows; i++) {
		hasfields = TRUE;
		if (first) 
			first = FALSE;
		else
			g_string_append (string, ", ");

		tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
								  "/FIELDS_A/@COLUMN_NAME/%d", error, i);
		if (!tmp) {
			g_string_free (string, TRUE);
			return NULL;
		}

		g_string_append (string, tmp);
		g_free (tmp);
		g_string_append_c (string, ' ');

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_AUTOINC/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
			g_string_append (string, "serial");
		else {
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_TYPE/%d", i);
			g_string_append (string, g_value_get_string (value));
		}

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_SIZE/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_UINT)) {
			g_string_append_printf (string, "(%d", g_value_get_uint (value));

			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_SCALE/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_UINT))
				g_string_append_printf (string, ",%d)", g_value_get_uint (value));
			else
				g_string_append (string, ")");
		}

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_DEFAULT/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
			const gchar *str = g_value_get_string (value);
			if (str && *str) {
				g_string_append (string, " DEFAULT ");
				g_string_append (string, str);
			}
		}

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_NNUL/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
			g_string_append (string, " NOT NULL");

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_UNIQUE/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
			g_string_append (string, " UNIQUE");

		if (nbpkfields == 1) {
			value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_PKEY/%d", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
				g_string_append (string, " PRIMARY KEY");
		}

		value = gda_server_operation_get_value_at (op, "/FIELDS_A/@COLUMN_CHECK/%d", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
			const gchar *str = g_value_get_string (value);
			if (str && *str) {
				g_string_append (string, " CHECK (");
				g_string_append (string, str);
				g_string_append_c (string, ')');
			}
		}
	}

	/* LIKE inheritance */
	nrows = gda_server_operation_get_sequence_size (op, "/TABLE_PARENTS_S");
	for (i = 0; i < nrows; i++) {
		value = gda_server_operation_get_value_at (op, "/TABLE_PARENTS_S/%d/TABLE_PARENT_COPY", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && !g_value_get_boolean (value)) {
			tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
									  "/TABLE_PARENTS_S/%d/TABLE_PARENT_TABLE",
									  error, i);
			if (!tmp) {
				g_string_free (string, TRUE);
				return NULL;
			}

			hasfields = TRUE;
			if (first) 
				first = FALSE;
			else
				g_string_append (string, ", ");

			g_string_append (string, "LIKE ");
			g_string_append (string, tmp);
			value = gda_server_operation_get_value_at (op, 
								   "/TABLE_PARENTS_S/%d/TABLE_PARENT_COPY_DEFAULTS", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && 
			    g_value_get_boolean (value))
				g_string_append (string, " INCLUDING DEFAULTS");
			g_free (tmp);
		}
	}

	/* composed primary key */
	if (nbpkfields > 1) {
		GSList *list;

		g_string_append (string, ", PRIMARY KEY (");
		for (list = pkfields; list; list = list->next) {
			if (list != pkfields)
				g_string_append (string, ", ");
			g_string_append (string, (gchar*) list->data);
		}
		g_string_append_c (string, ')');
	}
	g_slist_foreach (pkfields, (GFunc) g_free, NULL);
	g_slist_free (pkfields);

	/* foreign keys */
	first = TRUE;
	node = gda_server_operation_get_node_info (op, "/FKEY_S");
	if (node) {
		nrows = gda_server_operation_get_sequence_size (op, "/FKEY_S");
		for (i = 0; i < nrows; i++) {
			gint nbfields = 0;
			gint j;

			g_string_append (string, ", FOREIGN KEY (");
			node = gda_server_operation_get_node_info (op, "/FKEY_S/%d/FKEY_FIELDS_A", i);
			if (!node || ((nbfields = gda_data_model_get_n_rows (node->model)) == 0)) {
				g_string_free (string, TRUE);
				g_set_error (error, GDA_SERVER_OPERATION_ERROR,
					     GDA_SERVER_OPERATION_INCORRECT_VALUE_ERROR,
					     "%s",
					     _("No field specified in foreign key constraint"));
				return NULL;
			}
			else {
				for (j = 0; j < nbfields; j++) {
					if (j != 0)
						g_string_append (string, ", ");
					tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
											  "/FKEY_S/%d/FKEY_FIELDS_A/@FK_FIELD/%d",
											  error, i, j);
					if (tmp) {
						g_string_append (string, tmp);
						g_free (tmp);
					}
					else {
						g_string_free (string, TRUE);
						return NULL;
					}
				}
			}
			g_string_append (string, ") REFERENCES ");

			tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
									  "/FKEY_S/%d/FKEY_REF_TABLE", error, i);
			if (tmp) {
				g_string_append (string, tmp);
				g_free (tmp);
			}
			else {
				g_string_free (string, TRUE);
				return NULL;
			}

			g_string_append (string, " (");
			for (j = 0; j < nbfields; j++) {
				if (j != 0)
					g_string_append (string, ", ");
				tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
										  "/FKEY_S/%d/FKEY_FIELDS_A/@FK_REF_PK_FIELD/%d",
										  error, i, j);
				if (tmp) {
					g_string_append (string, tmp);
					g_free (tmp);
				}
				else {
					g_string_free (string, TRUE);
					return NULL;
				}
			}
			g_string_append_c (string, ')');
			value = gda_server_operation_get_value_at (op, "/FKEY_S/%d/FKEY_MATCH_TYPE", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING) && g_value_get_string (value))
				g_string_append_printf (string, " %s", g_value_get_string (value));
			value = gda_server_operation_get_value_at (op, "/FKEY_S/%d/FKEY_ONUPDATE", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING) && g_value_get_string (value))
				g_string_append_printf (string, " ON UPDATE %s", g_value_get_string (value));
			value = gda_server_operation_get_value_at (op, "/FKEY_S/%d/FKEY_ONDELETE", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING) && g_value_get_string (value))
				g_string_append_printf (string, " ON DELETE %s", g_value_get_string (value));
			value = gda_server_operation_get_value_at (op, "/FKEY_S/%d/FKEY_DEFERRABLE", i);
			if (value && G_VALUE_HOLDS (value, G_TYPE_STRING) && g_value_get_string (value))
				g_string_append_printf (string, " %s", g_value_get_string (value));
		}
	}

	g_string_append (string, ")");

	/* INHERITS */
	first = TRUE;
	nrows = gda_server_operation_get_sequence_size (op, "/TABLE_PARENTS_S");
	for (i = 0; i < nrows; i++) {
		value = gda_server_operation_get_value_at (op, "/TABLE_PARENTS_S/%d/TABLE_PARENT_COPY", i);
		if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value)) {
			tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider,
									  "/TABLE_PARENTS_S/%d/TABLE_PARENT_TABLE",
									  error, i);
			if (tmp) {
				hasfields = TRUE;
				if (first) {
					g_string_append (string, " INHERITS ");
					first = FALSE;
				}
				else
					g_string_append (string, ", ");
				g_string_append (string, tmp);
				g_free (tmp);
			}
			else {
				g_string_free (string, TRUE);
				return NULL;
			}
		}
	}

	if (!hasfields) {
		g_string_free (string, TRUE);
		g_set_error (error, GDA_SERVER_OPERATION_ERROR,
                             GDA_SERVER_OPERATION_INCORRECT_VALUE_ERROR,
			     "%s", _("Table to create must have at least one row"));
		return NULL;
	}

	value = gda_server_operation_get_value_at (op, "/TABLE_DEF_P/TABLE_WITH_OIDS");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, " WITH OIDS");

	sql = string->str;
	g_string_free (string, FALSE);

	return sql;
}
Ejemplo n.º 11
0
gchar *
gda_postgres_render_ADD_COLUMN (GdaServerProvider *provider, GdaConnection *cnc, 
				GdaServerOperation *op, G_GNUC_UNUSED GError **error)
{
	GString *string;
	const GValue *value;
	gchar *sql = NULL;
	gchar *tmp;

	string = g_string_new ("ALTER TABLE ");

	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/TABLE_ONLY");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, "ONLY ");

	tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/COLUMN_DEF_P/TABLE_NAME", error);
	if (!tmp) {
		g_string_free (string, TRUE);
		return NULL;
	}

	g_string_append (string, tmp);
	g_free (tmp);

	g_string_append (string, " ADD COLUMN ");

	tmp = gda_server_operation_get_sql_identifier_at (op, cnc, provider, "/COLUMN_DEF_P/COLUMN_NAME", error);
	if (!tmp) {
		g_string_free (string, TRUE);
		return NULL;
	}

	g_string_append (string, tmp);
	g_free (tmp);

	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_TYPE");
	g_assert (value && G_VALUE_HOLDS (value, G_TYPE_STRING));
	g_string_append_c (string, ' ');
	g_string_append (string, g_value_get_string (value));

	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_SIZE");
	if (value && G_VALUE_HOLDS (value, G_TYPE_UINT)) {
		g_string_append_printf (string, "(%d", g_value_get_uint (value));

		value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_SCALE");
		if (value && G_VALUE_HOLDS (value, G_TYPE_UINT))
			g_string_append_printf (string, ",%d)", g_value_get_uint (value));
		else
			g_string_append (string, ")");
	}

	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_DEFAULT");
	if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
		const gchar *str = g_value_get_string (value);
		if (str && *str) {
			g_string_append (string, " DEFAULT ");
			g_string_append (string, str);
		}
	}
				
	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_NNUL");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, " NOT NULL");
				
	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_UNIQUE");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, " UNIQUE");
	
	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_PKEY");
	if (value && G_VALUE_HOLDS (value, G_TYPE_BOOLEAN) && g_value_get_boolean (value))
		g_string_append (string, " PRIMARY KEY");
				
	value = gda_server_operation_get_value_at (op, "/COLUMN_DEF_P/COLUMN_CHECK");
	if (value && G_VALUE_HOLDS (value, G_TYPE_STRING)) {
		const gchar *str = g_value_get_string (value);
		if (str && *str) {
			g_string_append (string, " CHECK (");
			g_string_append (string, str);
			g_string_append_c (string, ')');
		}
	}

	sql = string->str;
	g_string_free (string, FALSE);

	return sql;
}
Ejemplo n.º 12
0
static void
_jabber_parse_and_write_message_to_ui(xmlnode *message_node, PurpleBuddy *pb)
{
	xmlnode *body_node, *html_node, *events_node;
	PurpleConnection *gc = purple_account_get_connection(purple_buddy_get_account(pb));
	gchar *body = NULL;
	gboolean composing_event = FALSE;

	body_node = xmlnode_get_child(message_node, "body");
	html_node = xmlnode_get_child(message_node, "html");

	if (body_node == NULL && html_node == NULL) {
		purple_debug_error("bonjour", "No body or html node found, discarding message.\n");
		return;
	}

	events_node = xmlnode_get_child_with_namespace(message_node, "x", "jabber:x:event");
	if (events_node != NULL) {
		if (xmlnode_get_child(events_node, "composing") != NULL)
			composing_event = TRUE;
		if (xmlnode_get_child(events_node, "id") != NULL) {
			/* The user is just typing */
			/* TODO: Deal with typing notification */
			return;
		}
	}

	if (html_node != NULL) {
		xmlnode *html_body_node;

		html_body_node = xmlnode_get_child(html_node, "body");
		if (html_body_node != NULL) {
			xmlnode *html_body_font_node;

			html_body_font_node = xmlnode_get_child(html_body_node, "font");
			/* Types of messages sent by iChat */
			if (html_body_font_node != NULL) {
				gchar *html_body;
				const char *font_face, *font_size,
					*ichat_balloon_color, *ichat_text_color;

				font_face = xmlnode_get_attrib(html_body_font_node, "face");
				/* The absolute iChat font sizes should be converted to 1..7 range */
				font_size = xmlnode_get_attrib(html_body_font_node, "ABSZ");
				if (font_size != NULL)
					font_size = _font_size_ichat_to_purple(atoi(font_size));
				/*font_color = xmlnode_get_attrib(html_body_font_node, "color");*/
				ichat_balloon_color = xmlnode_get_attrib(html_body_node, "ichatballooncolor");
				ichat_text_color = xmlnode_get_attrib(html_body_node, "ichattextcolor");

				html_body = get_xmlnode_contents(html_body_font_node);

				if (html_body == NULL)
					/* This is the kind of formatted messages that Purple creates */
					html_body = xmlnode_to_str(html_body_font_node, NULL);

				if (html_body != NULL) {
					GString *str = g_string_new("<font");

					if (font_face)
						g_string_append_printf(str, " face='%s'", font_face);
					if (font_size)
						g_string_append_printf(str, " size='%s'", font_size);
					if (ichat_text_color)
						g_string_append_printf(str, " color='%s'", ichat_text_color);
					if (ichat_balloon_color)
						g_string_append_printf(str, " back='%s'", ichat_balloon_color);
					g_string_append_printf(str, ">%s</font>", html_body);

					body = g_string_free(str, FALSE);

					g_free(html_body);
				}
			}
		}
	}

	/* Compose the message */
	if (body == NULL && body_node != NULL)
		body = xmlnode_get_data(body_node);

	if (body == NULL) {
		purple_debug_error("bonjour", "No html body or regular body found.\n");
		return;
	}

	/* Send the message to the UI */
	serv_got_im(gc, purple_buddy_get_name(pb), body, 0, time(NULL));

	g_free(body);
}
Ejemplo n.º 13
0
static void
gtk_source_map_rebuild_css (GtkSourceMap *map)
{
	GtkSourceMapPrivate *priv;
	GtkSourceStyleScheme *style_scheme;
	GtkSourceStyle *style = NULL;
	GtkTextBuffer *buffer;
	GString *gstr;
	gboolean alter_alpha = TRUE;
	gchar *background = NULL;

	priv = gtk_source_map_get_instance_private (map);

	if (priv->view == NULL)
	{
		return;
	}

	/*
	 * This is where we calculate the CSS that maps the font for the
	 * minimap as well as the styling for the scrubber.
	 *
	 * The font is calculated from #GtkSourceMap:font-desc. We convert this
	 * to CSS using _gtk_source_pango_font_description_to_css(). It gets
	 * applied to the minimap widget via the CSS style provider which we
	 * attach to the child widget in gtk_source_map_init().
	 *
	 * The rules for calculating the style for the scrubber are as follows.
	 *
	 * If the current style scheme provides a background color for the
	 * scrubber using the "map-overlay" style name, we use that without
	 * any transformations.
	 *
	 * If the style scheme contains a "selection" style scheme, used for
	 * selected text, we use that with a 0.75 alpha value.
	 *
	 * If none of these are met, we take the background from the
	 * #GtkStyleContext using the deprecated
	 * gtk_style_context_get_background_color(). This is non-ideal, but
	 * currently required since we cannot indicate that we want to
	 * alter the alpha for gtk_render_background().
	 */

	gstr = g_string_new (NULL);

	/* Calculate the font if one has been set */
	if (priv->font_desc != NULL)
	{
		gchar *css;

		css = _gtk_source_pango_font_description_to_css (priv->font_desc);
		g_string_append_printf (gstr, "GtkSourceView { %s }\n", css != NULL ? css : "");
		g_free (css);
	}

	buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (priv->view));
	style_scheme = gtk_source_buffer_get_style_scheme (GTK_SOURCE_BUFFER (buffer));

	if (style_scheme != NULL)
	{

		style = gtk_source_style_scheme_get_style (style_scheme, "map-overlay");

		if (style != NULL)
		{
			/* styling is taking as is only if we found a "map-overlay". */
			alter_alpha = FALSE;
		}
		else
		{
			style = gtk_source_style_scheme_get_style (style_scheme, "selection");
		}
	}

	if (style != NULL)
	{
		g_object_get (style,
		              "background", &background,
		              NULL);
	}

	if (background == NULL)
	{
		GtkStyleContext *context;
		GdkRGBA color;

		/*
		 * We failed to locate a style for both "map-overlay" and for
		 * "selection". That means we need to fallback to using the
		 * selected color for the gtk+ theme. This uses deprecated
		 * API because we have no way to tell gtk_render_background()
		 * to render with an alpha.
		 */

		context = gtk_widget_get_style_context (GTK_WIDGET (priv->view));
		gtk_style_context_save (context);
		gtk_style_context_add_class (context, "view");
		G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
		gtk_style_context_get_background_color (context, GTK_STATE_FLAG_SELECTED, &color);
		G_GNUC_END_IGNORE_DEPRECATIONS;
		gtk_style_context_restore (context);
		background = gdk_rgba_to_string (&color);

		/*
		 * Make sure we alter the alpha. It is possible this could be
		 * FALSE here if we found a style for map-overlay but it did
		 * not contain a background color.
		 */
		alter_alpha = TRUE;
	}

	if (alter_alpha)
	{
		GdkRGBA color;

		gdk_rgba_parse (&color, background);
		color.alpha = 0.75;
		g_free (background);
		background = gdk_rgba_to_string (&color);
	}


	if (background != NULL)
	{
		g_string_append_printf (gstr,
		                        "GtkSourceMap.scrubber {\n"
		                        "\tbackground-color: %s;\n"
		                        "\tborder-top: 1px solid shade(%s,0.9);\n"
		                        "\tborder-bottom: 1px solid shade(%s,0.9);\n"
		                        "}\n",
		                        background,
		                        background,
		                        background);
	}

	g_free (background);

	if (gstr->len > 0)
	{
		gtk_css_provider_load_from_data (priv->css_provider, gstr->str, gstr->len, NULL);
	}

	g_string_free (gstr, TRUE);
}
//! \brief try to fix some common errors in the csv representation of invoices
//! * corrects the date format
//! * corrects ambigous values in multi line invoices
//! * ensures customer exists
//! * if quantity is unset, set to 1
//! * if price is unset, delete row
void
gnc_bi_import_fix_bis (GtkListStore * store, guint * fixed, guint * deleted,
                       GString * info, gchar *type)
{
    GtkTreeIter iter;
    gboolean valid, row_deleted, row_fixed;
    gchar *id, *date_opened, *date_posted, *owner_id, *date, *quantity, *price;
    GString *prev_id, *prev_date_opened, *prev_date_posted, *prev_owner_id, *prev_date;	// needed to fix multi line invoices
    guint dummy;
    gint row = 1;

    // allow the call to this function with only GtkListeStore* specified
    if (!fixed)
        fixed = &dummy;
    if (!deleted)
        deleted = &dummy;

    *fixed = 0;
    *deleted = 0;

    // init strings
    prev_id = g_string_new ("");
    prev_date_opened = g_string_new ("");
    prev_date_posted = g_string_new ("");
    prev_owner_id = g_string_new ("");
    prev_date = g_string_new ("");

    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
    while (valid)
    {
        row_deleted = FALSE;
        row_fixed = FALSE;

        // Walk through the list, reading each row
        gtk_tree_model_get (GTK_TREE_MODEL (store), &iter,
                            ID, &id,
                            DATE_OPENED, &date_opened,
                            DATE_POSTED, &date_posted,
                            OWNER_ID, &owner_id,
                            DATE, &date,
                            QUANTITY, &quantity, PRICE, &price, -1);

        if (strlen (price) == 0)
        {
            // invalid row (no price given)
            // no fix possible -> delete row
            valid = gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info,
                                    _("ROW %d DELETED, PRICE_NOT_SET: id=%s\n"),
                                    row, id);
        }
        else if (strlen (quantity) == 0)
        {
            // invalid row (no quantity given)
            // no fix possible -> delete row
            valid = gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info, _("ROW %d DELETED, QTY_NOT_SET: id=%s\n"),
                                    row, id);
        }
        else
        {
            if (strlen (id) == 0)
            {
                // no invoice id specified
                if (prev_id->len == 0)
                {
                    // cannot fix -> delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, ID_NOT_SET\n"), row);
                }
                else
                {
                    // this is a fixable multi line invoice
                    gtk_list_store_set (store, &iter, ID, prev_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember invoice id (to be able to fix multi line invoices)
                g_string_assign (prev_id, id);
                // new invoice => reset all other fixable entries
                g_string_assign (prev_date_opened, "");
                g_string_assign (prev_date_posted, "");
                g_string_assign (prev_owner_id, "");
                g_string_assign (prev_date, "");
            }
        }

        if (!row_deleted)
        {
            // the row is valid (price and id are valid)

            if (strlen (date_opened) == 0)
            {
                if (prev_date_opened->len == 0)
                {
                    // fix this by using the current date
                    gchar temp[20];
                    GDate date;
                    g_date_clear (&date, 1);
                    gnc_gdate_set_today (&date);
                    g_date_strftime (temp, 20, "%x", &date);	// create a locale specific date string
                    g_string_assign (prev_date_opened, temp);
                }
                // fix this by using the previous date_opened value (multi line invoice)
                gtk_list_store_set (store, &iter, DATE_OPENED,
                                    prev_date_opened->str, -1);
                row_fixed = TRUE;
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_opened, date_opened);
            }

            // date_opened is valid

            if (strlen (date_posted) == 0)
            {
                if (prev_date_posted->len == 0)
                {
                    // this invoice will have to get posted manually
                }
                else
                {
                    // multi line invoice => fix it
                    gtk_list_store_set (store, &iter, DATE_POSTED,
                                        prev_date_posted->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_posted, date_posted);
            }

            // date_posted is valid

            if (strlen (quantity) == 0)
            {
                // quantity is unset => set to 1
                gtk_list_store_set (store, &iter, QUANTITY, "1", -1);
                row_fixed = TRUE;
            }

            // quantity is valid

            if (strlen (owner_id) == 0)
            {
                if (prev_owner_id->len == 0)
                {
                    // no customer given and not fixable => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, OWNER_NOT_SET: id=%s\n"),
                                            row, id);
                }
                else
                {
                    gtk_list_store_set (store, &iter, owner_id,
                                        prev_owner_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember owner_id
                g_string_assign (prev_owner_id, owner_id);
            }
            if (g_ascii_strcasecmp (type, "BILL") == 0)
            {
                // BILL: check, if vendor exists
                if (!gnc_search_vendor_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // vendor not found => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, VENDOR_DOES_NOT_EXIST: id=%s\n"),
                                            row, id);
                }
            }
            else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
            {
                // INVOICE: check, if customer exists
                if (!gnc_search_customer_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // customer not found => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, CUSTOMER_DOES_NOT_EXIST: id=%s\n"),
                                            row, id);
                }
            }

            // owner_id is valid
        }

        g_free (id);
        g_free (date_opened);
        g_free (date_posted);
        g_free (owner_id);
        g_free (date);
        g_free (quantity);
        g_free (price);
        if (row_deleted)
        {
            (*deleted)++;
            // reset all remembered values
            g_string_assign (prev_id, "");
            g_string_assign (prev_date_opened, "");
            g_string_assign (prev_date_posted, "");
            g_string_assign (prev_owner_id, "");
            g_string_assign (prev_date, "");
        }
        else if (row_fixed)
            (*fixed)++;

        if (!row_deleted)
            valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);

        row++;
    }

    // deallocate strings
    g_string_free (prev_id, TRUE);
    g_string_free (prev_date_opened, TRUE);
    g_string_free (prev_date_posted, TRUE);
    g_string_free (prev_owner_id, TRUE);
    g_string_free (prev_date, TRUE);

    if (info && (info->len > 0))
    {
        g_string_prepend (info, "\n\n");
        g_string_prepend (info, _("These rows were deleted:"));
    }
}
Ejemplo n.º 15
0
gboolean
cd_sensor_dump_device (CdSensor *sensor, GString *data, GError **error)
{
	g_string_append_printf (data, "dtp94-dump-version:%i\n", 1);
	return TRUE;
}
Ejemplo n.º 16
0
Archivo: gen-doc.c Proyecto: miq/libuca
static void
print_value_info (GParamSpec *pspec)
{
    gchar *default_value = NULL;
    GString *range = g_string_new("");

#define MAKE_RANGE(spec_type, fmt)              \
    {                                           \
        spec_type *spec = (spec_type *) pspec;  \
        g_string_printf (range,                                     \
                         fmt" &#8804; <em>%s</em> &#8804; "fmt,     \
                         spec->minimum,                             \
                         g_param_spec_get_name (pspec),             \
                         spec->maximum);                            \
        default_value = g_strdup_printf (fmt, spec->default_value); \
    }

    switch (pspec->value_type) {
        case G_TYPE_BOOLEAN:
            {
                GParamSpecBoolean *spec = (GParamSpecBoolean *) pspec;
                default_value = spec->default_value ? g_strdup ("<code>TRUE</code>") : g_strdup ("<code>FALSE</code>");
            }
            break;

        case G_TYPE_UINT:
            MAKE_RANGE (GParamSpecUInt, "%i");
            break;

        case G_TYPE_FLOAT:
            MAKE_RANGE (GParamSpecFloat, "%.1e");
            break;

        case G_TYPE_DOUBLE:
            MAKE_RANGE (GParamSpecDouble, "%.1e");
            break;
    }

#undef MAKE_RANGE

    if (g_type_is_a (pspec->value_type, G_TYPE_ENUM)) {
        GParamSpecEnum *spec = (GParamSpecEnum *) pspec;

        if (spec->enum_class->n_values > 0) {
            g_string_printf (range, "<table><tr><th>Enum name</th><th>Value</th>");

            for (guint i = 0; i < spec->enum_class->n_values; i++) {
                GEnumValue *v = &spec->enum_class->values[i];
                g_string_append_printf (range,
                                        "<tr><td><code>%s</code></td><td>%i</td></tr>",
                                        v->value_name, v->value);
            }

            g_string_append_printf (range, "</table>");
        }
    }

    if (range->len > 0)
        g_print ("<p>Possible values: %s</p>", range->str);

    if (default_value != NULL) {
        g_print ("<p>Default value: %s</p>", default_value);
        g_free (default_value);
    }

    g_string_free (range, TRUE);
}
Ejemplo n.º 17
0
/**
 * as_node_get_localized_unwrap_type_li:
 *
 * Denormalize AppData data where each <li> element is translated:
 *
 * |[
 * <description>
 *  <p>Hi</p>
 *  <p xml:lang="pl">Czesc</p>
 *  <ul>
 *   <li>First</li>
 *   <li xml:lang="pl">Pierwszy</li>
 *  </ul>
 * </description>
 * ]|
 **/
static gboolean
as_node_get_localized_unwrap_type_li (const AsNode *node,
				      GHashTable *hash,
				      GError **error)
{
	AsNode *tmp;
	AsNode *tmp_c;
	AsNodeData *data;
	AsNodeData *data_c;
	GString *str;

	for (tmp = node->children; tmp != NULL; tmp = tmp->next) {
		data = tmp->data;

		/* append to existing string, adding the locale if it's not
		 * already present */
		if (g_strcmp0 (data->name, "p") == 0) {
			str = as_node_denorm_get_str_for_lang (hash, data, TRUE);
			as_node_cdata_to_escaped (data);
			g_string_append_printf (str, "<p>%s</p>",
						data->cdata);

		/* loop on the children */
		} else if (g_strcmp0 (data->name, "ul") == 0 ||
			   g_strcmp0 (data->name, "ol") == 0) {
			as_node_denorm_add_to_langs (hash, data->name, TRUE);
			for (tmp_c = tmp->children; tmp_c != NULL; tmp_c = tmp_c->next) {
				data_c = tmp_c->data;

				/* handle new locales that have list
				 * translations but no paragraph translations */
				str = as_node_denorm_get_str_for_lang (hash,
								       data_c,
								       FALSE);
				if (str == NULL) {
					str = as_node_denorm_get_str_for_lang (hash,
									       data_c,
									       TRUE);
					g_string_append_printf (str, "<%s>",
								data->name);
				}
				if (g_strcmp0 (data_c->name, "li") == 0) {
					as_node_cdata_to_escaped (data_c);
					g_string_append_printf (str,
								"<li>%s</li>",
								data_c->cdata);
				} else {
					/* only <li> is valid in lists */
					g_set_error (error,
						     AS_NODE_ERROR,
						     AS_NODE_ERROR_INVALID_MARKUP,
						     "Tag %s in %s invalid",
						     data_c->name, data->name);
					return FALSE;
				}
			}
			as_node_denorm_add_to_langs (hash, data->name, FALSE);
		} else {
			/* only <p>, <ul> and <ol> is valid here */
			g_set_error (error,
				     AS_NODE_ERROR,
				     AS_NODE_ERROR_INVALID_MARKUP,
				     "Unknown tag '%s'",
				     data->name);
			return FALSE;
		}
	}
	return TRUE;
}
Ejemplo n.º 18
0
static void serialize_slide_config (GString       *str,
                                    PinPointPoint *point,
                                    PinPointPoint *reference,
                                    const char    *separator)
{
#define STRING(v,n) \
  if (point->v != reference->v) \
    g_string_append_printf (str, "%s[" n "%s]", separator, point->v)
#define INT(v,n) \
  if (point->v != reference->v) \
    g_string_append_printf (str, "%s[" n "%d]", separator, point->v)
#define FLOAT(v,n) \
  if (point->v != reference->v) \
    g_string_append_printf (str, "%s[" n "%f]", separator, point->v)

  STRING(stage_color, "stage-color=");
  STRING(bg, "");

  if (point->bg_scale != reference->bg_scale)
    {
      g_string_append (str, separator);
      switch (point->bg_scale)
        {
          case PP_BG_FILL:     g_string_append (str, "[fill]");     break;
          case PP_BG_FIT:      g_string_append (str, "[fit]");      break;
          case PP_BG_STRETCH:  g_string_append (str, "[stretch]");  break;
          case PP_BG_UNSCALED: g_string_append (str, "[unscaled]"); break;
        }
    }

  if (point->bg_position != reference->bg_position)
    {
      g_string_append(str, separator);
      switch (point->bg_position)
        {
          case CLUTTER_GRAVITY_NONE:
          case CLUTTER_GRAVITY_CENTER:
            break;
          case CLUTTER_GRAVITY_NORTH:
            g_string_append (str, "[bg-position=top]");break;
          case CLUTTER_GRAVITY_SOUTH:
            g_string_append (str, "[bg-position=bottom]");break;
          case CLUTTER_GRAVITY_WEST:
            g_string_append (str, "[bg-position=left]");break;
          case CLUTTER_GRAVITY_EAST:
            g_string_append (str, "[bg-position=right]");break;
          case CLUTTER_GRAVITY_NORTH_WEST:
            g_string_append (str, "[bg-position=top-left]");break;
          case CLUTTER_GRAVITY_NORTH_EAST:
            g_string_append (str, "[bg-position=top-right]");break;
          case CLUTTER_GRAVITY_SOUTH_WEST:
            g_string_append (str, "[bg-position=bottom-left]");break;
          case CLUTTER_GRAVITY_SOUTH_EAST:
            g_string_append (str, "[bg-position=bottom-right]");break;
        }
    }

  if (point->text_align != reference->text_align)
    {
      g_string_append (str, separator);
      switch (point->text_align)
        {
          case PP_TEXT_LEFT:  g_string_append (str, "[text-align=left]");break;
          case PP_TEXT_CENTER:g_string_append (str, "[text-align=center]");break;
          case PP_TEXT_RIGHT: g_string_append (str, "[text-align=right]");break;
        }
    }

  if (point->position != reference->position)
    {
      g_string_append (str, separator);
      switch (point->position)
        {
          case CLUTTER_GRAVITY_NONE:
            break;
          case CLUTTER_GRAVITY_CENTER:
            g_string_append (str, "[center]");break;
          case CLUTTER_GRAVITY_NORTH:
            g_string_append (str, "[top]");break;
          case CLUTTER_GRAVITY_SOUTH:
            g_string_append (str, "[bottom]");break;
          case CLUTTER_GRAVITY_WEST:
            g_string_append (str, "[left]");break;
          case CLUTTER_GRAVITY_EAST:
            g_string_append (str, "[right]");break;
          case CLUTTER_GRAVITY_NORTH_WEST:
            g_string_append (str, "[top-left]");break;
          case CLUTTER_GRAVITY_NORTH_EAST:
            g_string_append (str, "[top-right]");break;
          case CLUTTER_GRAVITY_SOUTH_WEST:
            g_string_append (str, "[bottom-left]");break;
          case CLUTTER_GRAVITY_SOUTH_EAST:
            g_string_append (str, "[bottom-right]");break;
        }
    }

  STRING(font,"font=");
  STRING(text_color,"text-color=");
  STRING(shading_color,"shading-color=");
  FLOAT(shading_opacity, "shading-opacity=");

  STRING(transition,"transition=");
  STRING(command,"command=");
  if (point->duration != 0.0)
    FLOAT(duration, "duration="); /* XXX: probably needs special treatment */

  INT(camera_framerate, "camera-framerate=");
  if (point->camera_resolution.width != reference->camera_resolution.width &&
      point->camera_resolution.height != reference->camera_resolution.height)
    {
        g_string_append_printf (str, "[camera-resolution=%dx%d]",
                                point->camera_resolution.width,
                                point->camera_resolution.height);
    }

  if (point->use_markup != reference->use_markup)
    {
      g_string_append (str, separator);
      if (point->use_markup)
        g_string_append (str, "[markup]");
      else
        g_string_append (str, "[no-markup]");
    }

#undef FLOAT
#undef INT
#undef STRING
}
Ejemplo n.º 19
0
void
mockart_do_entrance(const char *fname, ...)
{
    GList *sched_list;
    sched_entry_t *sched_entry;
    GList *mock_args;

    mockart_arg_t *mock_arg;
    va_list args;
    int i;
    char *bt_str;

    int int_arg;
    long long_arg;
    const char *str_arg;
    void *ptr_arg;

    GString *_fail_msg;

    if (entrance_schedule_table == NULL)
        return;

    /*
     * fail_msg != NULL means some entrance failures have already
     * occured.  In this case, do not overwrite fail_msg because I
     * want to focus on the first failure.
     */
    if (fail_msg != NULL) {
        return;
    }

    if (NULL == (sched_list = g_hash_table_lookup(entrance_schedule_table, fname))) {
        return;
    }

    __collect_backtrace();
    bt_str = mockart_bt_to_str();

    _fail_msg = g_string_new("");

    sched_entry = (sched_entry_t *) sched_list->data;
    sched_list = g_list_remove(sched_list, sched_entry);
    g_hash_table_insert(entrance_schedule_table, (char *) fname, sched_list);
    mock_args = sched_entry->mock_args;

    va_start(args, fname);

    for(i = 1;
        mock_args != NULL && _fail_msg->len == 0;
        mock_args = mock_args->next, i++)
    {
        mock_arg = (mockart_arg_t *) mock_args->data;
        switch(mock_arg->type) {
        case MOCK_ARG_SKIP: // no check
            va_arg(args, void *);
            break;
        case MOCK_ARG_INT:
            int_arg = va_arg(args, int);
            if (int_arg != mock_arg->u._int) {
                g_string_printf(_fail_msg, "Failure on %d-th argument of '%s': "
                                "expected <%d> but actually <%d>\n",
                                i, fname,
                                mock_arg->u._int,
                                int_arg);
            }
            break;
        case MOCK_ARG_LONG:
            long_arg = va_arg(args, long);
            if (mock_arg->u._long != long_arg) {
                g_string_printf(_fail_msg, "Failure on %d-th argument of '%s': "
                                "expected <%ld> but actually <%ld>\n",
                                i, fname,
                                mock_arg->u._long,
                                long_arg);
            }
            break;
        case MOCK_ARG_STR:
            str_arg = va_arg(args, const char *);
            if (strcmp(mock_arg->u._str, str_arg) != 0) {
                g_string_printf(_fail_msg, "Failure on %d-th argument of '%s': "
                                "expected <\"%s\"> but actually <\"%s\">\n",
                                i, fname,
                                mock_arg->u._str,
                                str_arg);
            }
            break;
        case MOCK_ARG_PTR:
            ptr_arg = va_arg(args, void *);
            if (mock_arg->u._ptr != ptr_arg) {
                g_string_printf(_fail_msg, "Failure on %d-th argument of '%s': "
                                "expected <%p> but actually <%p>\n",
                                i, fname,
                                mock_arg->u._ptr,
                                ptr_arg);
            }
            break;
        default:
            fprintf(stderr,
                    "%s: unimplemented type %d\n",
                    __func__,
                    mock_arg->type);
            exit(EXIT_FAILURE);
        }
    }

    va_end(args);

    if (_fail_msg->len > 0) {
        g_string_append_printf(_fail_msg,
                               "  Expected at %s:%d\n",
                               sched_entry->file, sched_entry->lineno);
        g_string_append(_fail_msg, bt_str);
        fail_msg = strdup(_fail_msg->str);
    }

    g_string_free(_fail_msg, TRUE);
    g_list_free(sched_entry->mock_args);
    free(sched_entry);
    free(bt_str);
}
Ejemplo n.º 20
0
static void
query_helper (const gchar *query_filename, const gchar *results_filename)
{
	GError *error = NULL;
	gchar *queries = NULL, *query;
	gchar *results = NULL;
	GString *test_results = NULL;

	g_file_get_contents (query_filename, &queries, NULL, &error);
	g_assert_no_error (error);

	g_file_get_contents (results_filename, &results, NULL, &error);
	g_assert_no_error (error);

	/* perform actual query */

	query = strtok (queries, "~");

	while (query) {
		TrackerDBCursor *cursor;

		cursor = tracker_data_query_sparql_cursor (query, &error);
		g_assert_no_error (error);

		/* compare results with reference output */

		if (!test_results) {
			test_results = g_string_new ("");
		} else {
			g_string_append (test_results, "~\n");
		}

		if (cursor) {
			gint col;

			while (tracker_db_cursor_iter_next (cursor, NULL, &error)) {
				for (col = 0; col < tracker_db_cursor_get_n_columns (cursor); col++) {
					const gchar *str;

					if (col > 0) {
						g_string_append (test_results, "\t");
					}

					str = tracker_db_cursor_get_string (cursor, col, NULL);
					if (str != NULL) {
						/* bound variable */
						g_string_append_printf (test_results, "\"%s\"", str);
					}
				}

				g_string_append (test_results, "\n");
			}

			g_object_unref (cursor);
		}

		query = strtok (NULL, "~");
	}

	if (strcmp (results, test_results->str)) {
		/* print result difference */
		gchar *quoted_results;
		gchar *command_line;
		gchar *quoted_command_line;
		gchar *shell;
		gchar *diff;

		quoted_results = g_shell_quote (test_results->str);
		command_line = g_strdup_printf ("echo -n %s | diff -u %s -", quoted_results, results_filename);
		quoted_command_line = g_shell_quote (command_line);
		shell = g_strdup_printf ("sh -c %s", quoted_command_line);
		g_spawn_command_line_sync (shell, &diff, NULL, NULL, &error);
		g_assert_no_error (error);

		g_error ("%s", diff);

		g_free (quoted_results);
		g_free (command_line);
		g_free (quoted_command_line);
		g_free (shell);
		g_free (diff);
	}

	g_string_free (test_results, TRUE);
	g_free (results);
	g_free (queries);
}
Ejemplo n.º 21
0
/**
 * xfce_dialog_show_help_with_version:
 * @parent    : (allow-none): transient parent of the dialog, or %NULL.
 * @component : (allow-none): name of the component opening the help page or %NULL. If the
 *              value is %NULL the target will be the main page of the
 *              documentation website.
 * @page      : (allow-none): subpage of the @component on the website or %NULL.
 * @offset    : (allow-none): anchor offset in @page or %NULL.
 * @version   : (allow-none): alternative version, or %NULL to use xfce_version_string().
 *
 * Asks the user to visit the online documentation. If confirmed, it will open
 * the webbrowser and redirect the user to the correct location.
 *
 * Appart from the @component, @page and @offset the following information
 * is also send to the server: user language and the xfce_version_string()
 * or @version if set.
 *
 * See also: xfce_dialog_show_help().
 *
 * Since: 4.12
 *
 */
void
xfce_dialog_show_help_with_version (GtkWindow   *parent,
                                    const gchar *component,
                                    const gchar *page,
                                    const gchar *offset,
                                    const gchar *version)
{
  GtkWidget   *dialog;
  const gchar *name;
  gchar       *primary;
  GString     *uri;
  gchar       *locale;
  GtkWidget   *message_box;
  GtkWidget   *button;
  XfceRc      *rc;
  gboolean     auto_online;
  GdkScreen   *screen;

  g_return_if_fail (parent == NULL || GTK_IS_WINDOW (parent));

  /* get the user's locale without encoding */
  locale = g_strdup (setlocale (LC_MESSAGES, NULL));
  if (G_LIKELY (locale != NULL))
    locale = g_strdelimit (locale, ".", '\0');
  else
    locale = g_strdup ("C");

  /* use desktop version if none is set */
  if (version == NULL)
    version = xfce_version_string ();

  /* build the redirect uri */
  uri = g_string_new (MANUAL_WEBSITE);
  g_string_append_printf (uri, "?version=%s&locale=%s", version, locale);
  g_free (locale);

  if (component != NULL)
    g_string_append_printf (uri, "&component=%s", component);
  if (page != NULL)
    g_string_append_printf (uri, "&page=%s", page);
  if (offset != NULL)
    g_string_append_printf (uri, "&offset=%s", offset);

  /* check if we should automatically go online */
  rc = xfce_rc_config_open (XFCE_RESOURCE_CONFIG, "xfce4/help.rc", TRUE);
  if (rc != NULL)
    {
      auto_online = xfce_rc_read_bool_entry (rc, "auto-online", FALSE);
      xfce_rc_close (rc);

      if (auto_online)
        {
          if (parent != NULL)
            screen = gtk_window_get_screen (GTK_WINDOW (parent));
          else
            screen = xfce_gdk_screen_get_active (NULL);

          xfce_dialog_show_help_uri (screen, parent, uri);
          g_string_free (uri, TRUE);

          return;
        }
    }

  /* try to get a translated name of the application */
  name = g_get_application_name ();
  if (g_strcmp0 (name, g_get_prgname ()) == 0)
    name = NULL;

  /* try to get a decent primary text */
  if (name != NULL)
    primary = g_strdup_printf (_("Do you want to read the %s manual online?"), name);
  else
    primary = g_strdup (_("Do you want to read the manual online?"));

  dialog = xfce_message_dialog_new (parent,
                                    _("Online Documentation"),
#if !GTK_CHECK_VERSION (3, 10, 0)
                                    GTK_STOCK_DIALOG_QUESTION,
#else
                                    "dialog-question",
#endif
                                    primary,
                                    _("You will be redirected to the documentation website "
                                      "where the help pages are maintained and translated."),
#if !GTK_CHECK_VERSION (3, 10, 0)
                                    GTK_STOCK_CANCEL,
#else
                                    "gtk-cancel",
#endif
                                    GTK_RESPONSE_NO,
                                    XFCE_BUTTON_TYPE_MIXED,
#if !GTK_CHECK_VERSION (3, 10, 0)
                                    GTK_STOCK_HELP,
#else
                                    "help-browser",
#endif
                                    _("_Read Online"),
                                    GTK_RESPONSE_YES,
                                    NULL);
  g_free (primary);


  message_box = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
  g_return_if_fail (GTK_IS_BOX (message_box));

  button = gtk_check_button_new_with_mnemonic (_("_Always go directly to the online documentation"));
  gtk_box_pack_end (GTK_BOX (message_box), button, FALSE, TRUE, 0);
#if GTK_CHECK_VERSION (3, 0, 0)
  g_object_set (G_OBJECT (button), "halign", GTK_ALIGN_END, "margin-start", 8, "margin-end", 8, NULL);
  gtk_widget_set_hexpand (button, TRUE);
#endif
  g_signal_connect (G_OBJECT (button), "toggled",
      G_CALLBACK (xfce_dialog_show_help_auto_toggled), NULL);
  gtk_widget_show (button);

  /* don't focus the checkbutton */
  gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_YES);
  button = gtk_dialog_get_widget_for_response (GTK_DIALOG (dialog), GTK_RESPONSE_YES);
  gtk_widget_grab_focus (button);

  /* show the dialog without locking the mainloop */
  gtk_window_set_modal (GTK_WINDOW (dialog), parent != NULL);
  g_signal_connect (G_OBJECT (dialog), "response",
      G_CALLBACK (xfce_dialog_show_help_response), uri);
  gtk_window_present (GTK_WINDOW (dialog));
}
Ejemplo n.º 22
0
static char
*get_all_applets (void)
{
	MateConfClient *client;
	GError *error;
	GSList *list, *l;
	char *key, *oafiid, *name;
	GHashTable *hash_table;
	GString *string;

	error = NULL;
	hash_table = g_hash_table_new (g_str_hash, g_str_equal);
	insert_oafiids (hash_table);

	string = g_string_new ("");

	client = mateconf_client_get_default ();

	mateconf_client_suggest_sync (client, NULL);
	
	list = mateconf_client_all_dirs (client,
		"/apps/panel/applets",
		&error);

	if (error)
	{
		g_warning ("Error: %s", error->message);
		g_error_free (error);
		error = NULL;
	}

	for (l = list; l; l = l->next)
	{
	    key = g_strdup_printf ("%s/matecomponent_iid", (gchar *)l->data);
		oafiid = mateconf_client_get_string (client, key, &error);
		if (error)
		{
			g_warning ("Error: %s", error->message);
			g_error_free (error);
			error = NULL;
		}
		g_free (key);
	
		if (oafiid)
		{
			name = g_hash_table_lookup (hash_table, oafiid);
			if (name)
			{
				mateconf_client_recursive_unset (client, l->data,
					MATECONF_UNSET_INCLUDING_SCHEMA_NAMES,
					&error);
				if (error)
				{
					g_warning ("Error: %s", error->message);
					g_error_free (error);
					error = NULL;
				}
				g_string_append_printf (string,
						"    • %s\n", name);
			}
			g_free (oafiid);
		}
		g_free (l->data);
	}

	g_slist_free (list);
	g_hash_table_destroy (hash_table);
	
	return g_string_free (string, FALSE);
}
Ejemplo n.º 23
0
gchar*
sim_event_get_alarm_insert_clause (SimDatabase *db_ossim,
                                   SimEvent   *event,
                                   gboolean    removable)
{
  gchar    time[TIMEBUF_SIZE];
  gchar   *timestamp=time;
  GString *query;
  GdaConnection *conn;
  gchar   *e_alarm_stats = NULL;

  g_return_val_if_fail (SIM_IS_EVENT (event), NULL);

  conn = sim_database_get_conn (db_ossim);

  if(event->time_str)
    timestamp=event->time_str;
  else
    strftime (timestamp, TIMEBUF_SIZE, "%F %T", gmtime ((time_t *) &event->time));

  guint efr =  event->priority * event->reliability * 2; //this is used for compliance. The "*2" is to take a percentage

  if (event->alarm_stats)
    e_alarm_stats = sim_str_escape (event->alarm_stats, conn, 0);

  ossim_debug ( "%s: risk_c:%f, risk_a:%f", __func__, event->risk_c, event->risk_a);

  query = g_string_new ("REPLACE INTO alarm "
                        "(event_id, backlog_id, corr_engine_ctx, timestamp, plugin_id, plugin_sid, "
                        "protocol, src_ip, dst_ip, src_port, dst_port, "
                        "risk, efr, similar, removable, stats) VALUES (");

  g_string_append_printf (query, "%s", sim_uuid_get_db_string (event->id));
  g_string_append_printf (query, ",%s", sim_uuid_get_db_string (event->backlog_id));
  g_string_append_printf (query, ",%s", sim_uuid_get_db_string (sim_engine_get_id (event->engine)));
  g_string_append_printf (query, ",'%s'", timestamp);
  g_string_append_printf (query, ",%d", event->plugin_id);
  g_string_append_printf (query, ",%d", event->plugin_sid);
  g_string_append_printf (query, ",%d", event->protocol);
  g_string_append_printf (query, ",%s", (event->src_ia) ? sim_inet_get_db_string (event->src_ia) : "NULL");
  g_string_append_printf (query, ",%s", (event->dst_ia) ? sim_inet_get_db_string (event->dst_ia) : "NULL");
  g_string_append_printf (query, ",%d", event->src_port);
  g_string_append_printf (query, ",%d", event->dst_port);
  g_string_append_printf (query, ",%d", ((gint)event->risk_a > (gint)event->risk_c) ? (gint)event->risk_a : (gint)event->risk_c);
  g_string_append_printf (query, ",%u", efr);
  g_string_append_printf (query, ",IF('%s'<>''", (event->groupalarmsha1 != NULL ? event->groupalarmsha1 : ""));
  g_string_append_printf (query, ",'%s'", (event->groupalarmsha1 != NULL ? event->groupalarmsha1 : ""));
  g_string_append_printf (query, ",SHA1('%s'))", sim_uuid_get_db_string (event->id));
  g_string_append_printf (query, ",%d", removable);
  g_string_append_printf (query, ",'%s')", e_alarm_stats ? e_alarm_stats : "");

  g_free (e_alarm_stats);

  return g_string_free (query, FALSE);
}
Ejemplo n.º 24
0
static gboolean
compute_and_append_legacy_archive_checksum (const char   *commit,
                                            GString      *buf,
                                            GCancellable *cancellable,
                                            GError      **error)
{
  gboolean ret = FALSE;
  const char *archive_argv[] = {"git", "archive", "--format=tar", commit, NULL};
  GSubprocess *gitarchive_proc = NULL;
  GInputStream *gitarchive_output = NULL;
  guint64 legacy_checksum_start;
  guint64 legacy_checksum_end;
  GChecksum *legacy_archive_sha256 = g_checksum_new (G_CHECKSUM_SHA256);
  gssize bytes_read;
  char readbuf[4096];
  char *gitversion = NULL;
  int estatus;
  char *nl;

  legacy_checksum_start = g_get_monotonic_time ();

  gitarchive_proc = g_subprocess_newv (archive_argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE, error);

  if (!gitarchive_proc)
    goto out;
          
  gitarchive_output = g_subprocess_get_stdout_pipe (gitarchive_proc);
          
  while ((bytes_read = g_input_stream_read (gitarchive_output, readbuf, sizeof (readbuf),
                                            cancellable, error)) > 0)
    g_checksum_update (legacy_archive_sha256, (guint8*)readbuf, bytes_read);
  if (bytes_read < 0)
    goto out;
  legacy_checksum_end = g_get_monotonic_time ();

  g_string_append_printf (buf, "# git-evtag comment: Computed legacy checksum in %0.1fs\n",
                          (double)(legacy_checksum_end - legacy_checksum_start) / (double) G_USEC_PER_SEC);

  g_string_append (buf, LEGACY_EVTAG_ARCHIVE_TAR);
  g_string_append_c (buf, ' ');
  g_string_append (buf, g_checksum_get_string (legacy_archive_sha256));
  g_string_append_c (buf, '\n');

  if (!g_spawn_command_line_sync ("git --version", &gitversion, NULL, &estatus, error))
    goto out;
  if (!g_spawn_check_exit_status (estatus, error))
    goto out;
          
  nl = strchr (gitversion, '\n');
  if (!nl)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "git --version returned invalid content without a newline");
      goto out;
    }

  *nl = '\0';
  g_strchomp (gitversion);

  g_string_append (buf, LEGACY_EVTAG_ARCHIVE_TAR_GITVERSION);
  g_string_append_c (buf, ' ');
  g_string_append (buf, gitversion);
  g_string_append_c (buf, '\n');

  ret = TRUE;
 out:
  return ret;
}
Ejemplo n.º 25
0
static void
log_json_parser_process_single (struct json_object *jso,
                                const gchar *prefix,
                                const gchar *obj_key,
                                LogMessage *msg)
{
  SBGString *key, *value;
  gboolean parsed = FALSE;

  key = sb_gstring_acquire ();
  value = sb_gstring_acquire ();

  switch (json_object_get_type (jso))
    {
    case json_type_boolean:
      parsed = TRUE;
      if (json_object_get_boolean (jso))
        g_string_assign (sb_gstring_string (value), "true");
      else
        g_string_assign (sb_gstring_string (value), "false");
      break;
    case json_type_double:
      parsed = TRUE;
      g_string_printf (sb_gstring_string (value), "%f",
                       json_object_get_double (jso));
      break;
    case json_type_int:
      parsed = TRUE;
      g_string_printf (sb_gstring_string (value), "%i",
                       json_object_get_int (jso));
      break;
    case json_type_string:
      parsed = TRUE;
      g_string_assign (sb_gstring_string (value),
                       json_object_get_string (jso));
      break;
    case json_type_object:
      if (prefix)
        g_string_assign (sb_gstring_string (key), prefix);
      g_string_append (sb_gstring_string (key), obj_key);
      g_string_append_c (sb_gstring_string (key), '.');
      log_json_parser_process_object (jso, sb_gstring_string (key)->str, msg);
      break;
    case json_type_array:
      {
        gint i, plen;

        g_string_assign (sb_gstring_string (key), obj_key);

        plen = sb_gstring_string (key)->len;

        for (i = 0; i < json_object_array_length (jso); i++)
          {
            g_string_truncate (sb_gstring_string (key), plen);
            g_string_append_printf (sb_gstring_string (key), "[%d]", i);
            log_json_parser_process_single (json_object_array_get_idx (jso, i),
                                            prefix,
                                            sb_gstring_string (key)->str, msg);
          }
        break;
      }
    case json_type_null:
      break;
    default:
      msg_error ("JSON parser encountered an unknown type, skipping",
                 evt_tag_str ("key", obj_key), NULL);
      break;
    }

  if (parsed)
    {
      if (prefix)
        {
          g_string_assign (sb_gstring_string (key), prefix);
          g_string_append (sb_gstring_string (key), obj_key);
          log_msg_set_value (msg,
                             log_msg_get_value_handle (sb_gstring_string (key)->str),
                             sb_gstring_string (value)->str,
                             sb_gstring_string (value)->len);
        }
      else
        log_msg_set_value (msg,
                           log_msg_get_value_handle (obj_key),
                           sb_gstring_string (value)->str,
                           sb_gstring_string (value)->len);
    }

  sb_gstring_release (key);
  sb_gstring_release (value);
}
Ejemplo n.º 26
0
static gboolean
git_evtag_builtin_sign (struct EvTag *self, int argc, char **argv, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  int r;
  const char *tagname;
  git_object *obj = NULL;
  git_oid specified_oid;
  GOptionContext *optcontext;
  guint64 elapsed_ns;
  char commit_oid_hexstr[GIT_OID_HEXSZ+1];

  optcontext = g_option_context_new ("TAGNAME - Create a new GPG signed tag");

  if (!option_context_parse (optcontext, sign_options, &argc, &argv,
                             cancellable, error))
    goto out;

  if (argc < 2)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "A TAGNAME argument is required");
      goto out;
    }
  else if (argc > 2)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Too many arguments");
      goto out;
    }
  tagname = argv[1];

  r = git_revparse_single (&obj, self->top_repo, "HEAD");
  if (!handle_libgit_ret (r, error))
    goto out;
  specified_oid = *git_object_id (obj);
  git_oid_fmt (commit_oid_hexstr, &specified_oid);
  commit_oid_hexstr[sizeof(commit_oid_hexstr)-1] = '\0';

  if (!validate_at_head (self, &specified_oid, error))
    goto out;

  if (!checksum_commit_recurse (self, &specified_oid, &elapsed_ns,
                                cancellable, error))
    goto out;

  if (opt_print_only)
    {
      char *stats = get_stats (self);
      g_print ("%s\n", stats);
      g_free (stats);
      g_print ("%s %s\n", EVTAG_SHA512, g_checksum_get_string (self->checksum));
    }
  else
    {
      const char *editor;
      int tmpfd;
      char *temppath;
      char *editor_child_argv[] = { NULL, NULL, NULL };
      GPtrArray *gittag_child_argv = g_ptr_array_new ();
      GString *buf = g_string_new ("\n\n");
      gboolean have_evtag;

      tmpfd = g_file_open_tmp ("git-evtag-XXXXXX.md", &temppath, error);
      if (tmpfd < 0)
        goto out;
      (void) close (tmpfd);

      g_string_append_printf (buf, "# git-evtag comment: Computed checksum in %0.1fs\n",
                              (double)(elapsed_ns) / (double) G_USEC_PER_SEC);

      {
        char *stats = get_stats (self);
        g_string_append (buf, stats);
        g_string_append_c (buf, '\n');
        g_free (stats);
      }
      g_string_append (buf, EVTAG_SHA512);
      g_string_append_c (buf, ' ');
      g_string_append (buf, g_checksum_get_string (self->checksum));
      g_string_append_c (buf, '\n');

      if (opt_with_legacy_archive_tag)
        {
          if (!compute_and_append_legacy_archive_checksum (commit_oid_hexstr, buf,
                                                           cancellable, error))
            goto out;
        }
      
      if (!g_file_set_contents (temppath, buf->str, -1, error))
        goto out;
      g_string_free (buf, TRUE);

      editor = getenv ("EDITOR");
      if (!editor)
        editor = "vi";

      editor_child_argv[0] = (char*)editor;
      editor_child_argv[1] = (char*)temppath;
      if (!spawn_sync_require_success (editor_child_argv, 
                                       G_SPAWN_SEARCH_PATH | G_SPAWN_CHILD_INHERITS_STDIN,
                                       error))
        goto out;

      if (!check_file_has_evtag (temppath, &have_evtag, error))
        goto out;

      if (!have_evtag)
        {
          g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                               "Aborting tag due to deleted Git-EVTag line"); 
          goto out;
        }
      
      g_ptr_array_add (gittag_child_argv, "git");
      g_ptr_array_add (gittag_child_argv, "tag");
      if (!opt_no_signature)
        g_ptr_array_add (gittag_child_argv, "-s");
      if (opt_keyid)
        {
          g_ptr_array_add (gittag_child_argv, "--local-user");
          g_ptr_array_add (gittag_child_argv, opt_keyid);
        }
      g_ptr_array_add (gittag_child_argv, "-F");
      g_ptr_array_add (gittag_child_argv, temppath);
      g_ptr_array_add (gittag_child_argv, (char*)tagname);
      g_ptr_array_add (gittag_child_argv, (char*)commit_oid_hexstr);
      g_ptr_array_add (gittag_child_argv, NULL);
      if (!spawn_sync_require_success ((char**)gittag_child_argv->pdata,
                                       G_SPAWN_SEARCH_PATH,
                                       error))
        {
          g_printerr ("Saved tag message in: %s\n", temppath);
          goto out;
        }
      (void) unlink (temppath);
      g_ptr_array_free (gittag_child_argv, TRUE);
    }

  ret = TRUE;
 out:
  return ret;
}
Ejemplo n.º 27
0
/* export_node_tree -- given a tree, export as specified format */
char * export_node_tree(node *list, int format, unsigned long extensions) {
	char *output;
	GString *out = g_string_new("");
	scratch_pad *scratch = mk_scratch_pad(extensions);
	scratch->result_tree = list;  /* Pointer to result tree to use later */

#ifdef DEBUG_ON
	fprintf(stderr, "export_node_tree\n");
#endif

#ifdef DEBUG_ON
	fprintf(stderr, "extract_references\n");
#endif
	/* Parse for link, images, etc reference definitions */
	if ((format != OPML_FORMAT) &&
		(format != CRITIC_ACCEPT_FORMAT) &&
		(format != CRITIC_REJECT_FORMAT) &&
		(format != CRITIC_HTML_HIGHLIGHT_FORMAT))
			extract_references(list, scratch);
	
	/* Change our desired format based on metadata */
	if (format == LATEX_FORMAT)
		format = find_latex_mode(format, list);
	
	switch (format) {
		case TEXT_FORMAT:
			print_text_node_tree(out, list, scratch);
			break;
		case HTML_FORMAT:
			if (scratch->extensions & EXT_COMPLETE) {
			    g_string_append_printf(out,
				"<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\"/>\n");
			}
#ifdef DEBUG_ON
	fprintf(stderr, "print_html output\n");
#endif
			print_html_node_tree(out, list, scratch);
#ifdef DEBUG_ON
	fprintf(stderr, "print html endnotes\n");
#endif
			print_html_endnotes(out, scratch);
#ifdef DEBUG_ON
	fprintf(stderr, "finished printing html endnotes\n");
#endif
			if (scratch->extensions & EXT_COMPLETE) {
				pad(out,2, scratch);
				g_string_append_printf(out, "</body>\n</html>");
			}
#ifdef DEBUG_ON
	fprintf(stderr, "closed HTML document\n");
#endif
			break;
		case LATEX_FORMAT:
			print_latex_node_tree(out, list, scratch);
			break;
		case MEMOIR_FORMAT:
			print_memoir_node_tree(out, list, scratch);
			break;
		case BEAMER_FORMAT:
			print_beamer_node_tree(out, list, scratch);
			break;
		case LYX_FORMAT:
			perform_lyx_output(out,list,scratch);
			break;
		case OPML_FORMAT:
#ifdef DEBUG_ON
	fprintf(stderr, "export OPML\n");
#endif
			begin_opml_output(out, list, scratch);
			print_opml_node_tree(out, list, scratch);
			end_opml_output(out, list, scratch);
			break;
		case ODF_FORMAT:
#ifdef DEBUG_ON
	fprintf(stderr, "export ODF\n");
#endif
			begin_odf_output(out, list, scratch);
			print_odf_node_tree(out, list, scratch);
			end_odf_output(out, list, scratch);
			break;
		case RTF_FORMAT:
#ifdef DEBUG_ON
	fprintf(stderr, "export RTF\n");
#endif
			if (!(scratch->extensions & EXT_SNIPPET))
				begin_rtf_output(out, list, scratch);
			print_rtf_node_tree(out, list, scratch);
			if (!(scratch->extensions & EXT_SNIPPET))
				end_rtf_output(out, list, scratch);
			break;
		case CRITIC_ACCEPT_FORMAT:
			print_critic_accept_node_tree(out, list, scratch);
			break;
		case CRITIC_REJECT_FORMAT:
			print_critic_reject_node_tree(out, list, scratch);
			break;
		case CRITIC_HTML_HIGHLIGHT_FORMAT:
			print_critic_html_highlight_node_tree(out, list, scratch);
			break;
		default:
			fprintf(stderr, "Unknown export format = %d\n",format);
			exit(EXIT_FAILURE);
	}
	
	output = out->str;
	g_string_free(out, false);
	free_scratch_pad(scratch);

#ifdef DEBUG_ON
	fprintf(stderr, "finish export_node_tree\n");
#endif
	return output;
}
Ejemplo n.º 28
0
/**
 * General feed source parsing function. Parses the passed feed source
 * and tries to determine the source type. 
 *
 * @param ctxt		feed parsing context
 *
 * @returns FALSE if auto discovery is indicated, 
 *          TRUE if feed type was recognized and parsing was successful
 */
gboolean
feed_parse (feedParserCtxtPtr ctxt)
{
	xmlNodePtr	cur;
	gboolean	success = FALSE;

	debug_enter("feed_parse");

	g_assert(NULL == ctxt->items);
	
	ctxt->failed = TRUE;	/* reset on success ... */

	if(ctxt->feed->parseErrors)
		g_string_truncate(ctxt->feed->parseErrors, 0);
	else
		ctxt->feed->parseErrors = g_string_new(NULL);

	/* try to parse buffer with XML and to create a DOM tree */	
	do {
		if(NULL == xml_parse_feed (ctxt)) {
			g_string_append_printf (ctxt->feed->parseErrors, _("XML error while reading feed! Feed \"%s\" could not be loaded!"), subscription_get_source (ctxt->subscription));
			break;
		}
		
		if(NULL == (cur = xmlDocGetRootElement(ctxt->doc))) {
			g_string_append(ctxt->feed->parseErrors, _("Empty document!"));
			break;
		}
		
		while(cur && xmlIsBlankNode(cur)) {
			cur = cur->next;
		}
		
		if(!cur)
			break;
				
		if(!cur->name) {
			g_string_append(ctxt->feed->parseErrors, _("Invalid XML!"));
			break;
		}

		/* determine the syndication format and start parser */
		GSList *handlerIter = feed_parsers_get_list ();
		while(handlerIter) {
			feedHandlerPtr handler = (feedHandlerPtr)(handlerIter->data);
			if(handler && handler->checkFormat && (*(handler->checkFormat))(ctxt->doc, cur)) {
				/* free old temp. parsing data, don't free right after parsing because
				   it can be used until the last feed request is finished, move me 
				   to the place where the last request in list otherRequests is 
				   finished :-) */
				g_hash_table_destroy(ctxt->tmpdata);
				ctxt->tmpdata = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, g_free);
				
				/* we always drop old metadata */
				metadata_list_free(ctxt->subscription->metadata);
				ctxt->subscription->metadata = NULL;
				ctxt->failed = FALSE;

				ctxt->feed->fhp = handler;
				(*(handler->feedParser))(ctxt, cur);		/* parse it */

				break;
			}
			handlerIter = handlerIter->next;
		}
	} while(0);
	
	/* if the given URI isn't valid we need to start auto discovery */
	if(ctxt->failed)
		feed_parser_auto_discover (ctxt);

	if(ctxt->failed) {
		/* Autodiscovery failed */
		/* test if we have a HTML page */
		if((strstr(ctxt->data, "<html>") || strstr(ctxt->data, "<HTML>") ||
		    strstr(ctxt->data, "<html ") || strstr(ctxt->data, "<HTML "))) {
			debug0(DEBUG_UPDATE, "HTML document detected!");
			g_string_append(ctxt->feed->parseErrors, _("Source points to HTML document."));
		} else {
			debug0(DEBUG_UPDATE, "neither a known feed type nor a HTML document!");
			g_string_append(ctxt->feed->parseErrors, _("Could not determine the feed type."));
		}
	} else {
		debug1(DEBUG_UPDATE, "discovered feed format: %s", feed_type_fhp_to_str(ctxt->feed->fhp));
		success = TRUE;
	}
	
	if(ctxt->doc) {
		xmlFreeDoc(ctxt->doc);
		ctxt->doc = NULL;
	}
		
	debug_exit("feed_parse");
	
	return success;
}
Ejemplo n.º 29
0
Archivo: move.c Proyecto: bpa/cube
GString *g_string_new_from_move(struct move *m) {
	GString *str = g_string_new("Setup: ");
	g_string_append_printf(str, "%s\nSolutions:", m->setup);
	g_slist_foreach(m->solutions, g_string_add_solution, str);
	return str;
}
Ejemplo n.º 30
0
static CoglBool
dump_layer_cb (CoglNode *node, void *user_data)
{
  CoglPipelineLayer *layer = COGL_PIPELINE_LAYER (node);
  PrintDebugState *state = user_data;
  int layer_id = *state->node_id_ptr;
  PrintDebugState state_out;
  GString *changes_label;
  CoglBool changes = FALSE;

  if (state->parent_id >= 0)
    g_string_append_printf (state->graph, "%*slayer%p -> layer%p;\n",
                            state->indent, "",
                            layer->_parent.parent,
                            layer);

  g_string_append_printf (state->graph,
                          "%*slayer%p [label=\"layer=0x%p\\n"
                          "ref count=%d\" "
                          "color=\"blue\"];\n",
                          state->indent, "",
                          layer,
                          layer,
                          COGL_OBJECT (layer)->ref_count);

  changes_label = g_string_new ("");
  g_string_append_printf (changes_label,
                          "%*slayer%p -> layer_state%d [weight=100];\n"
                          "%*slayer_state%d [shape=box label=\"",
                          state->indent, "",
                          layer,
                          layer_id,
                          state->indent, "",
                          layer_id);

  if (layer->differences & COGL_PIPELINE_LAYER_STATE_UNIT)
    {
      changes = TRUE;
      g_string_append_printf (changes_label,
                              "\\lunit=%u\\n",
                              layer->unit_index);
    }

  if (layer->differences & COGL_PIPELINE_LAYER_STATE_TEXTURE_DATA)
    {
      changes = TRUE;
      g_string_append_printf (changes_label,
                              "\\ltexture=%p\\n",
                              layer->texture);
    }

  if (changes)
    {
      g_string_append_printf (changes_label, "\"];\n");
      g_string_append (state->graph, changes_label->str);
      g_string_free (changes_label, TRUE);
    }

  state_out.parent_id = layer_id;

  state_out.node_id_ptr = state->node_id_ptr;
  (*state_out.node_id_ptr)++;

  state_out.graph = state->graph;
  state_out.indent = state->indent + 2;

  _cogl_pipeline_node_foreach_child (COGL_NODE (layer),
                                     dump_layer_cb,
                                     &state_out);

  return TRUE;
}