gegl-xml.c 36.6 KB
Newer Older
Øyvind Kolås's avatar
Øyvind Kolås committed
1 2 3 4 5
/* This file is part of GEGL
 *
 * GEGL is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
6
 * version 3 of the License, or (at your option) any later version.
Øyvind Kolås's avatar
Øyvind Kolås committed
7 8 9 10 11 12 13
 *
 * GEGL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
14
 * License along with GEGL; if not, see <https://www.gnu.org/licenses/>.
Øyvind Kolås's avatar
Øyvind Kolås committed
15 16 17
 *
 * Copyright 2006 Øyvind Kolås
 */
18
#include "config.h"
Øyvind Kolås's avatar
Øyvind Kolås committed
19 20 21 22

#include <glib.h>
#include <glib-object.h>
#include <stdlib.h>
23
#include <stdio.h>
Øyvind Kolås's avatar
Øyvind Kolås committed
24
#include <string.h>
25
#include <limits.h>
26

27
#include "gegl.h"
28
#include "property-types/gegl-paramspecs.h"
29
#include "gegl-instrument.h"
30
#include "gegl-xml.h"
31
#include "gegl-audio-fragment.h"
Øyvind Kolås's avatar
Øyvind Kolås committed
32

33
#ifdef G_OS_WIN32
34
#define realpath(a, b)    _fullpath (b, a, _MAX_PATH)
35 36
#endif

Øyvind Kolås's avatar
Øyvind Kolås committed
37 38
typedef struct _ParseData ParseData;

39 40 41
enum
{
  STATE_NONE = 0,
Øyvind Kolås's avatar
Øyvind Kolås committed
42
  STATE_TREE_NORMAL,
43
  STATE_TREE_FIRST_CHILD
Øyvind Kolås's avatar
Øyvind Kolås committed
44 45
};

46

47 48 49 50 51 52 53
struct _ParseData
{
  gint         state;
  const gchar *path_root;
  GeglNode    *gegl;
  gchar       *param;/*< the param we are setting (NULL when not in <param></param>) */
  GeglNode    *iter; /*< the iterator we're either connecting to input|aux of
Øyvind Kolås's avatar
Øyvind Kolås committed
54
                         depending on context */
55
  GList       *parent;/*< a stack of parents, as we are recursing into aux
Øyvind Kolås's avatar
Øyvind Kolås committed
56
                         branches */
57
  GeglCurve   *curve;/*< the curve whose points we are parsing */
Øyvind Kolås's avatar
Øyvind Kolås committed
58

59 60
  GHashTable  *ids;
  GList       *refs;
Øyvind Kolås's avatar
Øyvind Kolås committed
61 62
};

63 64 65 66

/* Search a paired attribute name/value arrays for an entry with a specific
 * name, return the value or null if not found.
 */
67 68 69 70
static const gchar *
name2val (const gchar **attribute_names,
          const gchar **attribute_values,
          const gchar  *name)
Øyvind Kolås's avatar
Øyvind Kolås committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84
{
  while (*attribute_names)
    {
      if (!strcmp (*attribute_names, name))
        {
          return *attribute_values;
        }

      attribute_names++;
      attribute_values++;
    }
  return NULL;
}

85 86 87 88 89
static void 
param_set (ParseData   *pd,
           GeglNode    *new,
           const gchar *param_name,
           const gchar *param_value)
90 91 92 93 94
{
  if (!strcmp (param_name, "name"))
    {
      g_object_set (new, param_name, param_value, NULL);
    }
95 96 97 98 99
  else if (!strcmp (param_name, "opi"))
    {
      /* should check if it is compatible with runtime version of op..
       */
    }
100 101 102 103 104 105 106 107 108 109 110 111 112
  else if (!strcmp (param_name, "id"))
    {
      g_hash_table_insert (pd->ids, g_strdup (param_value), new);
    }
  else if (!strcmp (param_name, "ref"))
    {
      pd->refs = g_list_append (pd->refs, new);
      goto set_clone_prop_as_well;
    }
  else if (strcmp (param_name, "operation") &&
           strcmp (param_name, "type"))
    {
      GParamSpec    *paramspec;
113
set_clone_prop_as_well:
114

115
      paramspec = gegl_node_find_property (new, param_name);
116 117 118

      if (!paramspec)
        {
119
          g_warning ("property %s not found for %s",
120
                     param_name, gegl_node_get_operation (new));
121 122
        }
      else if (g_type_is_a (G_PARAM_SPEC_TYPE (paramspec),
123
                            GEGL_TYPE_PARAM_FILE_PATH))
124
        {
125
          gchar *buf;
126 127 128 129 130 131 132

          if (g_path_is_absolute (param_value))
            {
              gegl_node_set (new, param_name, param_value, NULL);
            }
          else
            {
133 134 135
              gchar * absolute_path;
              if (pd->path_root)
                {
136
                  buf = g_strdup_printf ("%s/%s", pd->path_root, param_value);
137 138 139
                }
              else
                {
140
                  buf = g_strdup_printf ("./%s", param_value);
141 142
                }

143
              absolute_path = realpath (buf, NULL);
144
              g_free (buf);
145 146 147
              if (absolute_path)
                {
                  gegl_node_set (new, param_name, absolute_path, NULL);
148
                  free (absolute_path);
149 150 151
                }
              else
                {
152 153 154
                  g_warning ("Unable to obtain absolute path for parameter %s\n", param_name);
                  // Attempt to set raw value, useful for '-' meaning stdin
                  gegl_node_set (new, param_name, param_value, NULL);
155
                }
156 157 158 159 160 161
            }
        }
      else if (paramspec->value_type == G_TYPE_INT)
        {
          gegl_node_set (new, param_name, atoi (param_value), NULL);
        }
162 163 164 165
      else if (paramspec->value_type == G_TYPE_UINT)
        {
          gegl_node_set (new, param_name, (guint) strtoul (param_value, NULL, 10), NULL);
        }
166 167 168
      else if (paramspec->value_type == G_TYPE_FLOAT ||
               paramspec->value_type == G_TYPE_DOUBLE)
        {
169
          gegl_node_set (new, param_name, g_ascii_strtod (param_value, NULL), NULL);
170 171 172 173 174 175 176 177 178 179 180 181 182 183
        }
      else if (paramspec->value_type == G_TYPE_STRING)
        {
          gegl_node_set (new, param_name, param_value, NULL);
        }
      else if (paramspec->value_type == G_TYPE_BOOLEAN)
        {
          if (!strcmp (param_value, "true") ||
              !strcmp (param_value, "TRUE") ||
              !strcmp (param_value, "YES") ||
              !strcmp (param_value, "yes") ||
              !strcmp (param_value, "y") ||
              !strcmp (param_value, "Y") ||
              !strcmp (param_value, "1") ||
184
              !strcmp (param_value, "on"))
185 186 187 188 189 190 191 192
            {
              gegl_node_set (new, param_name, TRUE, NULL);
            }
          else
            {
              gegl_node_set (new, param_name, FALSE, NULL);
            }
        }
193 194 195 196
      else if (g_type_is_a (paramspec->value_type, G_TYPE_ENUM))
        {
          GEnumClass *eclass = g_type_class_peek (paramspec->value_type);
          GEnumValue *evalue = g_enum_get_value_by_nick (eclass, param_value);
197 198 199 200 201 202
          if (evalue)
            {
              gegl_node_set (new, param_name, evalue->value, NULL);
            }
          else
            {
203 204 205 206 207
              /* warn, but try to get a valid nick out of the old-style
               * value name
               */
              gchar *nick;
              gchar *c;
208 209 210 211
              g_printerr ("gegl-xml (param_set %s): enum %s has no value '%s'\n",
                          paramspec->name,
                          g_type_name (paramspec->value_type),
                          param_value);
212 213 214 215 216 217 218 219 220 221 222
              nick = g_strdup (param_value);
              for (c = nick; *c; c++)
                {
                  *c = g_ascii_tolower (*c);
                  if (*c == ' ')
                    *c = '-';
                }
              evalue = g_enum_get_value_by_nick (eclass, nick);
              if (evalue)
                gegl_node_set (new, param_name, evalue->value, NULL);
              g_free (nick);
223
            }
224
        }
225 226 227 228 229 230 231 232 233 234
      else if (paramspec->value_type == GEGL_TYPE_COLOR)
        {
          GeglColor *color = g_object_new (GEGL_TYPE_COLOR,
                                           "string", param_value,
                                           NULL);

          gegl_node_set (new, param_name, color, NULL);

          g_object_unref (color);
        }
235 236
      else if (paramspec->value_type == GEGL_TYPE_CURVE)
        {
237 238 239
          if (pd->curve)
            {
              gegl_node_set (new, param_name, pd->curve, NULL);
Debarshi Ray's avatar
Debarshi Ray committed
240
              g_clear_object (&pd->curve);
241 242
            }
        }
243
      else if (paramspec->value_type == GEGL_TYPE_PATH)
244
        {
245 246
          GeglPath *path = gegl_path_new ();
          gegl_path_parse_string (path, param_value);
247 248
          gegl_node_set (new, param_name, path, NULL);
        }
Daniel Sabo's avatar
Daniel Sabo committed
249 250 251 252 253 254 255 256 257 258
      else if (paramspec->value_type == G_TYPE_POINTER &&
               GEGL_IS_PARAM_SPEC_FORMAT (paramspec))
        {
          const Babl *format = NULL;

          if (strlen (param_value))
            format = babl_format (param_value);

          gegl_node_set (new, param_name, format, NULL);
        }
259 260
      else
        {
261
          g_warning ("operation desired unknown paramspec type for %s",
262 263 264 265 266
                     param_name);
        }
    }
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

/* Check that the attributes for ELEMENT include an attribute of name NAME,
 * and store it in the variable of the same name. Else report an error.
 *
 * eg:  { collect_attribute (value, 'key'); }
 */
#define collect_attribute(NAME, ELEMENT)                                \
{                                                                       \
  const gchar *__value = name2val (a, v, (G_STRINGIFY (NAME)));         \
  if (!__value)                                                         \
    {                                                                   \
      *error = g_error_new (G_MARKUP_ERROR,                             \
                            G_MARKUP_ERROR_MISSING_ATTRIBUTE,           \
                            "Expected attribute '%s' in element '%s'",  \
                            (G_STRINGIFY (NAME)),                       \
                            (ELEMENT));                                 \
      return;                                                           \
    }                                                                   \
  else                                                                  \
    {                                                                   \
      (NAME) = __value;                                                 \
    }                                                                   \
}

291 292 293 294 295 296 297
static void 
start_element (GMarkupParseContext *context,
               const gchar         *element_name,
               const gchar        **attribute_names,
               const gchar        **attribute_values,
               gpointer             user_data,
               GError             **error)
Øyvind Kolås's avatar
Øyvind Kolås committed
298
{
299 300 301
  const gchar **a  = attribute_names;
  const gchar **v  = attribute_values;
  ParseData    *pd = user_data;
Øyvind Kolås's avatar
Øyvind Kolås committed
302

303
  if (!strcmp (element_name, "gegl") ||
304
      !strcmp (element_name, "image"))
Øyvind Kolås's avatar
Øyvind Kolås committed
305
    {
306
      GeglNode *new = g_object_new (GEGL_TYPE_NODE, "operation", "gegl:nop", NULL);
Øyvind Kolås's avatar
Øyvind Kolås committed
307 308
      if (pd->gegl == NULL)
        {
309
          pd->gegl = new;
Øyvind Kolås's avatar
Øyvind Kolås committed
310 311 312 313
        }
      else
        {
        }
314

315
      pd->state  = STATE_TREE_NORMAL;
Øyvind Kolås's avatar
Øyvind Kolås committed
316
      pd->parent = g_list_prepend (pd->parent, new);
317 318 319 320 321 322 323 324

      if (pd->iter)
	{
	  gegl_node_get_output_proxy (pd->iter, "output");
	  gegl_node_connect_from (pd->iter, "input", new, "output");
	}

      pd->iter = gegl_node_get_output_proxy (new, "output");
Øyvind Kolås's avatar
Øyvind Kolås committed
325
    }
326 327 328 329
  else if (!strcmp (element_name, "graph"))
    {
      /*NYI*/
    }
330 331 332 333 334 335
  else if (!strcmp (element_name, "params"))
    {
      /*g_warning ("go a param set");*/
    }
  else if (!strcmp (element_name, "param"))
    {
336
      const gchar *name;
337 338
      if (pd->param != NULL)
        g_warning ("eek, haven't cleared previous param");
339 340 341

      collect_attribute (name, "param");
      pd->param = g_strdup (name);
342
    }
343 344
  else if (!strcmp (element_name, "curve"))
    {
345
      const gchar *ymin, *ymax;
346
      if (pd->curve != NULL)
347
        g_warning ("we haven't cleared previous curve");
348 349 350 351 352

      collect_attribute (ymin, "curve");
      collect_attribute (ymax, "curve");

      pd->curve = gegl_curve_new (g_ascii_strtod (ymin, NULL),
353
                                  g_ascii_strtod (ymax, NULL));
354 355 356 357
    }
  else if (!strcmp (element_name, "curve-point"))
    {
      if (!pd->curve)
358
        g_warning ("curve not instantiated");
359 360
      else
        {
361 362 363
          const gchar *x, *y;
          collect_attribute (x, "curve-point");
          collect_attribute (y, "curve-point");
364

365 366 367 368
          gegl_curve_add_point (pd->curve,
                                g_ascii_strtod (x, NULL),
                                g_ascii_strtod (y, NULL));
        }
369
    }
370 371 372 373 374 375
  else if (!strcmp (element_name, "link") ||
           !strcmp (element_name, "links") ||
           !strcmp (element_name, "stack") ||
           !strcmp (element_name, "launcher") ||
           !strcmp (element_name, "launchers") ||
           !strcmp (element_name, "source") ||
376 377
           !strcmp (element_name, "destination"))
    {
378
      /* ignore */
379
    }
380
  else
Øyvind Kolås's avatar
Øyvind Kolås committed
381
    {
382 383
      GeglNode *new;

384 385 386 387 388 389
      if (!strcmp (element_name, "clone"))
        {
          new = gegl_node_new_child (pd->gegl,
                                     "operation", "gegl:clone",
                                     NULL);
        }
390 391 392 393 394 395
      else if (!strcmp (element_name, "layer"))
        {
          new = gegl_node_new_child (pd->gegl,
                                     "operation", "gegl:layer",
                                     NULL);
        }
396
      else if (!strcmp (element_name, "node"))
397
        {
398 399 400
          const gchar *operation;
          collect_attribute (operation, "node");
          new = gegl_node_new_child (pd->gegl, "operation", operation, NULL);
401
        }
402 403
      else if (!strcmp (element_name, "filter"))
        {
404 405 406
          const gchar *type;
          collect_attribute (type, "filter");
          new = gegl_node_new_child (pd->gegl, "operation", type, NULL);
407
        }
408 409
      else
        {
410
          new = gegl_node_new_child (pd->gegl,
411 412
                                     "operation", element_name,
                                     NULL);
413
        }
414 415 416 417 418 419 420 421 422 423

      /* Could not instance an appropriate node */
      if (!new)
        {
          *error = g_error_new (G_MARKUP_ERROR,
                                G_MARKUP_ERROR_UNKNOWN_ELEMENT,
                                "Could not instantiate operation '%s'",
                                element_name);
          return;
        }
Øyvind Kolås's avatar
Øyvind Kolås committed
424 425 426

      while (*a)
        {
427
          param_set (pd, new, *a, *v);
428 429 430
          a++;
          v++;
        }
Øyvind Kolås's avatar
Øyvind Kolås committed
431

Øyvind Kolås's avatar
Øyvind Kolås committed
432
      if (pd->state == STATE_TREE_FIRST_CHILD)
Øyvind Kolås's avatar
Øyvind Kolås committed
433
        {
434
          gegl_node_connect_from (pd->iter, "aux", new, "output");
Øyvind Kolås's avatar
Øyvind Kolås committed
435 436 437
        }
      else
        {
438
          if (pd->iter && gegl_node_has_pad(new, "output"))
439 440 441
	    {
	      gegl_node_connect_from (pd->iter, "input", new, "output");
	    }
Øyvind Kolås's avatar
Øyvind Kolås committed
442 443
        }
      pd->parent = g_list_prepend (pd->parent, new);
444 445
      pd->state  = STATE_TREE_FIRST_CHILD;
      pd->iter   = new;
Øyvind Kolås's avatar
Øyvind Kolås committed
446 447 448
    }
}

449 450 451 452 453 454
static void 
text (GMarkupParseContext *context,
      const gchar         *text,
      gsize                text_len,
      gpointer             user_data,
      GError             **error)
455
{
456
  ParseData *pd = user_data;
457

458
  if (pd->param && pd->iter && !pd->curve)
459 460 461 462 463
    {
      param_set (pd, pd->iter, pd->param, text);
    }
}

Øyvind Kolås's avatar
Øyvind Kolås committed
464
/* Called for close tags </foo> */
465 466 467 468 469
static void 
end_element (GMarkupParseContext *context,
             const gchar         *element_name,
             gpointer             user_data,
             GError             **error)
Øyvind Kolås's avatar
Øyvind Kolås committed
470
{
471
  ParseData *pd = user_data;
Øyvind Kolås's avatar
Øyvind Kolås committed
472

473
  if (!strcmp (element_name, "gegl") ||
474
      !strcmp (element_name, "image"))
Øyvind Kolås's avatar
Øyvind Kolås committed
475 476 477
    {
      /*ignored*/
    }
478 479
  else if (!strcmp (element_name, "tree") ||
           !strcmp (element_name, "layers"))
Øyvind Kolås's avatar
Øyvind Kolås committed
480
    {
481
      if (gegl_node_get_producer (pd->iter, "input", NULL))
Øyvind Kolås's avatar
Øyvind Kolås committed
482
        {
483
          gegl_node_connect_from (pd->iter, "input",
484 485 486 487
                                  gegl_node_get_input_proxy (GEGL_NODE (pd->parent->data), "input"),
                                  "output");
          pd->iter = gegl_node_get_input_proxy (GEGL_NODE (pd->parent->data),
                                                "input");
Øyvind Kolås's avatar
Øyvind Kolås committed
488 489 490 491 492
        }
      else
        {
          pd->iter = NULL;
        }
493
      pd->parent = g_list_delete_link (pd->parent, pd->parent);
494
      pd->state  = STATE_TREE_NORMAL;
Øyvind Kolås's avatar
Øyvind Kolås committed
495
    }
496 497 498 499
  else if (!strcmp (element_name, "graph"))
    {
      /*NYI*/
    }
500 501
  else if (!strcmp (element_name, "param"))
    {
Debarshi Ray's avatar
Debarshi Ray committed
502
      g_clear_pointer (&pd->param, g_free);
503
    }
504 505 506 507 508
  else if (!strcmp (element_name, "curve"))
    {
      g_assert (pd->param && pd->iter);
      param_set (pd, pd->iter, pd->param, NULL);
    }
509 510 511 512 513
  else if (!strcmp (element_name, "link") ||
           !strcmp (element_name, "links") ||
           !strcmp (element_name, "launcher") ||
           !strcmp (element_name, "launchers") ||
           !strcmp (element_name, "source") ||
514
           !strcmp (element_name, "destination") ||
515
           !strcmp (element_name, "stack") ||
516
           !strcmp (element_name, "params") ||
517
           !strcmp (element_name, "curve-point"))
518
    {
519
      /* ignore */
520
    }
521 522 523
  else if (1 ||
           !strcmp (element_name, "node") ||
           !strcmp (element_name, "filter"))
Øyvind Kolås's avatar
Øyvind Kolås committed
524 525
    {
      pd->iter   = pd->parent->data;
526
      pd->parent = g_list_delete_link (pd->parent, pd->parent);
527
      pd->state  = STATE_TREE_NORMAL;
Øyvind Kolås's avatar
Øyvind Kolås committed
528 529 530 531 532 533
    }
}

/* Called on error, including one set by other
 * methods in the vtable. The GError should not be freed.
 */
534 535 536 537
static void 
error (GMarkupParseContext *context,
       GError              *error,
       gpointer             user_data)
Øyvind Kolås's avatar
Øyvind Kolås committed
538
{
539 540
  gint  line_number;
  gint  char_number;
541

Øyvind Kolås's avatar
Øyvind Kolås committed
542
  g_markup_parse_context_get_position (context, &line_number, &char_number);
543 544
  g_warning ("XML Parse error %i:%i: %s",
             line_number, char_number, error->message);
Øyvind Kolås's avatar
Øyvind Kolås committed
545 546
}

547
static GMarkupParser parser = {
Øyvind Kolås's avatar
Øyvind Kolås committed
548 549
  start_element,
  end_element,
550
  text,
Øyvind Kolås's avatar
Øyvind Kolås committed
551 552 553 554
  NULL,
  error
};

555 556 557
static void 
each_ref (gpointer value,
          gpointer user_data)
Øyvind Kolås's avatar
Øyvind Kolås committed
558
{
559
  ParseData *pd        = user_data;
Øyvind Kolås's avatar
Øyvind Kolås committed
560 561 562 563 564 565
  GeglNode  *dest_node = value;
  gchar     *ref;
  GeglNode  *source_node;

  gegl_node_get (dest_node, "ref", &ref, NULL);
  source_node = g_hash_table_lookup (pd->ids, ref);
Massimo Valentini's avatar
Massimo Valentini committed
566
  g_free (ref);
567
  gegl_node_connect_from (dest_node, "input", source_node, "output");
Øyvind Kolås's avatar
Øyvind Kolås committed
568 569
}

570 571 572
GeglNode *
gegl_node_new_from_xml (const gchar *xmldata,
                        const gchar *path_root)
Øyvind Kolås's avatar
Øyvind Kolås committed
573
{
574
  ParseData            pd   = { 0, };
Øyvind Kolås's avatar
Øyvind Kolås committed
575
  GMarkupParseContext *context;
576
  gboolean             success = FALSE;
577

578 579
  g_return_val_if_fail (xmldata != NULL, NULL);

580 581
  GEGL_INSTRUMENT_START();

582 583 584
  pd.ids       = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
  pd.refs      = NULL;
  pd.path_root = path_root;
Øyvind Kolås's avatar
Øyvind Kolås committed
585

586 587 588 589 590 591 592 593 594 595 596 597 598
  g_list_free (pd.refs);
  context = g_markup_parse_context_new   (&parser, 0, &pd, NULL);
  success = g_markup_parse_context_parse (context,
                                          xmldata,
                                          strlen (xmldata),
                                          NULL);
  if (success)
    {
      /* connect clones */
      g_list_foreach (pd.refs, each_ref, &pd);
    }
  else
    {
Debarshi Ray's avatar
Debarshi Ray committed
599
      g_clear_object (&pd.gegl);
600
    }
601

602
  g_list_free (pd.refs);
603
  g_list_free (pd.parent);
604 605
  g_markup_parse_context_free (context);
  g_hash_table_destroy (pd.ids);
606

607
  GEGL_INSTRUMENT_END ("gegl", "gegl_parse_xml");
608

609
  return success ? GEGL_NODE (pd.gegl) : NULL;
Øyvind Kolås's avatar
Øyvind Kolås committed
610
}
Øyvind Kolås's avatar
Øyvind Kolås committed
611

612
GeglNode *
613
gegl_node_new_from_file (const gchar   *path)
614
{
615 616
  GeglNode *node = NULL;
  GError   *err  = NULL;
617
  gchar    *script;
618
  gchar    *path_root;
619
  gchar    *dirname;
620 621 622

  g_assert (path);

623
  dirname = g_path_get_dirname (path);
624 625
  path_root = realpath (dirname, NULL);
  if (!path_root)
626 627 628
    {
      goto cleanup;
    }
629 630 631 632 633 634

  g_file_get_contents (path, &script, NULL, &err);
  if (err != NULL)
    {
      g_warning ("Unable to read file: %s", err->message);
      g_error_free (err);
635
      goto cleanup;
636 637
    }

638
  node = gegl_node_new_from_xml (script, path_root);
639

640
cleanup:
641
  g_free (path_root);
642
  g_free (dirname);
643 644 645
  return node;
}

Øyvind Kolås's avatar
Øyvind Kolås committed
646 647 648
/****/


649
#define ind    do { gint i; for (i = 0; i < indent; i++) g_string_append (ss->buf, " "); } while (0)
Øyvind Kolås's avatar
Øyvind Kolås committed
650 651 652 653

typedef struct _SerializeState SerializeState;
struct _SerializeState
{
654 655 656 657 658
  GString     *buf;
  const gchar *path_root;
  gint         clone_count;
  GHashTable  *clones;
  gboolean     terse;
Øyvind Kolås's avatar
Øyvind Kolås committed
659 660
};

661 662 663 664
static void
free_clone_id (gpointer key,
               gpointer value,
               gpointer user_data)
665 666 667
{
  g_free (value);
}
668 669 670 671 672

static void
xml_attr (GString     *buf,
          const gchar *key,
          const gchar *value)
673 674 675 676 677 678 679 680 681 682 683 684
{
  g_assert (key);

  if (value)
    {
      gchar *text = g_markup_escape_text (value, -1);
      gchar *p;

      g_string_append_c (buf, ' ');
      g_string_append (buf, key);
      g_string_append_c (buf, '=');
      g_string_append_c (buf, '\'');
685
      for (p = text; *p; p++)
686
        {
687
          if (*p == '\n')
688 689 690 691 692 693 694 695 696 697
            g_string_append (buf, "&#10;");
          else
            g_string_append_c (buf, *p);
        }
      g_string_append_c (buf, '\'');

      g_free (text);
    }
}

698 699 700 701
static void
xml_param_start (SerializeState *ss,
                 gint            indent,
                 const gchar    *key)
702 703 704 705 706 707 708
{
  g_assert (key);
  ind; g_string_append (ss->buf, "<param name='");
  g_string_append (ss->buf, key);
  g_string_append (ss->buf, "'>");
}

709 710 711
static void
xml_param_text (SerializeState *ss,
                const gchar    *value)
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
{
  gchar *text;
  /*gchar *p;*/

  g_assert (value);

  /* Why isn't this used here??? */
  text = g_markup_escape_text (value, -1);

  g_string_append (ss->buf, value);
  /*for (p=text;*p;p++)
    {
    if (*p=='\n')
    g_string_append (ss->buf, "&#10;");
    else
    g_string_append_c (ss->buf, *p);
728

729 730 731 732 733
    }*/

  g_free (text);
}

734 735
static void
xml_param_end (SerializeState *ss)
736 737 738 739
{
  g_string_append (ss->buf, "</param>\n");
}

740 741 742 743 744
static void
xml_param (SerializeState *ss,
           gint            indent,
           const gchar    *key,
           const gchar    *value)
745 746 747 748
{
  g_assert (key);

  if (value)
749 750 751 752 753 754
  {
    xml_param_start (ss, indent, key);
    xml_param_text (ss, value);
    xml_param_end (ss);
  }
}
755

756 757 758 759 760
static void
xml_curve_point (SerializeState *ss,
                 gint            indent,
                 gfloat          x,
                 gfloat          y)
761 762 763
{
  gchar str[64];
  ind; g_string_append (ss->buf, "<curve-point x='");
764
  g_ascii_dtostr (str, sizeof(str), x);
765 766
  g_string_append (ss->buf, str);
  g_string_append (ss->buf, "' y='");
767
  g_ascii_dtostr (str, sizeof(str), y);
768 769 770
  g_string_append (ss->buf, str);
  g_string_append (ss->buf, "'/>\n");
}
771

772 773 774 775
static void
xml_curve (SerializeState *ss,
           gint            indent,
           GeglCurve      *curve)
776
{
777
  gchar str[G_ASCII_DTOSTR_BUF_SIZE];
778
  gdouble min_y, max_y;
779 780 781 782 783
  guint num_points = gegl_curve_num_points (curve);
  guint i;

  gegl_curve_get_y_bounds (curve, &min_y, &max_y);

784 785
  ind; g_string_append (ss->buf, "<curve ymin='");
  g_ascii_dtostr (str, sizeof(str), min_y);
786
  g_string_append (ss->buf, str);
787 788
  g_string_append (ss->buf, "' ymax='");
  g_ascii_dtostr (str, sizeof(str), max_y);
789
  g_string_append (ss->buf, str);
790
  g_string_append (ss->buf, "'>\n");
791 792
  for (i = 0; i < num_points; ++i)
    {
793
      gdouble x, y;
794 795
      gegl_curve_get_point (curve, i, &x, &y);
      xml_curve_point (ss, indent + 2, x, y);
796
    }
797
  ind; g_string_append (ss->buf, "</curve>\n");
798 799
}

800 801 802 803
static void
serialize_properties (SerializeState *ss,
                      gint            indent,
                      GeglNode       *node)
804
{
805 806 807 808
  GParamSpec **properties;
  guint        n_properties;
  gboolean     got_a_param = FALSE;
  gint         i;
809

810
  properties = gegl_operation_list_properties (gegl_node_get_operation (node),
811
                                     &n_properties);
812

813
  for (i = 0; i < n_properties; i++)
814 815 816 817 818 819 820 821 822 823 824 825
    {
      if (strcmp (properties[i]->name, "input") &&
          strcmp (properties[i]->name, "output") &&
          strcmp (properties[i]->name, "aux"))
        {
          if (!got_a_param)
            {
              ind; g_string_append (ss->buf, "<params>\n");
              got_a_param = TRUE;
            }

          if (g_type_is_a (G_PARAM_SPEC_TYPE (properties[i]),
826
                           GEGL_TYPE_PARAM_FILE_PATH))
827 828 829 830 831 832 833
            {
              gchar *value;
              gegl_node_get (node, properties[i]->name, &value, NULL);

              if (value)
                {
                  if (ss->path_root &&
834
                      !strncmp (ss->path_root, value, strlen (ss->path_root)))
835
                    {
836
                      xml_param (ss, indent + 2, properties[i]->name, &value[strlen (ss->path_root) + 1]);
837 838 839
                    }
                  else
                    {
840
                      xml_param (ss, indent + 2, properties[i]->name, value);
841 842 843 844 845 846 847 848
                    }
                }

              g_free (value);
            }
          else if (properties[i]->value_type == G_TYPE_FLOAT)
            {
              gfloat value;
849
              gchar  str[G_ASCII_DTOSTR_BUF_SIZE];
850
              gegl_node_get (node, properties[i]->name, &value, NULL);
851
              g_ascii_dtostr (str, sizeof(str), value);
852
              xml_param (ss, indent + 2, properties[i]->name, str);
853 854 855 856
            }
          else if (properties[i]->value_type == G_TYPE_DOUBLE)
            {
              gdouble value;
857
              gchar   str[G_ASCII_DTOSTR_BUF_SIZE];
858
              gegl_node_get (node, properties[i]->name, &value, NULL);
859
              g_ascii_dtostr (str, sizeof(str), value);
860
              xml_param (ss, indent + 2, properties[i]->name, str);
861 862 863
            }
          else if (properties[i]->value_type == G_TYPE_INT)
            {
864
              gint  value;
865 866
              gchar str[64];
              gegl_node_get (node, properties[i]->name, &value, NULL);
867
              g_snprintf (str, sizeof (str), "%i", value);
868
              xml_param (ss, indent + 2, properties[i]->name, str);
869
            }
870 871 872 873 874 875 876 877
          else if (properties[i]->value_type == G_TYPE_UINT)
            {
              guint value;
              gchar str[64];
              gegl_node_get (node, properties[i]->name, &value, NULL);
              g_snprintf (str, sizeof (str), "%u", value);
              xml_param (ss, indent + 2, properties[i]->name, str);
            }
878 879 880 881 882 883
          else if (properties[i]->value_type == G_TYPE_BOOLEAN)
            {
              gboolean value;
              gegl_node_get (node, properties[i]->name, &value, NULL);
              if (value)
                {
884
                  xml_param (ss, indent + 2, properties[i]->name, "true");
885 886 887
                }
              else
                {
888
                  xml_param (ss, indent + 2, properties[i]->name, "false");
889 890 891 892 893 894
                }
            }
          else if (properties[i]->value_type == G_TYPE_STRING)
            {
              gchar *value;
              gegl_node_get (node, properties[i]->name, &value, NULL);
895
              xml_param (ss, indent + 2, properties[i]->name, value);
896 897
              g_free (value);
            }
898 899 900 901 902 903 904 905 906 907 908
          else if (g_type_is_a (properties[i]->value_type, G_TYPE_ENUM))
            {
              GEnumClass *eclass = g_type_class_peek (properties[i]->value_type);
              GEnumValue *evalue;
              gint value;

              gegl_node_get (node, properties[i]->name, &value, NULL);
              evalue = g_enum_get_value (eclass, value);

              xml_param (ss, indent + 2, properties[i]->name, evalue->value_nick);
            }
909 910 911
          else if (properties[i]->value_type == GEGL_TYPE_COLOR)
            {
              GeglColor *color;
912
              gchar     *value;
913 914 915
              gegl_node_get (node, properties[i]->name, &color, NULL);
              g_object_get (color, "string", &value, NULL);
              g_object_unref (color);
916
              xml_param (ss, indent + 2, properties[i]->name, value);
917 918
              g_free (value);
            }
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
          else if (properties[i]->value_type == GEGL_TYPE_CURVE)
            {
              GeglCurve *curve;
              gegl_node_get (node, properties[i]->name, &curve, NULL);
              xml_param_start (ss, indent + 2, properties[i]->name);
              g_string_append (ss->buf, "\n");
              xml_curve (ss, indent + 4, curve);
              indent += 2; ind; indent -= 2; xml_param_end (ss);
              g_object_unref (curve);
            }
          else if (properties[i]->value_type == GEGL_TYPE_PATH)
            {
              gchar *svg_path;
              GeglPath *path;
              gegl_node_get (node, properties[i]->name, &path, NULL);
              xml_param_start (ss, indent + 2, properties[i]->name);
              svg_path = gegl_path_to_string (path);
              g_string_append (ss->buf, svg_path);
              xml_param_end (ss);

              g_object_unref (path);
            }
Daniel Sabo's avatar
Daniel Sabo committed
941 942 943 944 945 946 947 948 949 950 951 952
          else if (properties[i]->value_type == G_TYPE_POINTER &&
                   GEGL_IS_PARAM_SPEC_FORMAT (properties[i]))
            {
              const Babl  *format;
              const gchar *value;
              gegl_node_get (node, properties[i]->name, &format, NULL);
              if (format)
                value = babl_get_name (format);
              else
                value = "";
              xml_param (ss, indent + 2, properties[i]->name, value);
            }
953 954 955 956 957 958
          else if (properties[i]->value_type == GEGL_TYPE_AUDIO_FRAGMENT)
            {
            }
          else if (properties[i]->value_type == GEGL_TYPE_BUFFER)
            {
            }
959 960
          else
            {
961
              g_warning ("%s: serialization of %s properties not implemented",
962
                         properties[i]->name, g_type_name (properties[i]->value_type));
963 964 965 966
            }
        }
    }

967 968 969 970
  if (got_a_param)
    {
      ind; g_string_append (ss->buf, "</params>\n");
    }
971 972 973
  g_free (properties);
}

974 975 976 977
static void
serialize_layer (SerializeState *ss,
                 gint            indent,
                 GeglNode       *layer)
978
{
979 980 981
  gchar  *name;
  gchar  *src;
  gchar  *composite_op;
982 983 984 985 986
  gdouble x;
  gdouble y;
  gdouble opacity;

  gegl_node_get (layer, "name", &name,
987 988 989 990 991 992
                 "src", &src,
                 "x", &x,
                 "y", &y,
                 "opacity", &opacity,
                 "composite_op", &composite_op,
                 NULL);
993 994 995
  ind; g_string_append (ss->buf, "<layer");
  if (name[0])
    g_string_append_printf (ss->buf, " name='%s'", name);
996
  if (x != 0.0)
997 998 999 1000 1001
    {
      gchar str[G_ASCII_DTOSTR_BUF_SIZE];
      g_ascii_dtostr (str, sizeof(str), x);
      g_string_append_printf (ss->buf, " x='%s'", str);
    }
1002
  if (y != 0.0)
1003 1004 1005 1006 1007
    {
      gchar str[G_ASCII_DTOSTR_BUF_SIZE];
      g_ascii_dtostr (str, sizeof(str), y);
      g_string_append_printf (ss->buf, " y='%s'", str);
    }
1008
  if (opacity != 1.0)
1009 1010 1011 1012 1013
    {
      gchar str[G_ASCII_DTOSTR_BUF_SIZE];
      g_ascii_dtostr (str, sizeof(str), opacity);
      g_string_append_printf (ss->buf, " opacity='%s'", str);
    }
1014 1015 1016 1017 1018
  if (src[0])
    {
      if (ss->path_root &&
          !strncmp (ss->path_root, src, strlen (ss->path_root)))
        {
1019
          g_string_append_printf (ss->buf, " src='%s'", &src[strlen (ss->path_root) + 1]);
1020 1021 1022 1023 1024 1025 1026 1027 1028
        }
      else
        {
          g_string_append_printf (ss->buf, " src='%s'", src);
        }
    }
  g_string_append (ss->buf, "/>\n");
}

1029 1030 1031
static void
add_stack (SerializeState *ss,
           gint            indent,
1032 1033
           GeglNode       *head,
           GeglNode       *tail)
1034 1035
{
  /*ind; g_string_append (ss->buf, "<stack>\n");
1036
     indent+=2;*/
1037 1038 1039 1040

  if (GEGL_IS_NODE (head))
    {
      GeglNode *iter = head;
1041
      gboolean last = FALSE;
1042 1043 1044

      while (iter)
        {
1045 1046
          const gchar *id = NULL;
          gchar       *class;
1047 1048
          gegl_node_get (iter, "operation", &class, NULL);

1049
          if (gegl_node_get_consumers (iter, "output", NULL, NULL) > 1)
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
            {
              const gchar *new_id = g_hash_table_lookup (ss->clones, iter);
              if (new_id)
                {
                  ind; g_string_append (ss->buf, "<clone ref='");
                  g_string_append (ss->buf, new_id);
                  g_string_append (ss->buf, "'/>\n");
                  return; /* terminate the stack, the cloned part is already
                             serialized */
                }
              else
                {
                  gchar temp_id[64];
1063 1064
                  g_snprintf (temp_id, sizeof (temp_id),
                              "clone%i", ss->clone_count++);
1065
                  id = g_strdup (temp_id);
1066
                  g_hash_table_insert (ss->clones, iter, (gchar *) id);
1067 1068 1069 1070
                  /* the allocation is freed by the hash table */
                }
            }

1071
          if (class)
1072
            {
1073
              if (!strcmp (class, "layer"))
1074
                {
1075
                  serialize_layer (ss, indent, iter);
1076 1077 1078
                }
              else
                {
1079 1080
                  GeglNode *source_node = gegl_node_get_producer (iter, "aux", NULL);
                  if (source_node)
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
                    {
                      {
                        GeglNode *graph = g_object_get_data (G_OBJECT (source_node),
                                                             "graph");
                        if (graph)
                          source_node = graph;
                      }
                      ind; g_string_append (ss->buf, "<node");

                      {
                        gchar *class;
                        gchar *name;
                        gegl_node_get (iter, "operation", &class,
                                       "name", &name,
                                       NULL);
                        if (name[0])
                          {
                            xml_attr (ss->buf, "name", name);
                          }
                        xml_attr (ss->buf, "operation", class);
                        if (id != NULL)
                          xml_attr (ss->buf, "id", id);
1103 1104 1105 1106

                        if (gegl_node_get_passthrough (iter) == TRUE)
                          xml_attr (ss->buf, "passthrough", "true");

1107 1108 1109 1110 1111 1112
                        g_free (name);
                        g_free (class);
                      }

                      g_string_append (ss->buf, ">\n");
                      serialize_properties (ss, indent + 4, iter);
1113
                      add_stack (ss, indent + 4, source_node, NULL);
1114 1115 1116 1117

                      ind; g_string_append (ss->buf, "</node>\n");
                    }
                  else
1118
                    {
1119 1120
                      if (strcmp (class, "gegl:nop") &&
                          strcmp (class, "gegl:clone"))
1121
                        {
1122
                          ind; g_string_append (ss->buf, "<node");
1123 1124 1125 1126 1127

                          {
                            gchar *class;
                            gchar *name;
                            gegl_node_get (iter, "operation", &class,
1128 1129
                                           "name", &name,
                                           NULL);
1130 1131 1132 1133 1134 1135 1136
                            if (name[0])
                              {
                                xml_attr (ss->buf, "name", name);
                              }
                            xml_attr (ss->buf, "operation", class);
                            if (id != NULL)
                              xml_attr (ss->buf, "id", id);
1137 1138 1139 1140

                            if (gegl_node_get_passthrough (iter) == TRUE)
                              xml_attr (ss->buf, "passthrough", "true");

1141 1142 1143 1144 1145
                            g_free (name);
                            g_free (class);
                          }

                          g_string_append (ss->buf, ">\n");
1146 1147
                          serialize_properties (ss, indent + 4, iter);
                          ind; g_string_append (ss->buf, "</node>\n");
1148 1149 1150 1151 1152
                        }
                    }
                }
            }
          id = NULL;
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

          if (last)
            iter = NULL;
          else
            {
              GeglNode *source_node = gegl_node_get_producer (iter, "input", NULL);
              if (source_node)
                {
                  GeglNode *graph       = g_object_get_data (G_OBJECT (source_node),
                                                             "graph");

                  if (source_node == tail)
                    last = TRUE;

                  /* if source_node is a proxy then make it point to
                   * the actual node
                   */
                  if (graph)
                    source_node = graph;

                  if (source_node == tail)
                    last = TRUE;

                  iter = source_node;
                }
              else
                iter = NULL;
            }
1181 1182 1183 1184 1185

          g_free (class);
        }
    }
  /*indent-=2;
1186
     ind; g_string_append (ss->buf, "<stack>\n");*/
Øyvind Kolås's avatar
Øyvind Kolås committed
1187 1188 1189
}

gchar *
1190 1191 1192
gegl_node_to_xml_full (GeglNode    *head,
                       GeglNode    *tail,
                       const gchar *path_root)
Øyvind Kolås's avatar
Øyvind Kolås committed
1193
{
1194
  GeglOperation *operation;
1195
  SerializeState  ss;
1196

1197 1198 1199 1200 1201
  ss.buf         = g_string_new ("");
  ss.path_root   = path_root;
  ss.clone_count = 0;
  ss.clones      = g_hash_table_new (NULL, NULL);
  ss.terse       = FALSE;
Øyvind Kolås's avatar
Øyvind Kolås committed
1202

1203
  operation = gegl_node_get_gegl_operation (head);
1204 1205 1206 1207
  /* this case is for empty graphs, and graphs with nodes that are
   * not meta-ops
   */
  if (!operation)
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    head = gegl_node_get_output_proxy (head, "output");

  if (tail)
    {
      operation = gegl_node_get_gegl_operation (tail);
      /* this case is for empty graphs, and graphs with nodes that are
       * not meta-ops
       */
      if (!operation)
        tail = gegl_node_get_input_proxy (tail, "input");
    }
1219

1220 1221
  g_string_append (ss.buf, "<?xml version='1.0' encoding='UTF-8'?>\n");
  g_string_append (ss.buf, "<gegl>\n");
Øyvind Kolås's avatar
Øyvind Kolås committed
1222

1223
  add_stack (&ss, 2, head, tail);
1224

1225
  g_string_append (ss.buf, "</gegl>\n");
Øyvind Kolås's avatar
Øyvind Kolås committed
1226

1227 1228
  g_hash_table_foreach (ss.clones, free_clone_id, NULL);
  g_hash_table_destroy (ss.clones);
1229

1230
  return g_string_free (ss.buf, FALSE);
Øyvind Kolås's avatar
Øyvind Kolås committed
1231
}
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

gchar *
gegl_node_to_xml (GeglNode    *gegl,
                  const gchar *path_root)
{
  gchar *xml;

  xml = gegl_node_to_xml_full (gegl, NULL, path_root);
  return xml;
}