Salome HOME
export of 3D poly to SHP (lot 5)
[modules/hydro.git] / src / HYDROData / HYDROData_Document.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include <HYDROData_Document.h>
20 #include <HYDROData_Application.h>
21 #include <HYDROData_Iterator.h>
22 #include <HYDROData_Tool.h>
23 #include <HYDROData_InterpolatorsFactory.h>
24 #include <HYDROData_StricklerTable.h>
25 #include <HYDROData_LandCoverMap.h>
26
27 #include <TDataStd_Real.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataXtd_Position.hxx>
30
31 #include <TDF_Delta.hxx>
32
33 #include <gp_Pnt.hxx>
34
35 #include <QFile>
36 #include <QStringList>
37 #include <QTextStream>
38 #include <QColor>
39
40 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Document,MMgt_TShared)
41
42 #define PYTHON_DOC_NAME "hydro_doc"
43
44 static const int UNDO_LIMIT = 10; // number of possible undo operations in the module
45
46 static const int TAG_PROPS = 1; // general properties tag
47 static const int TAG_PROPS_NEW_ID = 1; // general properties: tag for storage of the new object ID
48 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree
49 static const int TAG_HISTORY = 3; // tag of the history sub-tree (Root for History)
50 static const int TAG_LOCAL_CS = 4; // tag of local coordinate system information
51 static const int TAG_DEF_STRICKLER_COEFF = 5; // tag of default strickler coefficient
52 static const int TAG_COUNT_QUADTREE = 6; // tag of number of quadtrees created so far
53 static const int TAG_COUNT_DELAUNAY = 7; // tag of number of Delaunay triangulations created so far
54 static const gp_Pnt2d DEFAULT_LOCAL_CS( 0, 0 );
55
56 using namespace std;
57
58 typedef QMap<Standard_Integer, Handle(HYDROData_Entity)> MapOfOrdered;
59 typedef QMap<QString, Handle(HYDROData_Entity)> MapOfUnordered;
60
61 Handle(HYDROData_Document) HYDROData_Document::Document(const int theStudyID)
62 {
63   Handle(HYDROData_Document) aResult = 
64     HYDROData_Application::GetApplication()->GetDocument(theStudyID);
65   if (aResult.IsNull()) {
66     aResult = new HYDROData_Document();
67     HYDROData_Application::GetApplication()->AddDocument(theStudyID, aResult);
68   }
69   return aResult;
70 }
71
72 Handle(HYDROData_Document) HYDROData_Document::Document(
73   const TDF_Label& theObjectLabel )
74 {
75   Handle(HYDROData_Document) aResDoc;
76   if ( theObjectLabel.IsNull() )
77     return aResDoc;
78
79   Handle(TDocStd_Document) anObjDoc;
80   try
81   {
82     anObjDoc = TDocStd_Document::Get( theObjectLabel );
83   }
84   catch( ... )
85   {
86   }
87
88   if ( anObjDoc.IsNull() )
89     return aResDoc;
90
91   HYDROData_Application* anApp = HYDROData_Application::GetApplication();
92
93   DataMapOfStudyIDDocument::Iterator aMapIt( anApp->myDocuments );
94   for ( ; aMapIt.More(); aMapIt.Next() )
95   {
96     Handle(HYDROData_Document) anAppDoc = aMapIt.Value();
97     if ( anAppDoc.IsNull() || anAppDoc->myDoc != anObjDoc )
98       continue;
99
100     aResDoc = anAppDoc;
101     break;
102   }
103
104   return aResDoc;
105 }
106
107 bool HYDROData_Document::HasDocument(const int theStudyID)
108 {
109   Handle(HYDROData_Document) aResult = 
110     HYDROData_Application::GetApplication()->GetDocument(theStudyID);
111   return !aResult.IsNull();
112 }
113
114 bool HYDROData_Document::DocumentId(const Handle(HYDROData_Document)& theDocument,
115                                     int&                              theDocId )
116 {
117   return HYDROData_Application::GetApplication()->GetDocumentId(theDocument, theDocId);
118 }
119
120 Data_DocError HYDROData_Document::Load(const char* theFileName, const int theStudyID)
121 {
122   Handle(TDocStd_Document) aResult;
123   TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
124   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
125   try
126   {
127     aStatus = HYDROData_Application::GetApplication()->Open (aPath, aResult);
128   }
129   catch (Standard_Failure)
130   {}
131   if (!aResult.IsNull()) {
132     aResult->SetUndoLimit(UNDO_LIMIT);
133     HYDROData_Application::GetApplication()->AddDocument(theStudyID, new HYDROData_Document(aResult));
134   }
135   // recognize error
136   Data_DocError anError;
137   switch(aStatus) {
138   case PCDM_RS_OK:
139     anError = DocError_OK;
140     break;
141   case PCDM_RS_NoDriver:
142   case PCDM_RS_UnknownFileDriver:
143   case PCDM_RS_NoSchema:
144   case PCDM_RS_DriverFailure:
145   case PCDM_RS_WrongResource:
146     anError = DocError_ResourcesProblem;
147     break;
148   case PCDM_RS_OpenError:
149   case PCDM_RS_NoDocument:
150   case PCDM_RS_WrongStreamMode:
151   case PCDM_RS_PermissionDenied:
152     anError = DocError_CanNotOpen;
153     break;
154   case PCDM_RS_NoVersion:
155     anError = DocError_InvalidVersion;
156     break;
157   case PCDM_RS_ExtensionFailure:
158   case PCDM_RS_FormatFailure:
159   case PCDM_RS_TypeFailure:
160   case PCDM_RS_TypeNotFoundInSchema:
161   case PCDM_RS_UnrecognizedFileFormat:
162     anError = DocError_InvalidFormat;
163     break;
164   case PCDM_RS_MakeFailure:
165   default:
166     anError = DocError_UnknownProblem;
167     break;
168   }
169   return anError;
170 }
171
172 Data_DocError HYDROData_Document::Save(const char* theFileName)
173 {
174   TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
175   PCDM_StoreStatus aStatus;
176   try {
177     aStatus = HYDROData_Application::GetApplication()->SaveAs (myDoc, aPath);
178   }
179   catch (Standard_Failure) {}
180   myTransactionsAfterSave = 0;
181   Standard::Purge(); // Release free memory
182
183   // recognize error
184   Data_DocError anError;
185   switch(aStatus) {
186   case PCDM_SS_OK:
187     anError = DocError_OK;
188     break;
189   case PCDM_SS_DriverFailure:
190     anError = DocError_ResourcesProblem;
191     break;
192   case PCDM_SS_WriteFailure:
193   //case PCDM_SS_DiskWritingFailure:
194   //case PCDM_SS_UserRightsFailure:
195     anError = DocError_CanNotOpen;
196     break;
197   default:
198     anError = DocError_UnknownProblem;
199     break;
200   }
201   return anError;
202 }
203
204 void HYDROData_Document::Close()
205 {
206   myDoc->Close();
207   HYDROData_Application::GetApplication()->RemoveDocument(this);
208 }
209
210 double HYDROData_Document::GetDefaultStricklerCoefficient() const
211 {
212     double aRes = 0;
213     TDF_Label aLabel = myDoc->Main().FindChild(TAG_DEF_STRICKLER_COEFF, Standard_False);
214     if ( !aLabel.IsNull() )
215     {
216         Handle(TDataStd_Real) anAttr;
217         if ( aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
218             aRes = anAttr->Get();
219     }
220
221     return aRes;
222 }
223
224 void HYDROData_Document::SetDefaultStricklerCoefficient( double theCoeff ) const
225 {
226     TDF_Label aLabel = myDoc->Main().FindChild(TAG_DEF_STRICKLER_COEFF);
227     if ( !aLabel.IsNull() )
228     {
229         Handle(TDataStd_Real) anAttr;
230         if ( !aLabel.FindAttribute( TDataStd_Real::GetID(), anAttr ) )
231         {
232           anAttr = new TDataStd_Real();
233           aLabel.AddAttribute(anAttr);
234           anAttr->SetID(TDataStd_Real::GetID());
235         }
236         anAttr->Set( theCoeff );
237     }
238 }
239
240 int HYDROData_Document::GetCountQuadtree() const
241 {
242   int nbQuad = 0;
243   TDF_Label aLabel = myDoc->Main().FindChild(TAG_COUNT_QUADTREE, Standard_False);
244   if ( !aLabel.IsNull() )
245   {
246       Handle(TDataStd_Integer) anAttr;
247       if ( aLabel.FindAttribute( TDataStd_Integer::GetID(), anAttr ) )
248           nbQuad = anAttr->Get();
249   }
250   return nbQuad;
251 }
252
253 void HYDROData_Document::SetCountQuadtree( int nbQuad) const
254 {
255   TDF_Label aLabel = myDoc->Main().FindChild(TAG_COUNT_QUADTREE);
256   if ( !aLabel.IsNull() )
257   {
258       Handle(TDataStd_Integer) anAttr;
259       if ( !aLabel.FindAttribute( TDataStd_Integer::GetID(), anAttr ) )
260       {
261         anAttr = new TDataStd_Integer();
262         aLabel.AddAttribute(anAttr);
263         anAttr->SetID(TDataStd_Integer::GetID());
264         }
265       anAttr->Set( nbQuad );
266   }
267 }
268
269 int HYDROData_Document::GetCountDelaunay() const
270 {
271   int nbDelaunay = 0;
272   TDF_Label aLabel = myDoc->Main().FindChild(TAG_COUNT_DELAUNAY, Standard_False);
273   if ( !aLabel.IsNull() )
274   {
275       Handle(TDataStd_Integer) anAttr;
276       if ( aLabel.FindAttribute( TDataStd_Integer::GetID(), anAttr ) )
277         nbDelaunay = anAttr->Get();
278   }
279   return nbDelaunay;
280 }
281
282 void HYDROData_Document::SetCountDelaunay( int nbDelaunay) const
283 {
284   TDF_Label aLabel = myDoc->Main().FindChild(TAG_COUNT_DELAUNAY);
285   if ( !aLabel.IsNull() )
286   {
287       Handle(TDataStd_Integer) anAttr;
288       if ( !aLabel.FindAttribute( TDataStd_Integer::GetID(), anAttr ) )
289       {
290         anAttr = new TDataStd_Integer();
291         aLabel.AddAttribute(anAttr);
292         anAttr->SetID(TDataStd_Integer::GetID());
293       }
294       anAttr->Set( nbDelaunay );
295   }
296 }
297
298 bool HYDROData_Document::DumpToPython( const QString& thePyScriptPath,
299                                        const bool     theIsMultiFile ) const
300 {
301   // Try to open the file
302   QFile aFile( thePyScriptPath );
303   if ( !aFile.open( QIODevice::WriteOnly | QFile::Text ) )
304     return false;
305
306   MapOfTreatedObjects aTreatedObjects;
307
308   // Dump header for python script
309   QStringList aHeaderDump = DumpToPython( thePyScriptPath, aTreatedObjects, theIsMultiFile );
310   if ( aHeaderDump.isEmpty() )
311     return false;
312
313   HYDROData_Tool::WriteStringsToFile( aFile, aHeaderDump );
314
315   bool aRes = true;
316
317   // Dump the local CS data to Python 
318   UpdateLCSFields();
319   QString aLCS = QString( "%1.SetLocalCS( %2, %3 )" ).arg( GetDocPyName() ).arg( myLX, 0, 'f', 3 ).arg( myLY, 0, 'f', 3 );
320   if( theIsMultiFile )
321     aLCS.prepend( "  " );
322   HYDROData_Tool::WriteStringsToFile( aFile, QStringList() << aLCS );
323
324   // Dump all model objects to Python script
325   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_IMAGE );
326   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_STRICKLER_TABLE );
327   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_POLYLINEXY );
328   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_BATHYMETRY );
329   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_PROFILE );
330   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_POLYLINE );
331   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_IMMERSIBLE_ZONE );
332   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_STREAM );
333   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_CHANNEL );
334   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_DIGUE );
335   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_OBSTACLE );
336   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_LAND_COVER_MAP );
337   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_BC_POLYGON );
338   aRes = aRes && dumpPartitionToPython( aFile, thePyScriptPath, theIsMultiFile, aTreatedObjects, KIND_CALCULATION );
339
340   // Dump code to close python fuction
341   if ( aRes && theIsMultiFile )
342   {
343     QStringList aFooterScript;
344     aFooterScript << QString( "" );
345     aFooterScript << QString( "  pass" );
346     HYDROData_Tool::WriteStringsToFile( aFile, aFooterScript );
347   }
348
349   return aRes;
350 }
351
352 QString HYDROData_Document::GetDocPyName() const
353 {
354   QString aDocName = PYTHON_DOC_NAME;
355   
356   /*
357   int aDocId = 1;
358   if ( DocumentId( this, aDocId ) )
359     aDocName += "_" + QString::number( aDocId );
360   */
361   
362   return aDocName;
363 }
364
365 QStringList HYDROData_Document::DumpToPython( const QString& thePyScriptPath,
366                                               MapOfTreatedObjects& theTreatedObjects,
367                                               const bool           theIsMultiFile ) const
368 {
369   QString aDocName = GetDocPyName();
370
371   // Append document in to the map of treated objects to prevent names overlaping
372   theTreatedObjects.insert( aDocName, this );
373
374   int aDocId = 1;
375   if ( !DocumentId( this, aDocId ) )
376     aDocId = 1;
377
378   QStringList aResScript;
379
380   aResScript << QString( "from HYDROPy import *" );
381   aResScript << QString( "from PyQt5.QtCore import *" );
382   aResScript << QString( "from PyQt5.QtGui import *" );
383
384   if ( theIsMultiFile )
385   {
386     aResScript << QString( "import salome" );
387     aResScript << QString( "" );
388     aResScript << QString( "def RebuildData( theStudy ):" );
389     aResScript << QString( "  %1 = HYDROData_Document.Document( theStudy._get_StudyId() )" ).arg( aDocName );
390   }
391   else
392   {
393     aResScript << QString( "" );
394     aResScript << QString( "%1 = HYDROData_Document.Document( theStudy._get_StudyId() )" ).arg( aDocName );
395   }
396
397   return aResScript;
398 }
399
400 bool HYDROData_Document::dumpPartitionToPython( QFile&               theFile,
401                                                 const QString&       thePyScriptPath,
402                                                 const bool           theIsMultiFile,
403                                                 MapOfTreatedObjects& theTreatedObjects,
404                                                 const ObjectKind&    theObjectKind ) const
405 {
406   if ( !theFile.isOpen() )
407     return false;
408
409   QTextStream anOutStream( &theFile );
410
411   bool aRes = true;
412
413   HYDROData_Iterator anIterator( this, theObjectKind );
414   for( ; anIterator.More(); anIterator.Next() )
415   {
416     Handle(HYDROData_Entity) anObject = anIterator.Current();
417     if ( anObject.IsNull() )
418       continue;
419
420     QString anObjName = anObject->GetName();
421     if ( theTreatedObjects.contains( anObjName ) )
422       continue;
423
424     theTreatedObjects.insert( anObjName, anObject );
425
426     QStringList anObjDump = anObject->DumpToPython( thePyScriptPath, theTreatedObjects );
427
428     if ( theIsMultiFile )
429     {
430       // For multifile dump we use the function, see the document dump header
431       QStringList::iterator anIt = anObjDump.begin();
432       for ( ; anIt != anObjDump.end(); ++anIt )
433         anIt->prepend( "  " );
434     }
435     
436     HYDROData_Tool::WriteStringsToFile( theFile, anObjDump );
437   }
438   
439   return aRes;
440 }
441
442 bool takeLastDigits( QString& theStr, int& aRes )
443 {
444   aRes = -1;
445
446   QString anStrNum;
447   for ( int i = theStr.length() - 1; i >= 0; --i )
448   {
449     const QChar& aChar = theStr.at( i );
450     if ( !aChar.isDigit() )
451       break;
452
453     anStrNum.prepend( aChar );
454   }
455
456   if ( anStrNum.isEmpty() )
457     return false;
458
459   theStr.remove( theStr.length() - anStrNum.length(), anStrNum.length() );
460   aRes = anStrNum.toInt();
461
462   return true;
463 }
464
465 bool isObjectNameLessThan( const QString& theStr1, const QString& theStr2 )
466 {
467   QString aStr1 = theStr1, aStr2 = theStr2;
468
469   int aNum1 = -1, aNum2 = -1;
470   if ( takeLastDigits( aStr1, aNum1 ) && takeLastDigits( aStr2, aNum2 ) )
471   {
472     if ( aStr1 == aStr2 )
473       return aNum1 < aNum2;
474   }
475
476   return theStr1 < theStr2;
477 }
478
479 HYDROData_SequenceOfObjects HYDROData_Document::GetObjectsLayerOrder(
480   const Standard_Boolean theIsAll ) const
481 {
482   HYDROData_SequenceOfObjects anOrder;
483
484   MapOfOrdered   aMapOfOrdered;
485   MapOfUnordered aMapOfUnordered;
486
487   HYDROData_Iterator anIter( this );
488   for ( ; anIter.More(); anIter.Next() )
489   {
490     Handle(HYDROData_Entity) anObject = anIter.Current();
491     if ( anObject.IsNull() || !anObject->IsHas2dPrs() )
492       continue;
493
494     Standard_Integer anObjZLevel = -1;
495     if ( anObject->GetZLevel( anObjZLevel ) )
496     {
497       aMapOfOrdered.insert( anObjZLevel, anObject );
498     }
499     else
500     {
501       QString anObjName = anObject->GetName();
502       if ( anObjName.isEmpty() )
503         continue;
504
505       aMapOfUnordered.insert( anObjName, anObject );
506     }
507   }
508
509   MapOfOrdered::const_iterator anOrderedMapIt = aMapOfOrdered.constBegin();
510   for ( ; anOrderedMapIt != aMapOfOrdered.constEnd(); anOrderedMapIt++ )
511   {
512     const Handle(HYDROData_Entity)& anObject = anOrderedMapIt.value();
513     anOrder.Prepend( anObject );
514   }
515
516   if ( theIsAll )
517   {
518     QStringList aSortedNames = aMapOfUnordered.keys();
519     qSort( aSortedNames.begin(), aSortedNames.end(), isObjectNameLessThan );
520
521     for ( int i = 0; i < aSortedNames.length(); ++i )
522     {
523       QString anObjName = aSortedNames.value( i );
524
525       const Handle(HYDROData_Entity)& anObject = aMapOfUnordered.value( anObjName );
526       anOrder.Append( anObject );
527     }
528   }
529
530   return anOrder;
531 }
532
533 void HYDROData_Document::SetObjectsLayerOrder( const HYDROData_SequenceOfObjects& theOrder )
534 {
535   // At first we remove previous model order
536   RemoveObjectsLayerOrder();
537
538   // Make new objects order
539   Standard_Integer aLevel = 0;
540   for ( int i = theOrder.Length(), n = 1; i >= n; --i )
541   {
542     const Handle(HYDROData_Entity)& anObject = theOrder.Value( i );
543     if ( anObject.IsNull() || !anObject->IsHas2dPrs() )
544       continue;
545
546     anObject->SetZLevel( aLevel++ );
547   }
548 }
549
550 void HYDROData_Document::Show( const Handle(HYDROData_Entity)& theObject )
551 {
552   HYDROData_SequenceOfObjects anOrder;
553   anOrder.Append( theObject );
554   Show( anOrder );
555 }
556
557 void HYDROData_Document::Show( const HYDROData_SequenceOfObjects& theObjects )
558 {
559   MapOfUnordered aMapOfUnordered;
560
561   for ( int i = 1, n = theObjects.Length(); i <= n; ++i )
562   {
563     const Handle(HYDROData_Entity)& anObject = theObjects.Value( i );
564     if ( anObject.IsNull() || !anObject->IsHas2dPrs() )
565       continue;
566
567     Standard_Integer anObjZLevel = -1;
568     if ( anObject->GetZLevel( anObjZLevel ) )
569     {
570       continue; // Skip objects that already have the z-level
571     }
572     else
573     {
574       QString anObjName = anObject->GetName();
575       if ( anObjName.isEmpty() )
576         continue;
577
578       aMapOfUnordered.insert( anObjName, anObject );
579     }
580   }
581
582   if ( aMapOfUnordered.isEmpty() )
583     return; // Nothing to show
584
585   Standard_Integer aTopId = 0;
586
587   HYDROData_SequenceOfObjects aModelOrder = GetObjectsLayerOrder( Standard_False );
588   if ( !aModelOrder.IsEmpty() )
589   {
590     const Handle(HYDROData_Entity)& anObject = aModelOrder.First();
591     anObject->GetZLevel( aTopId );
592     aTopId++;
593   }
594
595   aTopId += aMapOfUnordered.size() - 1;
596
597   QStringList aSortedNames = aMapOfUnordered.keys();
598   qSort( aSortedNames.begin(), aSortedNames.end(), isObjectNameLessThan );
599
600   for ( int i = 0; i < aSortedNames.length(); ++i )
601   {
602     QString anObjName = aSortedNames.value( i );
603
604     const Handle(HYDROData_Entity)& anObject = aMapOfUnordered.value( anObjName );
605     anObject->SetZLevel( aTopId-- );
606   }
607 }
608
609 void HYDROData_Document::RemoveObjectsLayerOrder()
610 {
611   HYDROData_Iterator anIter( this );
612   for ( ; anIter.More(); anIter.Next() )
613   {
614     Handle(HYDROData_Entity) anObject = anIter.Current();
615     if ( anObject.IsNull() || !anObject->IsHas2dPrs() )
616       continue;
617
618     anObject->RemoveZLevel();
619   }
620 }
621
622 void HYDROData_Document::StartOperation()
623 {
624   myDoc->NewCommand();
625 }
626
627 void HYDROData_Document::CommitOperation(const TCollection_ExtendedString& theName)
628 {
629   if( !myDoc->CommitCommand() ) // it means that there were no modifications done
630   {
631     myDoc->NewCommand();
632     NewID(); // workaround: do something just to modify the document
633     myDoc->CommitCommand();
634   }
635   myTransactionsAfterSave++;
636
637   if( theName.Length() != 0 )
638   {
639     const TDF_DeltaList& aList = GetUndos();
640     if( !aList.IsEmpty() )
641     {
642       Handle(TDF_Delta) aDelta = aList.Last();
643       if( !aDelta.IsNull() )
644         aDelta->SetName( theName );
645     }
646   }
647 }
648
649 void HYDROData_Document::AbortOperation()
650 {
651   myDoc->AbortCommand();
652 }
653
654 bool HYDROData_Document::IsOperation()
655 {
656   return myDoc->HasOpenCommand() != 0;
657 }
658
659 bool HYDROData_Document::IsModified()
660 {
661   return myTransactionsAfterSave != 0;
662 }
663
664 bool HYDROData_Document::CanUndo()
665 {
666   return myDoc->GetAvailableUndos() > 0;
667 }
668
669 const TDF_DeltaList& HYDROData_Document::GetUndos()
670 {
671   return myDoc->GetUndos();
672 }
673
674 void HYDROData_Document::ClearUndos()
675 {
676   return myDoc->ClearUndos();
677 }
678
679 void HYDROData_Document::Undo()
680 {
681   myDoc->Undo();
682   myTransactionsAfterSave--;
683 }
684
685 bool HYDROData_Document::CanRedo()
686 {
687   return myDoc->GetAvailableRedos() > 0;
688 }
689
690 const TDF_DeltaList& HYDROData_Document::GetRedos()
691 {
692   return myDoc->GetRedos();
693 }
694
695 void HYDROData_Document::ClearRedos()
696 {
697   return myDoc->ClearRedos();
698 }
699
700 void HYDROData_Document::Redo()
701 {
702   myDoc->Redo();
703   myTransactionsAfterSave++;
704 }
705
706 Handle(HYDROData_Entity) HYDROData_Document::CreateObject( const ObjectKind theKind )
707 {
708   return HYDROData_Iterator::CreateObject( this, theKind );
709 }
710
711 Handle(HYDROData_Entity) HYDROData_Document::FindObjectByName( 
712   const QString&   theName,
713   const ObjectKind theObjectKind ) const
714 {
715   Handle(HYDROData_Entity) anObject;
716   if ( theName.isEmpty() )
717     return anObject;
718
719   QStringList aNamesList;
720   aNamesList << theName;
721
722   HYDROData_SequenceOfObjects aSeqOfObjs = FindObjectsByNames( aNamesList, theObjectKind );
723   if( aSeqOfObjs.IsEmpty() )
724     return anObject;
725   
726   anObject = aSeqOfObjs.First();
727   return anObject;
728 }
729
730 HYDROData_SequenceOfObjects HYDROData_Document::FindObjectsByNames(
731   const QStringList& theNames, 
732   const ObjectKind   theObjectKind ) const
733 {
734   HYDROData_SequenceOfObjects aResSeq;
735
736   QStringList aNamesList = theNames;
737
738   HYDROData_Iterator anIter( this, theObjectKind );
739   for( ; anIter.More(); anIter.Next() )
740   {
741     Handle(HYDROData_Entity) anObject = anIter.Current();
742     if( anObject.IsNull() )
743       continue;
744
745     QString anObjName = anObject->GetName();
746     if ( anObjName.isEmpty() || !aNamesList.contains( anObjName ) )
747       continue;
748
749     aResSeq.Append( anObject );
750
751     aNamesList.removeAll( anObjName );
752     if ( aNamesList.isEmpty() )
753       break;
754   }
755
756   return aResSeq;
757 }
758
759 HYDROData_SequenceOfObjects HYDROData_Document::CollectAllObjects( const ObjectKind theObjectKind ) const
760 {
761   HYDROData_SequenceOfObjects aResSeq;
762   HYDROData_Iterator anIter( this, theObjectKind );
763   for( ; anIter.More(); anIter.Next() )
764   {
765     Handle(HYDROData_Entity) anObject = anIter.Current();
766     if( anObject.IsNull() )
767       continue;
768     aResSeq.Append( anObject );
769   }
770   return aResSeq;
771 }
772
773 HYDROData_Document::HYDROData_Document()
774 {
775   HYDROData_Application::GetApplication()->NewDocument("BinOcaf", myDoc);
776   myDoc->SetUndoLimit(UNDO_LIMIT);
777   NewID(); // needed to have at least one attribute in initial document to avoid errors
778   myTransactionsAfterSave = 0;
779   myLX = -1;
780   myLY = -1;
781
782   myInterpolatorsFactory = 0;
783 }
784
785 HYDROData_Document::HYDROData_Document(const Handle(TDocStd_Document)& theDoc)
786 {
787   myDoc = theDoc;
788   myTransactionsAfterSave = 0;
789   myLX = -1;
790   myLY = -1;
791
792   myInterpolatorsFactory = 0;
793 }
794
795 HYDROData_Document::~HYDROData_Document()
796 {
797 }
798
799 int HYDROData_Document::NewID()
800 {
801   TDF_Label anIDLab = myDoc->Main().FindChild(TAG_PROPS).
802     FindChild(TAG_PROPS_NEW_ID);
803   Handle(TDataStd_Integer) anInt;
804   if (!anIDLab.FindAttribute(TDataStd_Integer::GetID(), anInt)) {
805     anInt = TDataStd_Integer::Set(anIDLab, 0);
806     anInt->SetID(TDataStd_Integer::GetID());
807   }
808   // just increment value and return
809   anInt->Set(anInt->Get() + 1);
810   return anInt->Get();
811 }
812
813 TDF_Label HYDROData_Document::LabelOfObjects()
814 {
815   return myDoc->Main().FindChild(TAG_OBJECTS);
816 }
817
818 TDF_Label HYDROData_Document::LabelOfLocalCS() const
819 {
820   return myDoc->Main().FindChild(TAG_LOCAL_CS);
821 }
822
823 void HYDROData_Document::GetLocalCS( double& theLX, double& theLY ) const
824 {
825   TDF_Label aLocalCSLab = LabelOfLocalCS();
826
827   Handle( TDataXtd_Position ) aLocalCS;
828   if( aLocalCSLab.FindAttribute( TDataXtd_Position::GetID(), aLocalCS ) )
829   {
830     gp_Pnt aLocalCS3d = aLocalCS->GetPosition();
831     theLX = aLocalCS3d.X();
832     theLY = aLocalCS3d.Y();
833   }
834   else
835   {
836     theLX = DEFAULT_LOCAL_CS.X();
837     theLY = DEFAULT_LOCAL_CS.Y();
838   }
839 }
840
841 void HYDROData_Document::SetLocalCS( double theLX, double theLY )
842 {
843   UpdateLCSFields();
844
845   // update the local CS data in attribute
846   TDF_Label aLocalCSLab = LabelOfLocalCS();
847   Handle( TDataXtd_Position ) aLocalCS;
848   if( !aLocalCSLab.FindAttribute( TDataXtd_Position::GetID(), aLocalCS ) )
849   {
850     aLocalCS = TDataXtd_Position::Set( aLocalCSLab );
851     aLocalCS->SetID(TDataXtd_Position::GetID());
852   }
853
854   gp_Pnt aLocalCS3d( theLX, theLY, 0 );
855   aLocalCS->SetPosition( aLocalCS3d );
856
857   // calculate delta for coordinates
858   double aDX = myLX - theLX;
859   double aDY = myLY - theLY;
860
861   // update the local CS data in internal fields
862   myLX = theLX;
863   myLY = theLY;
864
865   //update all objects in the document
866   HYDROData_Iterator anIterator( this, KIND_UNKNOWN );
867   for( ; anIterator.More(); anIterator.Next() )
868     anIterator.Current()->UpdateLocalCS( aDX, aDY );
869 }
870
871 void HYDROData_Document::UpdateLCSFields() const
872 {
873   if( myLX >= 0 && myLY >= 0 )
874     return;
875
876   double aLX, aLY;
877   GetLocalCS( aLX, aLY );
878   HYDROData_Document* aThat = const_cast<HYDROData_Document*>( this );
879   aThat->myLX = aLX;
880   aThat->myLY = aLY;
881 }
882
883 void HYDROData_Document::Transform( double& X, double& Y, bool IsToLocalCS ) const
884 {
885   UpdateLCSFields();
886   if( IsToLocalCS )
887   {
888     X -= myLX;
889     Y -= myLY;
890   }
891   else
892   {
893     X += myLX;
894     Y += myLY;
895   }
896 }
897
898 void HYDROData_Document::Transform( gp_Pnt& thePnt, bool IsToLocalCS ) const
899 {
900   double X = thePnt.X();
901   double Y = thePnt.Y();
902   double Z = thePnt.Z();
903   Transform( X, Y, IsToLocalCS );
904   thePnt = gp_Pnt( X, Y, Z ); 
905 }
906
907 void HYDROData_Document::Transform( gp_XYZ& thePnt, bool IsToLocalCS ) const
908 {
909   double X = thePnt.X();
910   double Y = thePnt.Y();
911   double Z = thePnt.Z();
912   Transform( X, Y, IsToLocalCS );
913   thePnt = gp_XYZ( X, Y, Z ); 
914 }
915
916 void HYDROData_Document::Transform( double& X, double& Y, double& Z, bool IsToLocalCS ) const
917 {
918   Transform( X, Y, IsToLocalCS );
919 }
920
921 void HYDROData_Document::Transform( gp_XY& thePnt, bool IsToLocalCS ) const
922 {
923   double X = thePnt.X();
924   double Y = thePnt.Y();
925   Transform( X, Y, IsToLocalCS );
926   thePnt = gp_XY( X, Y ); 
927 }
928
929 HYDROData_InterpolatorsFactory* HYDROData_Document::GetInterpolatorsFactory()
930 {
931   if ( !myInterpolatorsFactory ) {
932     myInterpolatorsFactory = new HYDROData_InterpolatorsFactory();
933   }
934
935   return myInterpolatorsFactory;
936 }
937
938 HYDROData_IProfilesInterpolator* HYDROData_Document::GetInterpolator( const TCollection_AsciiString& theName ) const
939 {
940   HYDROData_IProfilesInterpolator* anInterpolator = NULL;
941
942   HYDROData_Document* aThat = const_cast<HYDROData_Document*>( this );
943   HYDROData_InterpolatorsFactory* aFactory = aThat->GetInterpolatorsFactory();
944   if ( aFactory ) {
945     anInterpolator = aFactory->GetInterpolator( theName );
946   }
947
948   return anInterpolator;
949 }
950  
951 NCollection_Sequence<TCollection_AsciiString> HYDROData_Document::GetInterpolatorNames() const
952 {
953   NCollection_Sequence<TCollection_AsciiString> aNames;
954
955   HYDROData_Document* aThat = const_cast<HYDROData_Document*>( this );
956   HYDROData_InterpolatorsFactory* aFactory = aThat->GetInterpolatorsFactory();
957   if ( aFactory ) {
958     aNames = aFactory->GetInterpolatorNames();
959   }
960
961   return aNames;
962 }
963
964 QColor HYDROData_Document::GetAssociatedColor( const QString& theStricklerType, const Handle(HYDROData_StricklerTable)& theTable ) const
965 {
966   if( !theTable.IsNull() && theTable->HasType( theStricklerType ) )
967     return theTable->GetColor( theStricklerType );
968
969   HYDROData_Iterator anIt( this, KIND_STRICKLER_TABLE );
970   for( ; anIt.More(); anIt.Next() )
971   {
972     Handle(HYDROData_StricklerTable) aTable = Handle(HYDROData_StricklerTable)::DownCast( anIt.Current() );
973     if( aTable->HasType( theStricklerType ) )
974       return aTable->GetColor( theStricklerType );
975   }
976   return QColor();
977 }
978
979 void HYDROData_Document::CollectQGISValues( const QString& theAttrName,
980                                             QStringList& theAttrValues,
981                                             QStringList& theStricklerTypes ) const
982 {
983   HYDROData_Iterator It( this, KIND_STRICKLER_TABLE );
984   for( ; It.More(); It.Next() )
985   {
986     Handle(HYDROData_StricklerTable) aTable = Handle(HYDROData_StricklerTable)::DownCast( It.Current() );
987     if( !aTable.IsNull() && aTable->GetAttrName()==theAttrName )
988     {
989       theAttrValues.clear();
990       theStricklerTypes = aTable->GetTypes();
991       foreach( QString aType, theStricklerTypes )
992       {
993         QString anAttrValue = aTable->GetAttrValue( aType );
994         theAttrValues.append( anAttrValue );
995       }
996     }
997   }
998 }