File: vtkSMLoadStateOptionsProxy.cxx

package info (click to toggle)
paraview 5.4.1%2Bdfsg4-3.1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 218,616 kB
  • sloc: cpp: 2,331,508; ansic: 322,365; python: 111,051; xml: 79,203; tcl: 47,013; yacc: 4,877; java: 4,438; perl: 3,238; sh: 2,920; lex: 1,908; f90: 748; makefile: 273; pascal: 228; objc: 83; fortran: 31
file content (508 lines) | stat: -rw-r--r-- 17,394 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
189
190
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
227
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
261
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*=========================================================================

  Program:   ParaView
  Module:    vtkSMLoadStateOptionsProxy.cxx

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkClientServerStream.h"
#include "vtkFileSequenceParser.h"
#include "vtkObjectFactory.h"
#include "vtkPVSession.h"
#include "vtkPVXMLElement.h"
#include "vtkPVXMLParser.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMFileListDomain.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMPropertyIterator.h"
#include "vtkSMProxyManager.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMTrace.h"
#include "vtksys/SystemTools.hxx"
#include <vtk_pugixml.h>

using namespace vtksys;

#include <algorithm>
#include <set>
#include <sstream>

//---------------------------------------------------------------------------
class vtkSMLoadStateOptionsProxy::vtkInternals
{
public:
  struct PropertyInfo
  {
    pugi::xml_node XMLElement;
    std::vector<std::string> FilePaths;
    bool Modified;
    PropertyInfo()
      : Modified(false)
    {
    }
  };
  typedef std::map<int, std::map<std::string, PropertyInfo> > PropertiesMapType;
  PropertiesMapType PropertiesMap;
  std::map<int, pugi::xml_node> CollectionsMap;
  pugi::xml_document StateXML;

  void ProcessStateFile(pugi::xml_node node)
  {
    pugi::xpath_node_set proxies =
      node.select_nodes("//ServerManagerState/Proxy[@group and @type]");
    for (auto iter = proxies.begin(); iter != proxies.end(); ++iter)
    {
      this->ProcessProxy(iter->node());
    }
    pugi::xpath_node_set collections =
      node.select_nodes("//ServerManagerState/ProxyCollection[@name='sources']");
    for (auto iter = collections.begin(); iter != collections.end(); ++iter)
    {
      this->ProcessProxyCollection(iter->node());
    }
  }

  void ProcessProxy(pugi::xml_node node)
  {
    pugi::xml_attribute group = node.attribute("group");
    pugi::xml_attribute type = node.attribute("type");

    if (group.empty() || type.empty())
    {
      vtkGenericWarningMacro("Possibly invalid state file.");
      return;
    }

    vtkSMProxy* prototype =
      vtkSMProxyManager::GetProxyManager()->GetActiveSessionProxyManager()->GetPrototypeProxy(
        group.value(), type.value());
    if (!prototype)
    {
      return;
    }

    std::set<std::string> filenameProperties = this->LocateFileNameProperties(prototype);
    if (filenameProperties.size() == 0)
    {
      return;
    }

    int proxyId = node.attribute("id").as_int();

    pugi::xpath_variable_set vars;
    vars.add("propertyname", pugi::xpath_type_string);
    for (auto iter = filenameProperties.begin(); iter != filenameProperties.end(); ++iter)
    {
      vars.set("propertyname", iter->c_str());
      pugi::xpath_node_set properties =
        node.select_nodes("./Property[@name = string($propertyname)]", &vars);
      for (auto pIter = properties.begin(); pIter != properties.end(); ++pIter)
      {
        PropertyInfo info;
        info.XMLElement = pIter->node();
        pugi::xpath_node_set elements = info.XMLElement.select_nodes("./Element");
        for (auto eIter = elements.begin(); eIter != elements.end(); ++eIter)
        {
          info.FilePaths.push_back(eIter->node().attribute("value").value());
        }
        this->PropertiesMap[proxyId][pIter->node().attribute("name").value()] = info;
      }
    }
  }

  void ProcessProxyCollection(pugi::xml_node node)
  {
    pugi::xml_attribute name = node.attribute("name");
    if (name.empty())
    {
      vtkGenericWarningMacro(
        "Possibly invalid state file. Proxy Collection doesn't have a name attribute.");
      return;
    }

    pugi::xpath_node_set items = node.select_nodes("./Item");
    for (auto iter = items.begin(); iter != items.end(); ++iter)
    {
      int itemId = iter->node().attribute("id").as_int();
      this->CollectionsMap[itemId] = iter->node();
    }
  }

  std::set<std::string> LocateFileNameProperties(vtkSMProxy* proxy)
  {
    std::set<std::string> fileNameProperties;
    vtkSMPropertyIterator* piter = proxy->NewPropertyIterator();
    for (piter->Begin(); !piter->IsAtEnd(); piter->Next())
    {
      vtkSMProperty* property = piter->GetProperty();
      vtkSMDomainIterator* diter = property->NewDomainIterator();
      for (diter->Begin(); !diter->IsAtEnd(); diter->Next())
      {
        if (vtkSMFileListDomain::SafeDownCast(diter->GetDomain()))
        {
          fileNameProperties.insert(piter->GetKey());
        }
      }
      diter->Delete();
    }
    piter->Delete();
    return fileNameProperties;
  }
};

vtkStandardNewMacro(vtkSMLoadStateOptionsProxy);
//----------------------------------------------------------------------------
vtkSMLoadStateOptionsProxy::vtkSMLoadStateOptionsProxy()
{
  this->Internals = new vtkInternals();
  this->StateFileName = 0;
  this->PathMatchingThreshold = 3;
}

//----------------------------------------------------------------------------
vtkSMLoadStateOptionsProxy::~vtkSMLoadStateOptionsProxy()
{
  delete this->Internals;
  this->SetStateFileName(0);
}

//----------------------------------------------------------------------------
namespace
{

/**
 * Converts pugixml to vtkPVXMLElement
 */
vtkPVXMLElement* ConvertXML(vtkPVXMLParser* parser, pugi::xml_node& node)
{
  std::stringstream ss;
  node.print(ss);

  parser->Parse(ss.str().c_str());
  return parser->GetRootElement();
}
}

//----------------------------------------------------------------------------
bool vtkSMLoadStateOptionsProxy::PrepareToLoad(const char* statefilename)
{
  this->SetStateFileName(statefilename);
  pugi::xml_parse_result result = this->Internals->StateXML.load_file(statefilename);

  if (!result)
  {
    vtkErrorMacro(
      "Error parsing state file XML from " << statefilename << ": " << result.description());
    return false;
  }

  this->Internals->ProcessStateFile(this->Internals->StateXML);

  vtkSMSessionProxyManager* pxm =
    vtkSMProxyManager::GetProxyManager()->GetActiveSessionProxyManager();

  std::map<std::string, int> namesUsed;

  // Setup proxies for for explict file change dialog
  for (auto idIter = this->Internals->PropertiesMap.begin();
       idIter != this->Internals->PropertiesMap.end(); idIter++)
  {
    pugi::xml_node proxyXML = idIter->second.begin()->second.XMLElement.parent();
    vtkSmartPointer<vtkSMProxy> newReaderProxy;
    newReaderProxy.TakeReference(
      pxm->NewProxy(proxyXML.attribute("group").value(), proxyXML.attribute("type").value()));
    newReaderProxy->PrototypeOn();

    // Property group to group properties by source
    pugi::xml_document propertyGroup;
    pugi::xml_node propertyGroupElement = propertyGroup.append_child("PropertyGroup");
    propertyGroupElement.append_attribute("label").set_value(proxyXML.attribute("type").value());
    propertyGroupElement.append_attribute("panel_widget").set_value("LoadStateOptionsDialog");

    vtkNew<vtkPVXMLParser> XMLParser;
    newReaderProxy->LoadXMLState(ConvertXML(XMLParser.Get(), proxyXML), nullptr);
    std::string newProxyName = std::to_string(idIter->first);
    this->AddSubProxy(newProxyName.c_str(), newReaderProxy.GetPointer());

    std::string baseName =
      this->Internals->CollectionsMap[idIter->first].attribute("name").as_string();

    // Remove all '.'s in the name to avoid possible name collisions with the appended index
    // If baseName is not unique for each proxy then the proxies are linked and their properties
    // cannot
    // be set separately if the property names are the same.
    baseName.erase(std::remove(baseName.begin(), baseName.end(), '.'), baseName.end());

    auto nameUseCount = namesUsed.find(baseName);
    if (nameUseCount != namesUsed.end())
    {
      baseName.append(".").append(std::to_string(nameUseCount->second));
      ++nameUseCount->second;
    }
    else
    {
      namesUsed[baseName] = 1;
    }

    for (auto pIter = idIter->second.begin(); pIter != idIter->second.end(); pIter++)
    {
      vtkSmartPointer<vtkSMProperty> property = newReaderProxy->GetProperty(pIter->first.c_str());
      property->SetPanelVisibility("default");

      // Hints to insure explicit file property only show up for that mode
      pugi::xml_document hints;
      pugi::xml_node widgetDecorator =
        hints.append_child("Hints").append_child("PropertyWidgetDecorator");
      widgetDecorator.append_attribute("type").set_value("GenericDecorator");
      widgetDecorator.append_attribute("mode").set_value("visibility");
      widgetDecorator.append_attribute("property").set_value("LoadStateDataFileOptions");
      widgetDecorator.append_attribute("value").set_value("2");

      property->SetHints(ConvertXML(XMLParser.Get(), hints));

      pugi::xml_node propertyXML = pIter->second.XMLElement;
      std::string exposedName = baseName;

      exposedName.append(".").append(propertyXML.attribute("name").value());
      this->ExposeSubProxyProperty(newProxyName.c_str(), propertyXML.attribute("name").value(),
        exposedName.c_str(), 1 /*override*/);
      propertyGroupElement.append_child("Property")
        .append_attribute("name")
        .set_value(exposedName.c_str());
    }

    this->NewPropertyGroup(ConvertXML(XMLParser.Get(), propertyGroup));
  }

  return true;
}

//----------------------------------------------------------------------------
bool vtkSMLoadStateOptionsProxy::HasDataFiles()
{
  // This will always return false until PrepareToLoad has been called
  return (this->Internals->PropertiesMap.size() > 0);
}

//----------------------------------------------------------------------------
bool vtkSMLoadStateOptionsProxy::LocateFilesInDirectory(
  std::vector<std::string>& filepaths, bool clearFilenameIfNotFound)
{
  std::string lastLocatedPath = "";
  int numOfPathMatches = 0;
  std::vector<std::string>::iterator fIter;
  for (fIter = filepaths.begin(); fIter != filepaths.end(); ++fIter)
  {
    // TODO: Inefficient - need vtkPVInfomation class to bundle file paths
    if (numOfPathMatches < this->PathMatchingThreshold)
    {
      vtkClientServerStream stream;
      stream << vtkClientServerStream::Invoke << VTKOBJECT(this) << "LocateFileInDirectory"
             << *fIter << vtkClientServerStream::End;
      this->ExecuteStream(stream, false, vtkPVSession::DATA_SERVER_ROOT);
      vtkClientServerStream result = this->GetLastResult();
      std::string locatedPath = "";
      if (result.GetNumberOfMessages() == 1 && result.GetNumberOfArguments(0) == 1)
      {
        result.GetArgument(0, 0, &locatedPath);
      }

      if (!locatedPath.empty())
      {
        *fIter = locatedPath;
        if (SystemTools::GetParentDirectory(locatedPath) ==
          SystemTools::GetParentDirectory(lastLocatedPath))
        {
          numOfPathMatches++;
        }
        else
        {
          numOfPathMatches = 0;
        }
        lastLocatedPath = locatedPath;
      }
      else if (clearFilenameIfNotFound)
      {
        vtkErrorMacro(<< "Could not find file " << *fIter << " in data directory.");
        *fIter = "";
      }
      else
      {
        return false;
      }
    }
    else
    {
      std::vector<std::string> directoryPathComponents;
      SystemTools::SplitPath(
        SystemTools::GetParentDirectory(lastLocatedPath), directoryPathComponents);
      directoryPathComponents.push_back(SystemTools::GetFilenameName(*fIter));
      *fIter = SystemTools::JoinPath(directoryPathComponents);
    }
  }
  return true;
}

//----------------------------------------------------------------------------
bool vtkSMLoadStateOptionsProxy::Load()
{
  SM_SCOPED_TRACE(LoadState).arg("filename", this->StateFileName).arg("options", this);

  this->SetDataFileOptions(vtkSMPropertyHelper(this, "LoadStateDataFileOptions").GetAsInt());
  this->SetOnlyUseFilesInDataDirectory(
    vtkSMPropertyHelper(this, "OnlyUseFilesInDataDirectory").GetAsInt() == 1);
  switch (this->DataFileOptions)
  {
    case USE_FILES_FROM_STATE:
    {
      // Nothing to do
      break;
    }
    case USE_DATA_DIRECTORY:
    {
      for (auto idIter = this->Internals->PropertiesMap.begin();
           idIter != this->Internals->PropertiesMap.end(); idIter++)
      {
        for (auto pIter = idIter->second.begin(); pIter != idIter->second.end(); pIter++)
        {
          vtkInternals::PropertyInfo& info = pIter->second;

          if (pIter->first.find("FilePattern") == std::string::npos)
          {
            if (this->LocateFilesInDirectory(info.FilePaths, this->OnlyUseFilesInDataDirectory))
            {
              info.Modified = true;
            }
          }
        }
      }

      break;
    }
    case CHOOSE_FILES_EXPLICITLY:
    {
      for (auto idIter = this->Internals->PropertiesMap.begin();
           idIter != this->Internals->PropertiesMap.end(); idIter++)
      {
        vtkSMProxy* subProxy = this->GetSubProxy(std::to_string(idIter->first).c_str());
        for (auto pIter = idIter->second.begin(); pIter != idIter->second.end(); pIter++)
        {
          std::string propertyValue =
            vtkSMPropertyHelper(subProxy, pIter->first.c_str()).GetAsString();
          vtkInternals::PropertyInfo& info = pIter->second;

          // First check if environment variable shows up in user specified path
          if (propertyValue.compare(0, 1, "$") == 0)
          {
            std::vector<std::string> pathComponents;
            SystemTools::SplitPath(propertyValue, pathComponents);
            std::string variablePath;
            if (SystemTools::GetEnv(pathComponents[1].erase(0, 1), variablePath))
            {
              pathComponents.erase(pathComponents.begin(), pathComponents.begin() + 2);
              std::vector<std::string> variablePathComponents;
              SystemTools::SplitPath(variablePath, variablePathComponents);
              pathComponents.insert(pathComponents.begin(), variablePathComponents.begin(),
                variablePathComponents.end());
              propertyValue = SystemTools::JoinPath(pathComponents);
            }
            else
            {
              vtkWarningMacro("Environment variable " << pathComponents[1] << " is not set.");
              continue;
            }
          }

          if (info.FilePaths.size() == 1)
          {
            info.FilePaths[0] = propertyValue;
            info.Modified = true;
          }
          else if (info.FilePaths.size() > 1)
          {
            // Assume the filename will be unchanged so just add the new path the file
            std::vector<std::string> newPathCompenents;
            SystemTools::SplitPath(SystemTools::GetFilenamePath(propertyValue), newPathCompenents);
            for (auto fIter = info.FilePaths.begin(); fIter != info.FilePaths.end(); fIter++)
            {
              newPathCompenents.push_back(SystemTools::GetFilenameName(*fIter));
              *fIter = SystemTools::JoinPath(newPathCompenents);
              newPathCompenents.pop_back();
            }
            info.Modified = true;
          }
        }
      }
      break;
    }
  }

  for (auto idIter = this->Internals->PropertiesMap.begin();
       idIter != this->Internals->PropertiesMap.end(); idIter++)
  {
    std::string primaryFilename = "";
    bool propertiesModified = false;
    for (auto pIter = idIter->second.begin(); pIter != idIter->second.end(); pIter++)
    {
      vtkInternals::PropertyInfo& info = pIter->second;
      if (!info.Modified)
      {
        continue;
      }
      else
      {
        propertiesModified = true;
      }

      for (auto fIter = info.FilePaths.begin(); fIter != info.FilePaths.end(); ++fIter)
      {
        std::string idx = std::to_string(std::distance(info.FilePaths.begin(), fIter));
        info.XMLElement.find_child_by_attribute("Element", "index", idx.c_str())
          .attribute("value")
          .set_value(fIter->c_str());

        if (primaryFilename.empty() && fIter->compare(0, 3, "XML") != 0)
        {
          primaryFilename = fIter->c_str();
        }
      }
    }

    // Also fix up sources proxy collection
    // Get sequence basename if needed
    if (propertiesModified)
    {
      std::string filename = SystemTools::GetFilenameName(primaryFilename);
      vtkNew<vtkFileSequenceParser> sequenceParser;
      if (sequenceParser->ParseFileSequence(filename.c_str()))
      {
        filename = sequenceParser->GetSequenceName();
      }

      this->Internals->CollectionsMap[idIter->first].attribute("name").set_value(filename.c_str());
    }
  }

  vtkSMSessionProxyManager* pxm =
    vtkSMProxyManager::GetProxyManager()->GetActiveSessionProxyManager();
  vtkNew<vtkPVXMLParser> XMLParser;
  pxm->LoadXMLState(ConvertXML(XMLParser.Get(), this->Internals->StateXML));

  return true;
}

//----------------------------------------------------------------------------
void vtkSMLoadStateOptionsProxy::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}