vtkXMLUtilities.cxx 17.6 KB
Newer Older
1 2 3 4 5
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLUtilities.cxx

6
  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
7 8 9
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

10 11
     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12 13 14 15 16 17 18 19 20
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLUtilities.h"

#include "vtkObjectFactory.h"
#include "vtkXMLDataElement.h"
#include "vtkXMLDataParser.h"

21
#include <sstream>
22

23 24
#if !defined(_WIN32) || defined(__CYGWIN__)
# include <unistd.h> /* unlink */
Bill Hoffman's avatar
Bill Hoffman committed
25 26
#else
# include <io.h> /* unlink */
27 28
#endif

29
#include <vector>
30

31
typedef std::vector<vtkXMLDataElement*> vtkXMLUtilitiesDataElementContainer;
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

vtkStandardNewMacro(vtkXMLUtilities);

#define  VTK_XML_UTILITIES_FACTORED_POOL_NAME "FactoredPool"
#define  VTK_XML_UTILITIES_FACTORED_NAME      "Factored"
#define  VTK_XML_UTILITIES_FACTORED_REF_NAME  "FactoredRef"

//----------------------------------------------------------------------------
inline int vtkXMLUtilitiesEncodeEntities(unsigned char c, ostream &output)
{
  switch (c)
    {
    case '&':
      output << "&amp;";
      return 1;

    case '"':
      output << "&quot;";
      return 1;

    case '\'':
      output << "&apos;";
      return 1;

    case '<':
      output << "&lt;";
      return 1;

    case '>':
      output << "&gt;";
      return 1;
    }

  return 0;
}

//----------------------------------------------------------------------------
69
void vtkXMLUtilities::EncodeString(const char *input, int input_encoding,
70 71 72
                                   ostream &output, int output_encoding,
                                   int special_entities)
{
73
  // No string
74

75
  if (!input)
76 77 78 79
    {
    return;
    }

80
  // If either the input or output encoding is not specified,
81
  // or they are the same, dump as is (if no entites had to be converted)
82

83 84 85 86 87 88
  int no_input_encoding = (input_encoding <= VTK_ENCODING_NONE ||
                           input_encoding >= VTK_ENCODING_UNKNOWN);

  int no_output_encoding = (output_encoding <= VTK_ENCODING_NONE ||
                            output_encoding >= VTK_ENCODING_UNKNOWN);

89 90
  if (!special_entities &&
      (no_input_encoding || no_output_encoding ||
91
       input_encoding == output_encoding))
92 93 94 95 96 97 98 99
    {
    output << input;
    return;
    }

  // Convert

  const unsigned char *str = (const unsigned char*)input;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

  // If either the input or output encoding is not specified, just process
  // the entities

  if (no_input_encoding || no_output_encoding)
    {
    while (*str)
      {
      if (!vtkXMLUtilitiesEncodeEntities(*str, output))
        {
        output << *str;
        }
      str++;
      }
    return;
    }

117 118 119 120
  // To VTK_UTF_8...

  if (output_encoding == VTK_ENCODING_UTF_8)
    {
121
    int from_iso_8859 = (input_encoding >= VTK_ENCODING_ISO_8859_1 &&
122
                         input_encoding <= VTK_ENCODING_ISO_8859_16);
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    // From ISO-8859 or US-ASCII

    if (input_encoding == VTK_ENCODING_US_ASCII || from_iso_8859)
      {
      while (*str)
        {
        if (!special_entities || !vtkXMLUtilitiesEncodeEntities(*str, output))
          {
          if (*str > 0x7F)
            {
#if 0
            // This should be the right implementation, but it seems that
            // it just does not work for Expat. Brad and I should dig into
            // that later, but it seems weird. In the meantime, just
            // output the hex representation.

140 141 142
            output << "&#x"
                   << hex << (0xC0 | (*str >> 6))
                   << hex << (0x80 | (*str & 0x3F))
143 144 145 146
                   << ';';
#else
            output << "&#x" << hex << (int)(*str) << ';';
#endif
147
            }
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
          else if (*str < 30)
            {
            output << "&#x" << hex << (int)(*str) << ';';
            }
          else
            {
            output << *str;
            }
          }
        str++;
        }
      }

    // From VTK_ENCODING_UTF_8 (i.e. just encode the entities)
    // To be completed (need the whole &#x)

    else if (input_encoding == VTK_ENCODING_UTF_8)
      {
      while (*str)
        {
        if (!vtkXMLUtilitiesEncodeEntities(*str, output))
          {
          output << *str;
          }
        str++;
        }
      }

    // Unsupported input encoding

    else
      {
      vtkGenericWarningMacro(
        << "Input encoding not supported (" << input_encoding << ")");
      }
    }

  // From VTK_ENCODING_UTF_8...

  else if (input_encoding == VTK_ENCODING_UTF_8)
    {
189
    int to_iso_8859 = (output_encoding >= VTK_ENCODING_ISO_8859_1 &&
190
                       output_encoding <=VTK_ENCODING_ISO_8859_16);
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    // To US-ASCII or ISO 8859

    if (output_encoding == VTK_ENCODING_US_ASCII || to_iso_8859)
      {
      while (*str)
        {
        if (!special_entities || !vtkXMLUtilitiesEncodeEntities(*str, output))
          {
          // Multi-byte 2-chars converted into one char

          if (*str > 0x7F)
            {
            output << (unsigned char)((*str << 6) | (str[1] & 0x3F));
            str++;
            }
          else
            {
            output << *str;
            }
          }
        str++;
        }
      }

    // Unsupported output encoding

    else
      {
      vtkGenericWarningMacro(
        << "Output encoding not supported (" << input_encoding << ")");
      }
    }
}

//----------------------------------------------------------------------------
227
void vtkXMLUtilities::CollateAttributes(vtkXMLDataElement *elem,
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
                                        ostream &os,
                                        const char *sep)
{
  if (!elem)
    {
    return;
    }

  int i, nb = elem->GetNumberOfAttributes();
  for (i = 0; i < nb; i++)
    {
    const char *name = elem->GetAttributeName(i);
    if (name)
      {
      const char *value = elem->GetAttribute(name);
      if (value)
        {
        if (i)
          {
          os << (sep ? sep : " ");
          }
        os << name << "=\"";
        vtkXMLUtilities::EncodeString(
          value, elem->GetAttributeEncoding(), os, VTK_ENCODING_UTF_8, 1);
        os << '\"';
        }
      }
    }

  return;
}

//----------------------------------------------------------------------------
261
void vtkXMLUtilities::FlattenElement(vtkXMLDataElement *elem,
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                                     ostream &os,
                                     vtkIndent *indent,
                                     int indent_attributes)
{
  if (!elem)
    {
    return;
    }

  unsigned long pos = os.tellp();

  // Name

  if (indent)
    {
    os << *indent;
    }

  os << '<' << elem->GetName();

  // Attributes

  if (elem->GetNumberOfAttributes())
    {
    os << ' ';
    if (indent && indent_attributes)
      {
      unsigned long len = (unsigned long)os.tellp() - pos;
      if (os.fail())
        {
        return;
        }
      char *sep = new char [1 + len + 1];
      sep[0] = '\n';
      memset(sep + 1, ' ', len);
      sep[len + 1] = '\0';
      vtkXMLUtilities::CollateAttributes(elem, os, sep);
      delete [] sep;
      }
    else
      {
      vtkXMLUtilities::CollateAttributes(elem, os);
      }
    }

Sebastien Barre's avatar
Sebastien Barre committed
307
  const char *cdata = elem->GetCharacterData();
308
  int nb_nested = elem->GetNumberOfNestedElements();
Sebastien Barre's avatar
Sebastien Barre committed
309 310 311
  int need_close_tag = (nb_nested || cdata);

  if (!need_close_tag)
312 313 314 315 316 317
    {
    os << "/>";
    }
  else
    {
    os << '>';
Sebastien Barre's avatar
Sebastien Barre committed
318 319 320 321 322 323 324 325 326
    }

  // cdata

  if (cdata)
    {
    vtkXMLUtilities::EncodeString(
      cdata, elem->GetAttributeEncoding(), os, VTK_ENCODING_UTF_8, 1);
    }
327

Sebastien Barre's avatar
Sebastien Barre committed
328
  // Nested elements
329

Sebastien Barre's avatar
Sebastien Barre committed
330 331
  if (nb_nested)
    {
332 333 334 335 336 337 338 339 340
    if (indent)
      {
      os << '\n';
      }
    for (int i = 0; i < nb_nested; i++)
      {
      if (indent)
        {
        vtkIndent next_indent = indent->GetNextIndent();
341
        vtkXMLUtilities::FlattenElement(elem->GetNestedElement(i),
342 343 344 345 346 347 348 349 350 351 352
                                        os, &next_indent);
        }
      else
        {
        vtkXMLUtilities::FlattenElement(elem->GetNestedElement(i), os);
        }
      }
    if (indent)
      {
      os << *indent;
      }
Sebastien Barre's avatar
Sebastien Barre committed
353 354 355 356 357 358
    }

  // Close

  if (need_close_tag)
    {
359 360
    os << "</" << elem->GetName() << '>';
    }
Sebastien Barre's avatar
Sebastien Barre committed
361

362 363 364 365 366 367 368
  if (indent)
    {
    os << '\n';
    }
}

//----------------------------------------------------------------------------
369
int vtkXMLUtilities::WriteElementToFile(vtkXMLDataElement *elem,
370 371 372 373 374 375 376 377 378 379
                                        const char *filename,
                                        vtkIndent *indent)
{
  if (!elem || !filename)
    {
    return 0;
    }

  ofstream os(filename, ios::out);
  vtkXMLUtilities::FlattenElement(elem, os, indent);
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  os.flush();
  if (os.fail())
    {
    os.close();
    unlink(filename);
    return 0;
    }
  return 1;
}

//----------------------------------------------------------------------------
vtkXMLDataElement*
vtkXMLUtilities::ReadElementFromStream(istream &is, int encoding)
{
  vtkXMLDataElement *res = NULL;
  vtkXMLDataParser* xml_parser = vtkXMLDataParser::New();
  xml_parser->SetAttributesEncoding(encoding);

  xml_parser->SetStream(&is);
  if (xml_parser->Parse())
    {
    res = xml_parser->GetRootElement();
403 404 405
    // Bump up the ref count since we are going to delete the parser
    // which actually owns the element
    res->SetReferenceCount(res->GetReferenceCount() + 1);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    vtkXMLUtilities::UnFactorElements(res);
    }

  xml_parser->Delete();
  return res;
}

//----------------------------------------------------------------------------
vtkXMLDataElement*
vtkXMLUtilities::ReadElementFromString(const char *str, int encoding)
{
  if (!str)
    {
    return 0;
    }

422
  std::stringstream strstr;
423
  strstr << str;
424
  vtkXMLDataElement *res =
425
    vtkXMLUtilities::ReadElementFromStream(strstr, encoding);
426

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  return res;
}

//----------------------------------------------------------------------------
vtkXMLDataElement*
vtkXMLUtilities::ReadElementFromFile(const char *filename, int encoding)
{
  if (!filename)
    {
    return NULL;
    }

  ifstream is(filename);
  return vtkXMLUtilities::ReadElementFromStream(is, encoding);
}

443 444 445 446 447 448 449 450
//----------------------------------------------------------------------------
void vtkXMLUtilities::ReadElementFromAttributeArray(
        vtkXMLDataElement *element,
        const char** atts,
        int encoding)
{
  if(atts)
    {
451
    // If the target encoding is VTK_ENCODING_NONE or VTK_ENCODING_UNKNOWN,
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    // then keep the internal/default encoding, otherwise encode each
    // attribute using that new format

    if (encoding != VTK_ENCODING_NONE && encoding != VTK_ENCODING_UNKNOWN)
      {
      element->SetAttributeEncoding(encoding);
      }

    // Process each attributes returned by Expat in UTF-8 encoding, and
    // convert them to our encoding

    for (int i = 0; atts[i] && atts[i + 1]; i += 2)
      {
      if (element->GetAttributeEncoding() == VTK_ENCODING_UTF_8)
        {
        element->SetAttribute(atts[i], atts[i + 1]);
        }
      else
        {
471
        std::ostringstream str;
472 473 474 475 476 477 478 479 480
        vtkXMLUtilities::EncodeString(
          atts[i+1], VTK_ENCODING_UTF_8, str, element->GetAttributeEncoding(), 0);
        str << ends;
        element->SetAttribute(atts[i], str.str().c_str());
        }
      }
    }
}

481
//----------------------------------------------------------------------------
482
static void vtkXMLUtilitiesFindSimilarElementsInternal(
483 484
  vtkXMLDataElement *elem,
  vtkXMLDataElement *tree,
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
  vtkXMLUtilitiesDataElementContainer *results)
{
  if (!elem || !tree || !results || elem == tree)
    {
    return;
    }

  // If the element is equal to the current tree, append it to the
  // results, otherwise check the sub-trees

  if (elem->IsEqualTo(tree))
    {
    results->push_back(tree);
    }
  else
    {
    for (int i = 0; i < tree->GetNumberOfNestedElements(); i++)
      {
      vtkXMLUtilitiesFindSimilarElementsInternal(
        elem, tree->GetNestedElement(i), results);
      }
    }
}

//----------------------------------------------------------------------------
510 511
int vtkXMLUtilities::FindSimilarElements(vtkXMLDataElement *elem,
                                         vtkXMLDataElement *tree,
512 513 514 515 516 517 518 519 520
                                         vtkXMLDataElement ***results)
{
  if (!elem || ! tree)
    {
    return 0;
    }

  // Create a data element container, and find all similar elements

521
  vtkXMLUtilitiesDataElementContainer *container =
522
    new vtkXMLUtilitiesDataElementContainer;
523

524 525 526 527 528 529 530 531 532 533 534 535 536
  vtkXMLUtilitiesFindSimilarElementsInternal(elem, tree, container);

  // If nothing was found, exit now

  int size = (int)container->size();
  if (size)
    {
    // Allocate an array of element and copy the contents of the container
    // to this flat structure

    *results = new vtkXMLDataElement* [size];

    size = 0;
537
    for (vtkXMLUtilitiesDataElementContainer::const_iterator
538 539 540 541 542 543 544 545
           it = container->begin(); it != container->end(); ++it)
      {
      if (*it)
        {
        (*results)[size++] = *it;
        }
      }
    }
546

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  delete container;

  return size;
}

//----------------------------------------------------------------------------
void vtkXMLUtilities::FactorElements(vtkXMLDataElement *tree)
{
  if (!tree)
    {
    return;
    }

  // Create the factored pool, and add it to the tree so that it can
  // factor itself too

  vtkXMLDataElement *pool = vtkXMLDataElement::New();
  pool->SetName(VTK_XML_UTILITIES_FACTORED_POOL_NAME);
  pool->SetAttributeEncoding(tree->GetAttributeEncoding());
  tree->AddNestedElement(pool);

Kyle Lutz's avatar
Kyle Lutz committed
568
  // Factor the tree, as long as some factorization has occurred
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
  // (multiple pass might be needed because larger trees are factored
  // first)

  while (vtkXMLUtilities::FactorElementsInternal(tree, tree, pool)) {};

  // Nothing factored, remove the useless pool

  if (!pool->GetNumberOfNestedElements())
    {
    tree->RemoveNestedElement(pool);
    }

  pool->Delete();
}

//----------------------------------------------------------------------------
int vtkXMLUtilities::FactorElementsInternal(vtkXMLDataElement *tree,
                                            vtkXMLDataElement *root,
                                            vtkXMLDataElement *pool)
{
  if (!tree || !root || !pool)
    {
    return 0;
    }

  // Do not bother factoring something already factored

596
  if (tree->GetName() &&
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
      !strcmp(tree->GetName(), VTK_XML_UTILITIES_FACTORED_REF_NAME))
    {
    return 0;
    }

  // Try to find all trees similar to the current tree

  vtkXMLDataElement **similar_trees;
  int nb_of_similar_trees = vtkXMLUtilities::FindSimilarElements(
    tree, root, &similar_trees);

  // None was found, try to factor the sub-trees

  if (!nb_of_similar_trees)
    {
    int res = 0;
    for (int i = 0; i < tree->GetNumberOfNestedElements(); i++)
      {
      res += vtkXMLUtilities::FactorElementsInternal(
        tree->GetNestedElement(i), root, pool);
      }
    return res ? 1 : 0;
    }

  // Otherwise replace those trees with factored refs

  char buffer[5];
  sprintf(buffer, "%02d_", pool->GetNumberOfNestedElements());

626
  std::ostringstream id;
627
  id << buffer << tree->GetName();
628

629 630 631
  vtkXMLDataElement *factored = vtkXMLDataElement::New();
  factored->SetName(VTK_XML_UTILITIES_FACTORED_NAME);
  factored->SetAttributeEncoding(pool->GetAttributeEncoding());
632
  factored->SetAttribute("Id", id.str().c_str());
633 634 635 636 637 638 639
  pool->AddNestedElement(factored);
  factored->Delete();

  vtkXMLDataElement *tree_copy = vtkXMLDataElement::New();
  tree_copy->DeepCopy(tree);
  factored->AddNestedElement(tree_copy);
  tree_copy->Delete();
640

641 642 643 644
  for (int i = 0; i < nb_of_similar_trees; i++)
    {
    similar_trees[i]->RemoveAllAttributes();
    similar_trees[i]->RemoveAllNestedElements();
645
    similar_trees[i]->SetCharacterData(NULL, 0);
646
    similar_trees[i]->SetName(VTK_XML_UTILITIES_FACTORED_REF_NAME);
647
    similar_trees[i]->SetAttribute("Id", id.str().c_str());
648 649 650 651
    }

  tree->RemoveAllAttributes();
  tree->RemoveAllNestedElements();
652
  tree->SetCharacterData(NULL, 0);
653
  tree->SetName(VTK_XML_UTILITIES_FACTORED_REF_NAME);
654
  tree->SetAttribute("Id", id.str().c_str());
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

  delete [] similar_trees;

  return 1;
}

//----------------------------------------------------------------------------
void vtkXMLUtilities::UnFactorElements(vtkXMLDataElement *tree)
{
  if (!tree)
    {
    return;
    }

  // Search for the factored pool, if not found, we are done

  vtkXMLDataElement *pool = tree->FindNestedElementWithName(
    VTK_XML_UTILITIES_FACTORED_POOL_NAME);
  if (!pool)
    {
    return;
    }

  // Remove the pool from the tree, because it makes no sense
  // unfactoring it too

  pool->Register(tree);
  tree->RemoveNestedElement(pool);

  // Unfactor the tree

  vtkXMLUtilities::UnFactorElementsInternal(tree, pool);

  // Remove the useless empty pool

  pool->UnRegister(tree);
}

//----------------------------------------------------------------------------
int vtkXMLUtilities::UnFactorElementsInternal(vtkXMLDataElement *tree,
                                              vtkXMLDataElement *pool)
{
  if (!tree || !pool)
    {
    return 0;
    }

  int res = 0;

  // We found a factor, replace it with the corresponding sub-tree

  if (tree->GetName() &&
      !strcmp(tree->GetName(), VTK_XML_UTILITIES_FACTORED_REF_NAME))
    {
709
    vtkXMLDataElement *original_tree =
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
      pool->FindNestedElementWithNameAndAttribute(
        VTK_XML_UTILITIES_FACTORED_NAME, "Id", tree->GetAttribute("Id"));
    if (original_tree && original_tree->GetNumberOfNestedElements())
      {
      tree->DeepCopy(original_tree->GetNestedElement(0));
      res++;
      }
    }

  // Now try to unfactor the sub-trees

  for (int i = 0; i < tree->GetNumberOfNestedElements(); i++)
    {
    res += vtkXMLUtilities::UnFactorElementsInternal(
      tree->GetNestedElement(i), pool);
    }

  return res ? 1 : 0;
}