Salome HOME
c2fb84ce44072adb6247cd0e409838a9c502afcf
[modules/hydro.git] / src / HYDROCurveCreator / CurveCreator_Widget.cxx
1 // Copyright (C) 2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "CurveCreator_Widget.h"
21 #include "CurveCreator_TreeView.h"
22 #include "CurveCreator_ICurve.hxx"
23 //#include "CurveCreator_CurveEditor.hxx"
24 #include "CurveCreator.hxx"
25 //#include "CurveCreator_NewPointDlg.h"
26 #include "CurveCreator_NewSectionDlg.h"
27 #include "CurveCreator_Utils.h"
28 #include "CurveCreator_TableView.h"
29
30 #include <SUIT_Session.h>
31 #include <SUIT_Desktop.h>
32 #include <SUIT_ResourceMgr.h>
33 #include <SUIT_ViewManager.h>
34
35 #include <OCCViewer_ViewWindow.h>
36 #include <OCCViewer_ViewManager.h>
37 #include <OCCViewer_ViewPort3d.h>
38
39 #include <BRep_Tool.hxx>
40 #include <TopoDS.hxx>
41 #include <TopoDS_Vertex.hxx>
42 #include <TopoDS_Wire.hxx>
43 #include <TopoDS_Edge.hxx>
44 #include <gp_Lin.hxx>
45 #include <gp_Dir.hxx>
46 #include <TopExp_Explorer.hxx>
47
48 #include <GeomAPI_ProjectPointOnCurve.hxx>
49
50 #include <AIS_ListOfInteractive.hxx>
51 #include <AIS_ListIteratorOfListOfInteractive.hxx>
52 #include <AIS_Shape.hxx>
53 #include <AIS_Point.hxx>
54 #include <AIS_Line.hxx>
55 #include <Geom_Point.hxx>
56 #include <Geom_BSplineCurve.hxx>
57 #include <Geom_Line.hxx>
58 #include <StdSelect_BRepOwner.hxx>
59
60 #include <QHBoxLayout>
61 #include <QVBoxLayout>
62 #include <QLabel>
63 #include <QLineEdit>
64 #include <QGroupBox>
65 #include <QToolButton>
66 #include <QToolBar>
67 #include <QAction>
68 #include <QMenu>
69 #include <QMouseEvent>
70 #include <QApplication>
71 #include <QTableWidget>
72
73 const double LOCAL_SELECTION_TOLERANCE = 0.0001;
74 const int SECTION_NAME_COLUMN_WIDTH = 75;
75 const int POINT_INDEX_COLUMN_WIDTH = 40;
76
77 const int SCENE_PIXEL_TOLERANCE = 10;
78
79 CurveCreator_Widget::CurveCreator_Widget(QWidget* parent,
80                                          CurveCreator_ICurve *theCurve,
81                                          Qt::WindowFlags fl)
82 : QWidget(parent), myNewSectionEditor(NULL), myCurve(theCurve), mySection(0),
83   myDragStarted( false ), myDragInteractionStyle( SUIT_ViewModel::STANDARD ),
84   myOCCViewer( 0 )
85 {
86   myNewSectionEditor = new CurveCreator_NewSectionDlg( this );
87   myNewSectionEditor->hide();
88   connect( myNewSectionEditor, SIGNAL(addSection()), this, SLOT(onAddNewSection()) );
89   connect( myNewSectionEditor, SIGNAL(modifySection()), this, SLOT(onModifySection()) );
90   connect( myNewSectionEditor, SIGNAL(cancelSection()), this, SLOT(onCancelSection()) );
91
92   QGroupBox* aSectionGroup = new QGroupBox(tr("Sections"),this);
93
94   mySectionView = new CurveCreator_TreeView(myCurve, aSectionGroup);
95   connect( mySectionView, SIGNAL(selectionChanged()), this, SLOT( onSelectionChanged() ) );
96   connect( mySectionView, SIGNAL(sectionEntered(int)), this, SLOT(onEditSection(int)) );
97   connect( mySectionView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onContextMenu(QPoint)) );
98
99   myLocalPointView = new QTableWidget();
100   myLocalPointView->setItemDelegate( new CurveCreator_TableItemDelegate( myLocalPointView ) );
101   myLocalPointView->setVisible( false );
102   myLocalPointView->setColumnCount( 4 );
103   myLocalPointView->setColumnWidth( 0, SECTION_NAME_COLUMN_WIDTH );
104   myLocalPointView->setColumnWidth( 1, POINT_INDEX_COLUMN_WIDTH );
105   QStringList aLabels;
106   //aLabels << tr( "SECTION_LABEL" ) << tr( "IDENTIFIER_LABEL" ) << tr( "X_POSITION_LBL" ) << tr( "Y_POSITION_LBL" );
107   aLabels << tr( "Section" ) << "Index" << tr( "X" ) << tr( "Y" );
108   myLocalPointView->setHorizontalHeaderLabels( aLabels );
109   connect( myLocalPointView, SIGNAL( cellChanged( int, int ) ),
110            this, SLOT( onCellChanged( int, int ) ) );
111
112   QToolBar* aTB = new QToolBar(tr("TOOL_BAR_TLT"), aSectionGroup);
113 //    QToolButton* anUndoBtn = new QToolButton(aTB);
114
115   SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr();
116   QPixmap anUndoPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_UNDO")));
117   QPixmap aRedoPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_REDO")));
118   QPixmap aNewSectionPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_NEW_SECTION")));
119   QPixmap aNewPointPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_NEW_POINT")));
120   QPixmap anEditPointsPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_EDIT_POINTS")));
121   QPixmap aDetectPointsPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_EDIT_POINTS")));
122   QPixmap aPolylinePixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_POLYLINE")));
123   QPixmap aSplinePixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_SPLINE")));
124   QPixmap aRemovePixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_DELETE")));
125   QPixmap aJoinPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_JOIN")));
126   QPixmap aStepUpPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_ARROW_UP")));
127   QPixmap aStepDownPixmap(aResMgr->loadPixmap("GEOM", tr("ICON_CC_ARROW_DOWN")));
128
129   QAction* anAct = createAction( UNDO_ID, tr("UNDO"), anUndoPixmap, tr("UNDO_TLT"), 
130                                  QKeySequence(Qt::ControlModifier|Qt::Key_Z) );
131   connect(anAct, SIGNAL(triggered()), this, SLOT(onUndo()) );
132   aTB->addAction(anAct);
133
134   anAct = createAction( REDO_ID, tr("REDO"), aRedoPixmap, tr("REDO_TLT"), 
135                         QKeySequence(Qt::ControlModifier|Qt::Key_Y) );
136   connect(anAct, SIGNAL(triggered()), this, SLOT(onRedo()) );
137   aTB->addAction(anAct);
138
139   aTB->addSeparator();
140
141   anAct = createAction( NEW_SECTION_ID, tr("NEW_SECTION"), aNewSectionPixmap, tr("NEW_SECTION_TLT"), 
142                         QKeySequence(Qt::ControlModifier|Qt::Key_N) );
143   connect(anAct, SIGNAL(triggered()), this, SLOT(onNewSection()) );
144   aTB->addAction(anAct);
145   aTB->addSeparator();
146
147   anAct = createAction( ADDITION_MODE_ID, tr("ADDITION_MODE"), aNewPointPixmap, tr("ADDITION_MODE_TLT"), 
148                         QKeySequence() );
149   anAct->setCheckable(true);
150   connect(anAct, SIGNAL(triggered(bool)), this, SLOT(onAdditionMode(bool)) );
151   connect(anAct, SIGNAL(toggled(bool)), this, SLOT(onModeChanged(bool)) );
152   aTB->addAction(anAct);
153   
154   anAct = createAction( MODIFICATION_MODE_ID, tr("MODIFICATION_MODE"), anEditPointsPixmap, tr("MODIFICATION_MODE_TLT"), 
155                         QKeySequence() );
156   anAct->setCheckable(true);
157   connect(anAct, SIGNAL(triggered(bool)), this, SLOT(onModificationMode(bool)) );
158   connect(anAct, SIGNAL(toggled(bool)), this, SLOT(onModeChanged(bool)) );
159   aTB->addAction(anAct);
160
161   anAct = createAction( DETECTION_MODE_ID, tr("DETECTION_MODE"), aDetectPointsPixmap, tr("DETECTION_MODE_TLT"), 
162                         QKeySequence() );
163   anAct->setCheckable(true);
164   connect(anAct, SIGNAL(triggered(bool)), this, SLOT(onDetectionMode(bool)) );
165   connect(anAct, SIGNAL(toggled(bool)), this, SLOT(onModeChanged(bool)) );
166   aTB->addAction(anAct);
167
168   anAct = createAction( CLOSE_SECTIONS_ID, tr("CLOSE_SECTIONS"), QPixmap(), tr("CLOSE_SECTIONS_TLT"), 
169                         QKeySequence(Qt::ControlModifier|Qt::Key_W) );
170   connect(anAct, SIGNAL(triggered()), this, SLOT(onCloseSections()) );
171
172   anAct = createAction( UNCLOSE_SECTIONS_ID, tr("UNCLOSE_SECTIONS"), QPixmap(), 
173                         tr("UNCLOSE_SECTIONS_TLT"), QKeySequence(Qt::ControlModifier|Qt::Key_S) );
174   connect(anAct, SIGNAL(triggered()), this, SLOT(onUncloseSections()) );
175
176   anAct = createAction( SET_SECTIONS_POLYLINE_ID, tr("SET_SECTIONS_POLYLINE"), 
177                         aPolylinePixmap, tr("SET_POLYLINE_TLT"), 
178                         QKeySequence(Qt::ControlModifier|Qt::Key_E) );
179   connect(anAct, SIGNAL(triggered()), this, SLOT(onSetPolyline()) );
180
181   anAct = createAction( SET_SECTIONS_SPLINE_ID, tr("SET_SECTIONS_SPLINE"), aSplinePixmap, 
182                         tr("SET_SPLINE_TLT"), QKeySequence(Qt::ControlModifier|Qt::Key_R) );
183   connect(anAct, SIGNAL(triggered()), this, SLOT(onSetSpline()) );
184
185   anAct = createAction( REMOVE_ID, tr("REMOVE"), aRemovePixmap, tr("REMOVE_TLT"), 
186                         QKeySequence(Qt::ControlModifier|Qt::Key_Delete ) );
187   connect(anAct, SIGNAL(triggered()), this, SLOT(onRemove()) );
188   aTB->addAction(anAct);
189   // TODO join
190   //aTB->addSeparator();
191
192   //anAct = createAction( JOIN_ID, tr("JOIN"), aJoinPixmap, tr("JOIN_TLT"), 
193   //                      QKeySequence(Qt::ControlModifier|Qt::Key_Plus ) );
194   //connect( anAct, SIGNAL(triggered()), this, SLOT(onJoin()) );
195   //aTB->addAction(anAct);
196
197   anAct = createAction( CLEAR_ALL_ID, tr("CLEAR_ALL"), QPixmap(), tr("CLEAR_ALL_TLT"), 
198                         QKeySequence(Qt::ControlModifier | Qt::ShiftModifier | Qt::Key_Delete ) );
199   connect( anAct, SIGNAL(triggered()), this, SLOT( onClearAll()) );
200
201   // TODO join
202   //anAct = createAction( JOIN_ALL_ID, tr("JOIN_ALL"), QPixmap(), tr("JOIN_ALL_TLT"), 
203   //                      QKeySequence(Qt::ControlModifier | Qt::ShiftModifier | Qt::Key_Plus ) );
204   //connect( anAct, SIGNAL(triggered()), this, SLOT(onJoinAll()) );
205
206   QVBoxLayout* aSectLayout = new QVBoxLayout();
207   aSectLayout->setMargin( 5 );
208   aSectLayout->setSpacing( 5 );
209   aSectLayout->addWidget(aTB);
210   aSectLayout->addWidget(mySectionView);
211   aSectLayout->addWidget( myLocalPointView );
212   aSectionGroup->setLayout(aSectLayout);
213   QVBoxLayout* aLay = new QVBoxLayout();
214   aLay->setMargin( 0 );
215   aLay->setSpacing( 5 );
216 //    aLay->addLayout(aNameLayout);
217   aLay->addWidget(aSectionGroup);
218   setLayout(aLay);
219   onSelectionChanged();
220 }
221
222 /**
223  * Set an OCC viewer
224  */
225 void CurveCreator_Widget::setOCCViewer( OCCViewer_Viewer* theViewer )
226 {
227   if ( myOCCViewer == theViewer )
228     return;
229
230   if ( myOCCViewer ) {
231     OCCViewer_ViewManager* aViewManager = dynamic_cast<OCCViewer_ViewManager*>
232                                                     ( myOCCViewer->getViewManager() );
233     disconnect( aViewManager, SIGNAL( mousePress( SUIT_ViewWindow*, QMouseEvent* ) ),
234            this, SLOT( onMousePress( SUIT_ViewWindow*, QMouseEvent* ) ) );
235     disconnect( aViewManager, SIGNAL( mouseRelease( SUIT_ViewWindow*, QMouseEvent* ) ),
236            this, SLOT( onMouseRelease( SUIT_ViewWindow*, QMouseEvent* ) ) );
237     disconnect( aViewManager, SIGNAL( mouseMove( SUIT_ViewWindow*, QMouseEvent* ) ),
238            this, SLOT( onMouseMove( SUIT_ViewWindow*, QMouseEvent* ) ) );
239     // all local contexts should be closed if the viewer is not more used
240     setLocalPointContext( false, true );
241   }
242
243   myOCCViewer = theViewer;
244   if ( myOCCViewer ) {
245     OCCViewer_ViewManager* aViewManager = dynamic_cast<OCCViewer_ViewManager*>
246                                                     ( myOCCViewer->getViewManager() );
247     connect( aViewManager, SIGNAL( mousePress( SUIT_ViewWindow*, QMouseEvent* ) ),
248            this, SLOT( onMousePress( SUIT_ViewWindow*, QMouseEvent* ) ) );
249     connect( aViewManager, SIGNAL( mouseRelease( SUIT_ViewWindow*, QMouseEvent* ) ),
250            this, SLOT( onMouseRelease( SUIT_ViewWindow*, QMouseEvent* ) ) );
251     connect( aViewManager, SIGNAL( mouseMove( SUIT_ViewWindow*, QMouseEvent* ) ),
252            this, SLOT( onMouseMove( SUIT_ViewWindow*, QMouseEvent* ) ) );
253   }
254 }
255
256 /**
257  * Returns current OCC viewer
258  */
259 OCCViewer_Viewer* CurveCreator_Widget::getOCCViewer()
260 {
261   return myOCCViewer;
262 }
263
264 //=======================================================================
265 // function: getUniqSectionName
266 // purpose: return unique section name
267 //=======================================================================
268 std::string CurveCreator_Widget::getUniqSectionName( CurveCreator_ICurve* theCurve ) const
269 {
270   for( int i = 0 ; i < 1000000 ; i++ ){
271       char aBuffer[255];
272       sprintf( aBuffer, "Section_%d", i+1 );
273       std::string aName(aBuffer);
274       int j;
275       for( j = 0 ; j < theCurve->getNbSections() ; j++ ){
276         if( theCurve->getSectionName(j) == aName )
277             break;
278       }
279       if( j == theCurve->getNbSections() )
280           return aName;
281   }
282   return "";
283 }
284
285 void CurveCreator_Widget::setCurve( CurveCreator_ICurve* theCurve )
286 {
287   myCurve = theCurve;
288   mySectionView->setCurve(myCurve);
289   onSelectionChanged();
290   updateUndoRedo();
291 }
292
293 void CurveCreator_Widget::onSelectionChanged()
294 {
295   QList<ActionId> anEnabledAct;
296   if( myCurve ){
297     anEnabledAct << NEW_SECTION_ID << MODIFICATION_MODE_ID;
298     if ( removeEnabled() )
299       anEnabledAct << REMOVE_ID;
300     QList<int> aSelSections = mySectionView->getSelectedSections();
301     QList< QPair< int, int > > aSelPoints = mySectionView->getSelectedPoints();
302     CurveCreator_TreeView::SelectionType aSelType = mySectionView->getSelectionType();
303     switch( aSelType ){
304     case CurveCreator_TreeView::ST_NOSEL:{
305       break;
306     }
307     case CurveCreator_TreeView::ST_SECTIONS:{
308       /*if( aSelSections[0] > 0 ){
309         anEnabledAct << UP_ID;
310       }*/
311       if( aSelSections.size() == 1 ){
312         anEnabledAct << ADDITION_MODE_ID << DETECTION_MODE_ID;
313       }
314       switch ( getActionMode() ) {
315         case AdditionMode: {
316           mySection = -1;
317           myPointNum = -1;
318           QList<int> aSelSection = mySectionView->getSelectedSections();
319           if( aSelSection.size() > 0 ){
320             mySection = aSelSection[0];
321             myPointNum = myCurve->getNbPoints(mySection);
322           }
323         }
324         break;
325         case ModificationMode: {
326          anEnabledAct << CLOSE_SECTIONS_ID << UNCLOSE_SECTIONS_ID << SET_SECTIONS_POLYLINE_ID << SET_SECTIONS_SPLINE_ID;
327           int aSectCnt = myCurve->getNbSections();
328           if( aSectCnt > 0 )
329             anEnabledAct << CLEAR_ALL_ID;
330           // TODO
331           //if( aSectCnt > 1 )
332           //  anEnabledAct << JOIN_ALL_ID;
333           //if( aSelSections.size() > 1 ){
334           //  anEnabledAct << JOIN_ID;
335           //}
336         }
337         break;
338         case DetectionMode: {
339         }
340         break;
341         case NoneMode:
342         default:
343         break;
344       }
345       /*if( aSelSections[ aSelSections.size() - 1 ] < ( myCurve->getNbSections() - 1 ) ){
346         anEnabledAct << DOWN_ID;
347       }*/
348       break;
349     }
350     /*case CurveCreator_TreeView::ST_POINTS_ONE_SECTION:{
351       if( aSelPoints[0].second > 0 ){
352         anEnabledAct << UP_ID;
353       }
354       int aLastIndex = aSelPoints.size()-1;
355       int aSect = aSelPoints[0].first;
356       if( aSelPoints[aLastIndex].second < (myCurve->getNbPoints(aSect) - 1)){
357         anEnabledAct << DOWN_ID;
358       }
359       if( aSelPoints.size() == 1){
360         anEnabledAct << INSERT_POINT_BEFORE_ID << INSERT_POINT_AFTER_ID;
361       }
362       break;
363     }*/
364
365     }
366     
367     /*int aSelObjsCnt = aSelPoints.size() + aSelSections.size();
368     if( aSelObjsCnt > 0 ){
369       anEnabledAct << REMOVE_ID;
370     }
371     if( (myCurve->getNbSections() + myCurve->getNbPoints()) > 0 ){
372       anEnabledAct << REMOVE_ALL_ID;
373     }*/
374     // TODO
375     //if( myCurve->getNbSections() > 1 ){
376     //  anEnabledAct << JOIN_ALL_ID;
377     //}
378   }
379   QList<ActionId> anIds = myActionMap.keys();
380   for( int i = 0 ; i < anIds.size() ; i++ ){
381     if( myActionMap.contains(anIds[i]) ){
382       if( anEnabledAct.contains(anIds[i]) ){
383         myActionMap[anIds[i]]->setEnabled(true);
384       }
385       else{
386         myActionMap[anIds[i]]->setEnabled(false);
387       }
388     }
389   }
390   updateUndoRedo();
391   emit selectionChanged();
392 }
393
394 void CurveCreator_Widget::onAdditionMode(bool checked)
395 {
396   OCCViewer_Viewer* aViewer = getOCCViewer();
397   if( !myCurve || !aViewer )
398     return;
399
400   Handle(AIS_InteractiveContext) aContext = aViewer->getAISContext();
401   OCCViewer_ViewManager* aViewManager = dynamic_cast<OCCViewer_ViewManager*>
402                                                     (aViewer->getViewManager());
403 //  if ( aViewManager->getType() == OCCViewer_Viewer::Type() ) {
404   if( aViewer ) {
405     if (checked) {
406 /*      myGuiState = aViewWindow->saveState();
407       aViewer->enableMultiselection(false);
408       aViewer->enableSelection(false);*/
409     } else {
410 /*      aViewer->enableMultiselection(true);
411       aViewer->enableSelection(true);
412       aViewWindow->restoreState( myGuiState );*/
413       return;
414     }
415   }
416
417   mySection= -1;
418   myPointNum = -1;
419   QList<int> aSelSection = mySectionView->getSelectedSections();
420   if( aSelSection.size() > 0 ){
421     mySection = aSelSection[0];
422   }
423   else{
424     QList< QPair<int,int> > aSelPoints = mySectionView->getSelectedPoints();
425     if( aSelPoints.size() > 0 ){
426       mySection = aSelPoints[0].first;
427       myPointNum = aSelPoints[0].second + 1;
428     }
429   }
430 //  emit subOperationStarted( myNewPointEditor );
431 }
432
433 void CurveCreator_Widget::onModificationMode(bool checked)
434 {
435   myLocalPointView->setVisible( checked );
436 }
437
438 void CurveCreator_Widget::onDetectionMode(bool checked)
439 {
440 }
441
442 void CurveCreator_Widget::onModeChanged(bool checked)
443 {
444   ActionMode aMode = NoneMode;
445   if (checked) {
446     QAction* anAction = (QAction*)sender();
447     switch(myActionMap.key(anAction)) {
448       case ADDITION_MODE_ID:
449         aMode = AdditionMode;
450         if (myActionMap[MODIFICATION_MODE_ID]->isChecked())
451           myActionMap[MODIFICATION_MODE_ID]->trigger();
452         else if (myActionMap[DETECTION_MODE_ID]->isChecked())
453           myActionMap[DETECTION_MODE_ID]->trigger();
454         break;
455       case MODIFICATION_MODE_ID:
456         aMode = ModificationMode;
457         if (myActionMap[ADDITION_MODE_ID]->isChecked())
458           myActionMap[ADDITION_MODE_ID]->trigger();
459         else if (myActionMap[DETECTION_MODE_ID]->isChecked())
460           myActionMap[DETECTION_MODE_ID]->trigger();
461         break;
462       case DETECTION_MODE_ID:
463         aMode = DetectionMode;
464         if (myActionMap[ADDITION_MODE_ID]->isChecked())
465           myActionMap[ADDITION_MODE_ID]->trigger();
466         else if (myActionMap[MODIFICATION_MODE_ID]->isChecked())
467           myActionMap[MODIFICATION_MODE_ID]->trigger();
468         break;
469     }
470   }
471   onSelectionChanged();
472   setLocalPointContext( aMode == ModificationMode, true );
473 }
474
475 void CurveCreator_Widget::onAddNewPoint(const CurveCreator::Coordinates& theCoords)
476 {
477   if( !myCurve )
478     return;
479   //myCurve->addPoints(theCoords, mySection, myPointNum );
480   //mySectionView->pointsAdded( mySection, myPointNum );
481   //myPointNum++;
482   QList<int> aSections = mySectionView->getSelectedSections();
483   if( aSections.size() == 0 ){
484     return;
485   }
486   int aSection = aSections[0];
487   myCurve->addPoints(theCoords, aSection); // add to the end of section
488   mySectionView->pointsAdded( aSection, myCurve->getNbPoints( aSection ) );
489   onSelectionChanged();
490   updateUndoRedo();
491 }
492
493 void CurveCreator_Widget::onNewSection()
494 {
495   if( !myCurve )
496     return;
497   myNewSectionEditor->clear();
498   myNewSectionEditor->setEditMode(false);
499   QString aSectName = QString( getUniqSectionName(myCurve).c_str() );
500   myNewSectionEditor->setSectionParameters(aSectName, true, CurveCreator::Polyline );
501   emit subOperationStarted( myNewSectionEditor );
502 }
503
504 void CurveCreator_Widget::onAddNewSection()
505 {
506   if( !myCurve )
507     return;
508   myCurve->addSection( myNewSectionEditor->getName().toStdString(), myNewSectionEditor->getSectionType(),
509                       myNewSectionEditor->isClosed() );
510   mySectionView->sectionAdded( -1 ); // add a new section to the end of list
511   QString aNewName = QString(getUniqSectionName(myCurve).c_str());
512   myNewSectionEditor->setSectionName(aNewName);
513   onSelectionChanged();
514   updateUndoRedo();
515   onCancelSection();
516 }
517
518 void CurveCreator_Widget::onCancelSection()
519 {
520   emit subOperationFinished( myNewSectionEditor );
521 }
522
523 QAction* CurveCreator_Widget::createAction( ActionId theId, const QString& theName, const QPixmap& theImage,
524                                             const QString& theToolTip, const QKeySequence& theShortcut )
525 {
526   QAction* anAct = new QAction(theName,this);
527   if( !theImage.isNull() ){
528     anAct->setIcon(theImage);
529   }
530   anAct->setShortcut(theShortcut);
531   anAct->setToolTip(theToolTip);
532   myActionMap[theId] = anAct;
533   return anAct;
534 }
535
536 QAction* CurveCreator_Widget::getAction(ActionId theId)
537 {
538   if( myActionMap.contains(theId) )
539     return myActionMap[theId];
540   return NULL;
541 }
542
543 CurveCreator_Widget::ActionMode CurveCreator_Widget::getActionMode() const
544 {
545   ActionMode aMode = NoneMode;
546
547   if ( myActionMap[ADDITION_MODE_ID]->isChecked() )
548     aMode = AdditionMode;
549   else if ( myActionMap[MODIFICATION_MODE_ID]->isChecked() )
550     aMode = ModificationMode;
551   else if ( myActionMap[DETECTION_MODE_ID]->isChecked() )
552     aMode = DetectionMode;
553
554   return aMode;
555 }
556
557 void CurveCreator_Widget::onEditSection( int theSection )
558 {
559   if( !myCurve )
560     return;
561   mySection = theSection;
562   QString aSectName = QString::fromStdString( myCurve->getSectionName(theSection));
563   bool isClosed = myCurve->isClosed(theSection);
564   CurveCreator::SectionType aType = myCurve->getSectionType(theSection);
565   myNewSectionEditor->setEditMode(true);
566   myNewSectionEditor->setSectionParameters( aSectName, isClosed, aType );
567
568   emit subOperationStarted( myNewSectionEditor );
569 }
570
571 void CurveCreator_Widget::onModifySection()
572 {
573   if( !myCurve )
574     return;
575   QString aName = myNewSectionEditor->getName();
576   bool isClosed = myNewSectionEditor->isClosed();
577   CurveCreator::SectionType aSectType = myNewSectionEditor->getSectionType();
578 //  myCurve->startOperation();
579   if( myCurve->getSectionName(mySection) != aName.toStdString() )
580     myCurve->setSectionName( mySection , aName.toStdString() );
581
582   if( myCurve->getSectionType(mySection) != aSectType )
583     myCurve->setSectionType( mySection, aSectType );
584
585   if( myCurve->isClosed(mySection) != isClosed )
586     myCurve->setClosed( mySection, isClosed );
587 //  myCurve->finishOperation();
588   mySectionView->sectionChanged(mySection);
589   updateUndoRedo();
590   onCancelSection();
591 }
592
593 /*void CurveCreator_Widget::onEditPoint( int theSection, int thePoint )
594 {
595   if( !myNewPointEditor || !myEdit )
596     return;
597   mySection = theSection;
598   myPointNum = thePoint;
599   QString aSectName = QString::fromStdString( myCurve->getSectionName(theSection));
600   myNewPointEditor->setEditMode(true);
601   myNewPointEditor->setSectionName(aSectName);
602   myNewPointEditor->setDimension( myCurve->getDimension() );
603   CurveCreator::Coordinates aCoords = myCurve->getCoordinates(theSection,thePoint);
604   myNewPointEditor->setCoordinates(aCoords);
605   emit subOperationStarted( myNewPointEditor );
606 }
607
608 void CurveCreator_Widget::onModifyPoint()
609 {
610   if( !myEdit )
611     return;
612   CurveCreator::Coordinates aCoords = myNewPointEditor->getCoordinates();
613   myEdit->setCoordinates( aCoords, mySection, myPointNum );
614   mySectionView->pointDataChanged( mySection, myPointNum );
615   updateUndoRedo();
616   onCancelPoint();
617 }*/
618
619 void CurveCreator_Widget::onJoin()
620 {
621   if( !myCurve )
622     return;
623   QList<int> aSections = mySectionView->getSelectedSections();
624   if( aSections.size() == 0 ){
625     return;
626   }
627   int aMainSect = aSections[0];
628   int aMainSectSize = myCurve->getNbPoints(aMainSect);
629 //  myCurve->startOperation();
630   for( int i = 1 ; i < aSections.size() ; i++ ){
631     int aSectNum = aSections[i] - (i-1);
632     myCurve->join( aMainSect, aSectNum );
633     mySectionView->sectionsRemoved( aSectNum );
634   }
635 //  myCurve->finishOperation();
636   int aNewSectSize = myCurve->getNbPoints(aMainSect);
637   if( aNewSectSize != aMainSectSize )
638     mySectionView->pointsAdded( aMainSect, aMainSectSize, aNewSectSize-aMainSectSize );
639   updateUndoRedo();
640 }
641
642 void CurveCreator_Widget::onRemove()
643 {
644   if( !myCurve )
645     return;
646
647   switch( getActionMode() ) {
648     case NoneMode:
649       removeSection();
650     break;
651     case ModificationMode:
652       removePoint();
653     break;
654     default:
655       break;
656   }
657 }
658
659 void CurveCreator_Widget::onClearAll()
660 {
661   if( !myCurve )
662     return;
663   myCurve->clear();
664   mySectionView->reset();
665   onSelectionChanged();
666   updateUndoRedo();
667 }
668
669 void CurveCreator_Widget::onJoinAll()
670 {
671   if( !myCurve )
672     return;
673   myCurve->join();
674   mySectionView->reset();
675   onSelectionChanged();
676   updateUndoRedo();
677 }
678
679 void CurveCreator_Widget::onUndoSettings()
680 {
681
682 }
683
684 void CurveCreator_Widget::onSetSpline()
685 {
686   if( !myCurve )
687     return;
688   QList<int> aSelSections = mySectionView->getSelectedSections();
689 //  myCurve->startOperation();
690   for( int i = 0 ; i < aSelSections.size() ; i++ ){
691     myCurve->setSectionType(aSelSections[i], CurveCreator::Spline );
692     mySectionView->sectionChanged(aSelSections[i]);
693   }
694 //  myCurve->finishOperation();
695   updateUndoRedo();
696 }
697
698 void CurveCreator_Widget::onSetPolyline()
699 {
700   if( !myCurve )
701     return;
702 //  myCurve->startOperation();
703   QList<int> aSelSections = mySectionView->getSelectedSections();
704   for( int i = 0 ; i < aSelSections.size() ; i++ ){
705     myCurve->setSectionType( aSelSections[i], CurveCreator::Polyline );
706     mySectionView->sectionChanged( aSelSections[i] );
707   }
708 //  myCurve->finishOperation();
709   updateUndoRedo();
710 }
711
712 void CurveCreator_Widget::onCloseSections()
713 {
714   if( !myCurve )
715     return;
716 //  myCurve->startOperation();
717   QList<int> aSelSections = mySectionView->getSelectedSections();
718   for( int i = 0 ; i < aSelSections.size() ; i++ ){
719     myCurve->setClosed(aSelSections[i], true);
720     mySectionView->sectionChanged(aSelSections[i]);
721   }
722 //  myCurve->finishOperation();
723   updateUndoRedo();
724 }
725
726 void CurveCreator_Widget::onUncloseSections()
727 {
728   if( !myCurve )
729     return;
730 //  myCurve->startOperation();
731   QList<int> aSelSections = mySectionView->getSelectedSections();
732   for( int i = 0 ; i < aSelSections.size() ; i++ ){
733     myCurve->setClosed(aSelSections[i], false);
734     mySectionView->sectionChanged(aSelSections[i]);
735   }
736 //  myCurve->finishOperation();
737   updateUndoRedo();
738 }
739
740 void CurveCreator_Widget::onUndo()
741 {
742     if( !myCurve )
743       return;
744
745     CurveCreator_Widget::SectionToPointList aPoints;
746     startCurveModification( aPoints, false );
747     myCurve->undo();
748     finishCurveModification();
749     mySectionView->reset();
750 }
751
752 void CurveCreator_Widget::onRedo()
753 {
754     if( !myCurve )
755       return;
756     CurveCreator_Widget::SectionToPointList aPoints;
757     startCurveModification( aPoints, false );
758     myCurve->redo();
759     finishCurveModification();
760     mySectionView->reset();
761 }
762
763 void CurveCreator_Widget::updateUndoRedo()
764 {
765   if( !myCurve )
766     return;
767   QAction* anAct = myActionMap[UNDO_ID];
768   if( anAct != 0 ){
769     if( myCurve->getNbUndo() != 0 ){
770       anAct->setEnabled(true);
771     }
772     else{
773       anAct->setDisabled(true);
774     }
775   }
776   anAct = myActionMap[REDO_ID];
777   if( anAct != 0 ){
778     if( myCurve->getNbRedo() != 0 ){
779       anAct->setEnabled(true);
780     }
781     else{
782       anAct->setDisabled(true);
783     }
784   }
785 }
786
787 void CurveCreator_Widget::onContextMenu( QPoint thePoint )
788 {
789   QList<ActionId> aContextActions;
790   aContextActions << CLEAR_ALL_ID << JOIN_ALL_ID << SEPARATOR_ID <<
791                      CLOSE_SECTIONS_ID << UNCLOSE_SECTIONS_ID << SET_SECTIONS_POLYLINE_ID <<
792                      SET_SECTIONS_SPLINE_ID;
793   QPoint aGlPoint = mySectionView->mapToGlobal(thePoint);
794   bool isVis = false;
795   QList<ActionId> aResAct;
796   for( int i = 0 ; i < aContextActions.size() ; i++ ){
797     if( aContextActions[i] != SEPARATOR_ID ){
798       if( myActionMap.contains(aContextActions[i]) ){
799         QAction* anAct = myActionMap[aContextActions[i]];
800         if( anAct->isEnabled() ){
801           aResAct << aContextActions[i];
802           isVis = true;
803         }
804       }
805     }
806     else{
807       aResAct << SEPARATOR_ID;
808     }
809   }
810   if( !isVis )
811     return;
812
813   QMenu* aMenu = new QMenu(this);
814   for( int i = 0 ; i < aResAct.size() ; i++ ){
815     if( aResAct[i] == SEPARATOR_ID ){
816       aMenu->addSeparator();
817     }
818     else{
819       QAction* anAct = myActionMap[aResAct[i]];
820       aMenu->insertAction(NULL, anAct);
821     }
822   }
823   aMenu->exec(aGlPoint);
824 }
825
826 QList<int> CurveCreator_Widget::getSelectedSections()
827 {
828   return mySectionView->getSelectedSections();
829 }
830
831 QList< QPair< int, int > > CurveCreator_Widget::getSelectedPoints()
832 {
833   return mySectionView->getSelectedPoints();
834 }
835
836 /**
837  * According to the widget state, performs the remove action
838  */
839 void CurveCreator_Widget::removeSelected()
840 {
841   onRemove();
842 }
843
844 /**
845  * Checks whether there are some selection to be removed
846  */
847 bool CurveCreator_Widget::removeEnabled()
848 {
849   bool isEnabled = getActionMode() == ModificationMode;
850   if ( !isEnabled ) {
851     QList<int> aSelSections = mySectionView->getSelectedSections();
852     CurveCreator_TreeView::SelectionType aSelType = mySectionView->getSelectionType();
853     isEnabled = aSelType == CurveCreator_TreeView::ST_SECTIONS &&
854                 aSelSections.size() == 1;
855   }
856   return isEnabled;
857 }
858
859
860 //=================================================================================
861 // function : GeometryGUI::onGetCoordsByClick()
862 // purpose  : Manage mouse press events in Additon mode
863 //=================================================================================
864 void CurveCreator_Widget::onGetCoordsByClick( QMouseEvent* pe )
865 {
866   if (pe->button() != Qt::LeftButton)
867     return;
868
869   if ( pe->modifiers() != Qt::ControlModifier ) {
870   OCCViewer_Viewer* aViewer = getOCCViewer();
871   if ( !aViewer )
872     return;
873     Handle(AIS_InteractiveContext) ic = aViewer->getAISContext();
874
875     gp_Pnt aPnt;    
876
877     ic->InitSelected();
878     if ( pe->modifiers() == Qt::ShiftModifier )
879       ic->ShiftSelect();  // Append selection
880     else
881       ic->Select();       // New selection
882
883     /*TopoDS_Shape aShape;
884
885     ic->InitSelected();
886     if ( ic->MoreSelected() )
887       aShape = ic->SelectedShape();
888
889     if ( !aShape.IsNull() && aShape.ShapeType() == TopAbs_VERTEX )
890       aPnt = BRep_Tool::Pnt( TopoDS::Vertex( ic->SelectedShape() ) );
891     else*/
892     {
893       OCCViewer_ViewPort3d* vp =
894         ((OCCViewer_ViewWindow*)aViewer->getViewManager()->getActiveView())->getViewPort();
895       aPnt = CurveCreator_Utils::ConvertClickToPoint( pe->x(), pe->y(), vp->getView() );
896     }
897     // set the coordinates into dialog
898     CurveCreator::Coordinates aCoords;
899     aCoords.push_back( aPnt.X() );
900     aCoords.push_back( aPnt.Y() );
901     if ( myCurve->getDimension() == 3 ) {
902       aCoords.push_back( aPnt.Z() );
903     }
904     onAddNewPoint(aCoords);
905 //    myNewPointEditor->setCoordinates( aCoords );
906   }
907 }
908
909 //=================================================================================
910 // function : CurveCreator_Widget::onMousePress()
911 // purpose  : Manage mouse press events in Modification mode
912 //=================================================================================
913 void CurveCreator_Widget::onMousePress( SUIT_ViewWindow*, QMouseEvent* theEvent )
914 {
915   if ( theEvent->button() != Qt::LeftButton )
916     return;
917
918   switch( getActionMode() ) {
919     case ModificationMode: {
920       //store initial cursor position for Drag&Drop
921       setDragStarted( true, theEvent->pos() );
922       break;
923     }
924     case AdditionMode: {
925       onGetCoordsByClick( theEvent );
926       break;
927     }
928     default:
929       break;
930   }
931 }
932
933 //=================================================================================
934 // function : HYDROGUI_PolylineOp::onMouseRelease()
935 // purpose  : Manage mouse press events in Modification mode
936 //=================================================================================
937 void CurveCreator_Widget::onMouseRelease( SUIT_ViewWindow*, QMouseEvent* theEvent )
938 {
939   if ( getActionMode() != ModificationMode )
940     return;
941
942   if ( myDragStarted ) {
943     if ( myDragged ) // if the drag of some points has happened, restore the drag selection
944       setSelectedPonts( myDragPoints );
945     setDragStarted( false );
946   }
947   else // check whether the segment is clicked an a new point should be added to the segment
948     insertPointToSelectedSegment( theEvent->pos().x(), theEvent->pos().y() );
949
950   // updates the input panel table to show the selected point coordinates
951   updateLocalPointView();
952 }
953
954 //=================================================================================
955 // function : GeometryGUI::onMouseMove()
956 // purpose  : Manage mouse move events in Modification mode
957 //=================================================================================
958 void CurveCreator_Widget::onMouseMove( SUIT_ViewWindow*, QMouseEvent* theEvent )
959 {
960   if ( getActionMode() != ModificationMode || !myDragStarted )
961     return;
962
963   QPoint aPos = theEvent->pos();
964   if ( (aPos - myDragStartPosition).manhattanLength() < QApplication::startDragDistance() )
965     return;
966
967   moveSelectedPoints( aPos.x(), aPos.y() );
968   myDragStartPosition = aPos;
969 }
970
971 void CurveCreator_Widget::onCellChanged( int theRow, int theColumn )
972 {
973   int aCurrSect = getSectionId( theRow );
974   int aPntIndex = getPointId( theRow );
975
976   if ( aPntIndex < 0 )
977     return;
978
979   SectionToPointList aSelPoints;
980   startCurveModification( aSelPoints );
981
982   double aX  = myLocalPointView->item( theRow, 2 )->data( Qt::UserRole ).toDouble();
983   double anY = myLocalPointView->item( theRow, 3 )->data( Qt::UserRole ).toDouble();
984   std::deque<float> aChangedPos;
985   aChangedPos.push_back( aX );
986   aChangedPos.push_back( anY );
987   myCurve->setPoint( aCurrSect, aPntIndex, aChangedPos );
988
989   finishCurveModification( aSelPoints );
990 }
991
992 /**
993  * Removes a selected section from the curve. Updates undo/redo status
994  */
995 void CurveCreator_Widget::removeSection()
996 {
997   QList< QPair<int,int> > aSelPoints = mySectionView->getSelectedPoints();
998   int aCurrSect=-1;
999   int aRemoveCnt = 0;
1000 //  myCurve->startOperation();
1001   for( int i = 0 ; i < aSelPoints.size() ; i++ ){
1002     if( aCurrSect != aSelPoints[i].first ){
1003       aRemoveCnt = 0;
1004       aCurrSect = aSelPoints[i].first;
1005     }
1006     int aPntIndx = aSelPoints[i].second - aRemoveCnt;
1007     myCurve->removePoint( aCurrSect, aPntIndx );
1008     mySectionView->pointsRemoved( aCurrSect, aPntIndx );
1009     aRemoveCnt++;
1010   }
1011   QList<int> aSections = mySectionView->getSelectedSections();
1012   for( int i = 0 ; i < aSections.size() ; i++ ){
1013     int aSectNum = aSections[i] - (i);
1014     myCurve->removeSection( aSectNum );
1015     mySectionView->sectionsRemoved( aSectNum );
1016   }
1017 //  myCurve->finishOperation();
1018   mySectionView->clearSelection();
1019   updateUndoRedo();
1020 }
1021
1022 /**
1023  * Removes a selected points from the curve. Updates undo/redo status
1024  */
1025 void CurveCreator_Widget::removePoint()
1026 {
1027   SectionToPointList aPoints;
1028   getSelectedPonts( aPoints );
1029   if ( aPoints.size() == 0 )
1030     return;
1031
1032   SectionToPointList aSelPoints;
1033   startCurveModification( aSelPoints, false );
1034
1035   myCurve->removeSeveralPoints( aPoints );
1036   finishCurveModification( SectionToPointList() );
1037 }
1038
1039 void CurveCreator_Widget::insertPointToSelectedSegment( const int theX,
1040                                                         const int theY )
1041 {
1042   OCCViewer_Viewer* aViewer = getOCCViewer();
1043   if ( !aViewer )
1044     return;
1045
1046   gp_Pnt aPoint;
1047   gp_Pnt aPoint1, aPoint2;
1048   bool isFoundPoint = false;
1049   Handle(AIS_InteractiveContext) aContext = aViewer->getAISContext();
1050   for ( aContext->InitSelected(); aContext->MoreSelected() && !isFoundPoint;
1051         aContext->NextSelected() ) {
1052     TopoDS_Shape aTShape = aContext->SelectedShape();
1053     if ( !aTShape.IsNull() && aTShape.ShapeType() == TopAbs_VERTEX )
1054       continue;
1055     else {
1056       Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1057       if ( anOwner.IsNull() )
1058         continue;
1059       const TopLoc_Location& aLocation = anOwner->Location();
1060       Handle(AIS_InteractiveObject) anAIS = Handle(AIS_InteractiveObject)::DownCast( anOwner->Selectable() );
1061       isFoundPoint = pointOnObject( anAIS, theX, theY, aPoint, aPoint1, aPoint2 );
1062     }
1063   }
1064   if ( !isFoundPoint )
1065     return;
1066
1067   // insert the point to the model curve
1068   SectionToPointList aSelPoints;
1069   startCurveModification( aSelPoints );
1070
1071   CurveCreator::Coordinates aCoords;
1072   aCoords.push_back( aPoint.X() );
1073   aCoords.push_back( aPoint.Y() );
1074
1075   SectionToPointList aPoints1, aPoints2;
1076   findSectionsToPoints( aPoint1.X(), aPoint1.Y(), aPoints1 );
1077   findSectionsToPoints( aPoint2.X(), aPoint2.Y(), aPoints2 );
1078   SectionToPointList::const_iterator anIt = aPoints1.begin(), aLast = aPoints1.end();
1079   int aSectionId = -1;
1080   // there can be a case when a new point is added into two sections
1081   int aPoint1Id = -1, aPoint2Id = -1;
1082   for ( ; anIt != aLast && aSectionId < 0; anIt++ ) {
1083     int aSectionCur = anIt->first;
1084     SectionToPointList::const_iterator anIt2 = aPoints2.begin(), aLast2 = aPoints2.end();
1085     for ( ; anIt2 != aLast2 && aSectionId < 0; anIt2++ ) {
1086       if ( anIt2->first == aSectionCur ) {
1087         aSectionId = aSectionCur;
1088         aPoint1Id = anIt->second;
1089         aPoint2Id = anIt2->second;
1090       }
1091     }
1092   }
1093
1094   int anInsertPos = -1;
1095   int aLastPoint = myCurve->getNbPoints( aSectionId )-1; 
1096   if ( ( aPoint1Id == aLastPoint && aPoint2Id == 0 ) ||
1097        ( aPoint2Id == aLastPoint && aPoint1Id == 0 ) )
1098     anInsertPos = -1; // if the section happens between first and last points
1099   else
1100     anInsertPos = aPoint1Id < aPoint2Id ? aPoint1Id + 1 : aPoint2Id + 1;
1101
1102   myCurve->addPoints( aCoords, aSectionId, anInsertPos );
1103   mySectionView->pointsAdded( aSectionId, myCurve->getNbPoints( aSectionId ) );
1104
1105   finishCurveModification( aSelPoints );
1106
1107   setSelectedPonts();
1108 }
1109
1110 void CurveCreator_Widget::moveSelectedPoints( const int theXPosition,
1111                                               const int theYPosition )
1112 {
1113   OCCViewer_Viewer* aViewer = getOCCViewer();
1114   if ( !aViewer )
1115     return;
1116
1117   SectionToPointList aPoints;
1118   startCurveModification( aPoints, false );
1119
1120   OCCViewer_ViewWindow* aWindow =
1121            (OCCViewer_ViewWindow*)aViewer->getViewManager()->getActiveView();
1122   gp_Pnt aStartPnt = CurveCreator_Utils::ConvertClickToPoint( myDragStartPosition.x(),
1123                                                      myDragStartPosition.y(),
1124                                                      aWindow->getViewPort()->getView() );
1125   gp_Pnt anEndPnt = CurveCreator_Utils::ConvertClickToPoint( theXPosition, theYPosition,
1126                                                      aWindow->getViewPort()->getView() );
1127   double aXDelta = aStartPnt.X() - anEndPnt.X();
1128   double anYDelta = aStartPnt.Y() - anEndPnt.Y();
1129
1130   CurveCreator_ICurve::SectionToPointCoordsList aCoordList;
1131   std::deque<float> aChangedPos;
1132   SectionToPointList::const_iterator anIt = myDragPoints.begin(), aLast = myDragPoints.end();
1133   for ( ; anIt != aLast; anIt++ ) {
1134     int aSectionId = anIt->first;
1135     int aPointId = anIt->second;
1136     aChangedPos = myCurve->getPoint( aSectionId, aPointId );
1137     if ( aChangedPos.size() < 2 )
1138       continue;
1139     aChangedPos[0] = aChangedPos[0] - aXDelta;
1140     aChangedPos[1] = aChangedPos[1] - anYDelta;
1141     
1142     aCoordList.push_back(
1143       std::make_pair(std::make_pair( aSectionId, aPointId ), 
1144                      aChangedPos ));
1145   }
1146   myCurve->setSeveralPoints( aCoordList );
1147
1148   myDragged = true;
1149   finishCurveModification( myDragPoints );
1150 }
1151
1152 void CurveCreator_Widget::updateLocalPointView()
1153 {
1154   OCCViewer_Viewer* aViewer = getOCCViewer();
1155   if ( !aViewer )
1156     return;
1157   Handle(AIS_InteractiveContext) aContext = aViewer->getAISContext();
1158
1159   bool isBlocked = myLocalPointView->blockSignals(true);
1160   gp_Pnt aPnt;
1161   myLocalPointView->setRowCount( 0 );
1162   for ( aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected() ) {
1163     TopoDS_Vertex aVertex;
1164     TopoDS_Shape aShape = aContext->SelectedShape();
1165     if ( !aShape.IsNull() && aShape.ShapeType() == TopAbs_VERTEX )
1166       aVertex = TopoDS::Vertex( aContext->SelectedShape() );
1167     else {
1168       Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1169       if ( !anOwner.IsNull() ) {
1170         Handle(AIS_InteractiveObject) anAIS = Handle(AIS_InteractiveObject)::DownCast( anOwner->Selectable() );
1171         if ( !anAIS.IsNull() ) {
1172           Handle(AIS_Point) aPoint = Handle(AIS_Point)::DownCast( anAIS);
1173           if ( !aPoint.IsNull() )
1174             aVertex = TopoDS::Vertex( aPoint->Vertex() );
1175         }
1176         if ( aVertex.IsNull() ) {
1177           // the following happens if there are no points in the current curve, there is only a shape
1178           /*Handle(StdSelect_BRepOwner) aBrepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
1179           if ( aBrepOwner.IsNull() )
1180             continue;
1181           if ( aBrepOwner->HasShape() ) {
1182             const TopoDS_Shape& aShape = aBrepOwner->Shape();
1183             if ( !aShape.IsNull() && aShape.ShapeType() == TopAbs_VERTEX )
1184             {
1185               aVertex = TopoDS::Vertex( aShape );
1186             }
1187           }*/
1188         }
1189       }
1190       if ( aVertex.IsNull() )
1191         continue;
1192       aPnt = BRep_Tool::Pnt( aVertex );
1193       addLocalPointToTable( aPnt.X(), aPnt.Y() );
1194     }
1195   }
1196   myLocalPointView->blockSignals(isBlocked);
1197 }
1198
1199 /**
1200  * 
1201  */
1202 void CurveCreator_Widget::setLocalPointContext( const bool theOpen, const bool isUpdateTable )
1203 {
1204   OCCViewer_Viewer* aViewer = getOCCViewer();
1205   if ( !aViewer )
1206     return;
1207   Handle(AIS_InteractiveContext) ic = aViewer->getAISContext();
1208
1209   if ( theOpen ) {
1210     // Open local context if there is no one
1211     if ( !ic->HasOpenedContext() ) {
1212       ic->ClearCurrents( false );
1213       ic->OpenLocalContext( false/*use displayed objects*/, true/*allow shape decomposition*/ );
1214     }
1215     AIS_ListOfInteractive aList;
1216     ic->DisplayedObjects( aList );
1217     int aLSize = 0;
1218     for ( AIS_ListIteratorOfListOfInteractive it( aList ); it.More(); it.Next() )
1219       aLSize++;
1220
1221     for ( AIS_ListIteratorOfListOfInteractive it( aList ); it.More(); it.Next() )
1222     {
1223       Handle(AIS_InteractiveObject) anAIS = it.Value();
1224       if ( !anAIS.IsNull() )
1225       {
1226         if ( anAIS->IsKind( STANDARD_TYPE( AIS_Shape ) ) )
1227         {
1228           ic->Load( anAIS, -1/*selection mode*/, true/*allow decomposition*/ );
1229           ic->Activate( anAIS, AIS_Shape::SelectionMode( (TopAbs_ShapeEnum)TopAbs_WIRE ) );
1230         }
1231         else if ( anAIS->DynamicType() != STANDARD_TYPE(AIS_Trihedron) )
1232         {
1233           ic->Load( anAIS, -1/*selection mode*/, false/*allow decomposition*/ );
1234           ic->Activate( anAIS, TopAbs_VERTEX );
1235         }
1236       }
1237       continue;
1238     }
1239   }
1240   else {
1241     if ( ic->HasOpenedContext() )
1242       ic->CloseAllContexts();
1243     if ( isUpdateTable )
1244       updateLocalPointView();
1245   }
1246 }
1247
1248 void CurveCreator_Widget::addLocalPointToTable( const double theX, const double theY )
1249 {
1250   SectionToPointList aPoints;
1251   findSectionsToPoints( theX, theY, aPoints );
1252
1253   SectionToPointList aSkipList;
1254   // table could not contain two equal value rows
1255   int aRowId = myLocalPointView->rowCount();
1256   double aCurrentX, aCurrentY;
1257   int aSectionId, aPointId;
1258   SectionToPoint aPoint;
1259   for ( int i = 0; i < aRowId; i++ ) {
1260     aCurrentX = myLocalPointView->item( i, 2 )->data( Qt::UserRole ).toDouble();
1261     aCurrentY = myLocalPointView->item( i, 3 )->data( Qt::UserRole ).toDouble();
1262     if ( fabs( aCurrentX - theX ) < LOCAL_SELECTION_TOLERANCE &&
1263          fabs( aCurrentY - theY ) < LOCAL_SELECTION_TOLERANCE ) {
1264            aPoint = std::make_pair<int, int>( getSectionId( i ), getPointId( i ) );
1265       if ( !contains( aSkipList, aPoint ) )
1266         aSkipList.push_back( aPoint );
1267     }
1268   }
1269   if ( aSkipList.size() == aPoints.size() )
1270     return;
1271
1272   QTableWidgetItem* anItem;
1273   SectionToPointList::const_iterator anIt = aPoints.begin(), aLast = aPoints.end();
1274   for ( ; anIt != aLast; anIt++ ) {
1275     aPoint = *anIt;
1276     if ( contains( aSkipList, aPoint ) )
1277       continue;
1278
1279     myLocalPointView->setRowCount( aRowId+1 );
1280     aSectionId = aPoint.first;
1281     aPointId = aPoint.second;
1282
1283     anItem = new QTableWidgetItem( myCurve->getSectionName( aSectionId ).c_str() );
1284     anItem->setFlags( anItem->flags() & ~Qt::ItemIsEnabled );
1285     anItem->setData( Qt::UserRole, aSectionId );
1286     myLocalPointView->setItem( aRowId, 0, anItem );
1287
1288     anItem = new QTableWidgetItem( QString::number( aPointId + 1 ) );
1289     anItem->setFlags( anItem->flags() & ~Qt::ItemIsEnabled );
1290     anItem->setData( Qt::UserRole, aPointId );
1291     myLocalPointView->setItem( aRowId, 1, anItem );
1292
1293     anItem = new QTableWidgetItem( QString::number( theX ) );
1294     anItem->setData( Qt::UserRole, theX );
1295     myLocalPointView->setItem( aRowId, 2, anItem );
1296
1297     anItem = new QTableWidgetItem( QString::number( theY ) );
1298     anItem->setData( Qt::UserRole, theY );
1299     myLocalPointView->setItem( aRowId, 3, anItem );
1300   }
1301 }
1302
1303 /**
1304  * Set drag operation started. Save the position and a list of dragged points
1305  * \param theState the drag operation state: started/finished
1306  * \param thePoint the start drag position
1307  */
1308 void CurveCreator_Widget::setDragStarted( const bool theState, const QPoint& thePoint )
1309 {
1310   OCCViewer_Viewer* aViewer = getOCCViewer();
1311   if ( theState ) {
1312     getSelectedPonts( myDragPoints );
1313     myDragStarted = myDragPoints.size();
1314     myDragStartPosition = thePoint;
1315     if ( aViewer && myDragStarted ) {
1316       // change a viewer interaction style in order to avoid a select rectangle build
1317       myDragInteractionStyle = aViewer->interactionStyle();
1318       aViewer->setInteractionStyle(SUIT_ViewModel::KEY_FREE);
1319     }
1320   }
1321   else {
1322     if ( aViewer && myDragStarted )
1323       aViewer->setInteractionStyle( myDragInteractionStyle );
1324     myDragStarted = false;
1325     myDragPoints.clear();
1326   }
1327   myDragged = false;
1328 }
1329
1330 void CurveCreator_Widget::getSelectedPonts( CurveCreator_Widget::SectionToPointList& thePoints )
1331 {
1332   thePoints.clear();
1333   for ( int i = 0, aNb = myLocalPointView->rowCount(); i < aNb; i++ )
1334     thePoints.push_back( std::make_pair( getSectionId( i ), getPointId( i ) ) );
1335 }
1336
1337 void CurveCreator_Widget::setSelectedPonts( const CurveCreator_Widget::SectionToPointList& thePoints )
1338 {
1339   OCCViewer_Viewer* aViewer = getOCCViewer();
1340   if ( !aViewer )
1341     return;
1342
1343   AIS_ListOfInteractive aListToSelect;
1344
1345   Handle(AIS_InteractiveContext) ic = aViewer->getAISContext();
1346   if ( !ic->HasOpenedContext() )
1347     return;
1348
1349   AIS_ListOfInteractive aDisplayedList;
1350   ic->DisplayedObjects( aDisplayedList );
1351
1352   SectionToPointList::const_iterator anIt = thePoints.begin(), aLast = thePoints.end();
1353   SectionToPoint aSToPoint;
1354   for( ; anIt != aLast; anIt++ ) {
1355     aSToPoint = *anIt;
1356
1357     for ( AIS_ListIteratorOfListOfInteractive it( aDisplayedList ); it.More(); it.Next() )
1358     {
1359       Handle(AIS_InteractiveObject) anAIS = it.Value();
1360       if ( anAIS.IsNull() )
1361         continue;
1362       Handle(AIS_Point) anAISPoint = Handle(AIS_Point)::DownCast( anAIS );
1363       if ( anAISPoint.IsNull() )
1364         continue;
1365
1366       TopoDS_Vertex aVertex = TopoDS::Vertex( anAISPoint->Vertex() );
1367
1368       if ( aVertex.IsNull() )
1369         continue;
1370
1371       gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
1372
1373       SectionToPointList aPoints;
1374       findSectionsToPoints( aPnt.X(), aPnt.Y(), aPoints );
1375
1376       SectionToPointList::const_iterator anIt = aPoints.begin(), aLast = aPoints.end();
1377       SectionToPoint aPoint;
1378       for ( ; anIt != aLast; anIt++ ) {
1379         aPoint = *anIt;
1380         if ( aPoint.first == aSToPoint.first && aPoint.second == aSToPoint.second )
1381           aListToSelect.Append( anAIS );
1382       }
1383     }
1384   }
1385
1386   ic->ClearSelected( Standard_False );
1387   aViewer->setObjectsSelected( aListToSelect );
1388   updateLocalPointView();
1389 }
1390
1391 /**
1392  * Get viewer information before perform the curve modification.
1393  * Take a list of selected cuve points an close local context.
1394  * The context should be closed because the curve presentation is
1395  * redisplayed and if it is not closed, when we close the local context
1396  * later, the presentation shown in the local context is disappeared.
1397  * \param thePoints an output list of curve selected points
1398  * \param theFillPoints a flag whether the selection list should be filled
1399  */
1400 void CurveCreator_Widget::startCurveModification(
1401                            CurveCreator_Widget::SectionToPointList& thePoints,
1402                            const bool theFillPoints )
1403 {
1404   if ( theFillPoints ) {
1405     thePoints.clear();
1406     getSelectedPonts( thePoints );
1407   }
1408   setLocalPointContext( false );
1409 }
1410
1411 /**
1412  * Restore the viewer state after the curve modification is done.
1413  * Open local context and select given points inside it.
1414  * \param thePoints a list of curve selected points
1415  */
1416 void CurveCreator_Widget::finishCurveModification(
1417                            const CurveCreator_Widget::SectionToPointList& thePoints )
1418 {
1419   if ( getActionMode() == ModificationMode )
1420     setLocalPointContext( true );
1421   setSelectedPonts( thePoints );
1422   updateUndoRedo();
1423 }
1424
1425 /**
1426  * Returns a point index in the model curve by the point coordinates in the viewer
1427  * \param theX the X coordinate of the point
1428  * \param theY the Y coordinate of the point
1429  */
1430 int CurveCreator_Widget::findLocalPointIndex( int theSectionId, float theX, float theY )
1431 {
1432   int aPntIndex = -1;
1433
1434   CurveCreator::Coordinates aCoords;
1435   for ( int i = 0, aNb = myCurve->getNbPoints( theSectionId ); i < aNb && aPntIndex < 0; i++ ) {
1436     aCoords = myCurve->getPoint( theSectionId, i );
1437     if ( aCoords.size() < 2 )
1438       continue;
1439     if ( fabs( aCoords[0] - theX ) < LOCAL_SELECTION_TOLERANCE &&
1440          fabs( aCoords[1] - theY ) < LOCAL_SELECTION_TOLERANCE )
1441       aPntIndex = i;
1442   }
1443
1444   return aPntIndex;
1445 }
1446
1447 void CurveCreator_Widget::findSectionsToPoints( const double theX, const double theY,
1448                                  CurveCreator_Widget::SectionToPointList& thePoints )
1449 {
1450   thePoints.clear();
1451
1452   int aPointId = -1;
1453   for ( int i = 0, aNb = myCurve->getNbSections(); i < aNb; i++ ) {
1454     aPointId = findLocalPointIndex( i, theX, theY );
1455     if ( aPointId < 0 )
1456       continue;
1457     SectionToPoint aPoint = std::make_pair( i, aPointId );
1458     if ( !contains( thePoints, aPoint ) )
1459       thePoints.push_back( aPoint );
1460   }
1461 }
1462
1463 void CurveCreator_Widget::convert( const SectionToPointList& thePoints,
1464                                    QMap<int, QList<int> >& theConvPoints )
1465 {
1466   theConvPoints.clear();
1467
1468   SectionToPointList::const_iterator anIt = thePoints.begin(), aLast = thePoints.end();
1469   QList<int> aPoints;
1470   int aSectionId, aPointId;
1471   for ( ; anIt != aLast; anIt++ ) {
1472     aSectionId = anIt->first;
1473     aPointId = anIt->second;
1474     aPoints.clear();
1475     if ( theConvPoints.contains( aSectionId ) )
1476       aPoints = theConvPoints[aSectionId];
1477     if ( aPoints.contains( aPointId ) )
1478       continue;
1479     aPoints.append( aPointId );
1480     theConvPoints[aSectionId] = aPoints;
1481   }
1482 }
1483
1484 /**
1485  * Checks whether the point belongs to the OCC object
1486  * \param theObject a line or shape with a bspline inside
1487  * \param theX the X coordinate in the view.
1488  * \param theY the Y coordinate in the view.
1489  * \param thePoint the output point to be append to the model curve
1490  * \param thePoint1 the output point to bound the line where a new point should be inserted
1491  * \param thePoint2 the output point to bound the line where a new point should be inserted
1492  */
1493 bool CurveCreator_Widget::pointOnObject( Handle(AIS_InteractiveObject) theObject,
1494                                          const int theX, const int theY,
1495                                          gp_Pnt& thePoint,
1496                                          gp_Pnt& thePoint1, gp_Pnt& thePoint2 )
1497 {
1498   bool isFound = false;
1499
1500   OCCViewer_Viewer* aViewer = getOCCViewer();
1501   if ( theObject.IsNull() || !aViewer )
1502     return isFound;
1503
1504   gp_Pnt aPoint;
1505   Standard_Real aParameter;
1506   gp_Pnt aPnt1, aPnt2;
1507   Handle(AIS_Line) aLine = Handle(AIS_Line)::DownCast( theObject );
1508   if ( !aLine.IsNull() ) {
1509     const Handle(Geom_Line) aGLine = aLine->Line();
1510     isFound = hasProjectPointOnCurve( theX, theY, aGLine, aParameter );
1511     if ( isFound ) {
1512       aPoint = aGLine->Value( aParameter );
1513
1514       Handle(Geom_Point) aPStart;
1515       Handle(Geom_Point) aPEnd;
1516       aLine->Points( aPStart, aPEnd );
1517       aPnt1 = aPStart->Pnt();
1518       aPnt2 = aPEnd->Pnt();
1519
1520       // in case of Geom line a projection is performed to the infinite line,
1521       // so it is necessary to bound it by the line size
1522       Bnd_Box aLineBox;
1523       aLineBox.Set( aPnt1, gp_Vec( aPnt1, aPnt2 ) );
1524       isFound = !aLineBox.IsOut( aPoint );
1525     }
1526   }
1527   else {
1528     Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast( theObject );
1529     if ( !aShape.IsNull() ) {
1530       const TopoDS_Wire& aWire = TopoDS::Wire( aShape->Shape() );
1531       if ( !aWire.IsNull() ) {
1532         TopExp_Explorer anExp( aWire, TopAbs_EDGE );
1533         for ( ; anExp.More(); anExp.Next())
1534         {
1535           const TopoDS_Edge& anEdge = TopoDS::Edge(anExp.Current());
1536           if ( !anEdge.IsNull() ) {
1537             Standard_Real aFirst, aLast;
1538             Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aFirst, aLast );
1539
1540             if ( aCurve->IsKind( STANDARD_TYPE(Geom_BSplineCurve) ) ) {
1541               Handle(Geom_BSplineCurve) aBSplineCurve = Handle(Geom_BSplineCurve)::DownCast( aCurve );
1542               if ( !aBSplineCurve.IsNull() ) {
1543                 isFound = hasProjectPointOnCurve( theX, theY, aCurve, aParameter );
1544                 if ( isFound ) {
1545                   aPoint = aBSplineCurve->Value( aParameter );
1546                   Standard_Integer anI1, anI2;
1547                   aBSplineCurve->LocateU( aParameter, LOCAL_SELECTION_TOLERANCE, anI1, anI2 );
1548
1549                   aPnt1 = aBSplineCurve->Value( aBSplineCurve->Knot( anI1 ) );
1550                   aPnt2 = aBSplineCurve->Value( aBSplineCurve->Knot( anI2 ) );
1551                 }
1552               }
1553             }
1554           }
1555         }
1556       }
1557     }
1558   }
1559   if ( isFound ) {
1560     thePoint = aPoint;
1561     thePoint1 = aPnt1;
1562     thePoint2 = aPnt2;
1563   }
1564   return isFound;
1565 }
1566
1567 /**
1568  * Returns whether the clicked point belong to the curve or has a very near projection
1569  * \param theX the X coordinate of a point clicked in the OCC viewer
1570  * \param theY the Y coordinate of a point clicked in the OCC viewer
1571  * \param theCurve a geometry curve
1572  * \param theOutPoint a found projected point on the curve
1573  */
1574 bool CurveCreator_Widget::hasProjectPointOnCurve( const int theX, const int theY,
1575                                                   const Handle(Geom_Curve)& theCurve,
1576                                                   Standard_Real& theParameter )
1577 {
1578   bool isFound = false;
1579   OCCViewer_Viewer* aViewer = getOCCViewer();
1580   if ( !aViewer )
1581     return isFound;
1582
1583   OCCViewer_ViewWindow* aWindow =
1584            (OCCViewer_ViewWindow*)aViewer->getViewManager()->getActiveView();
1585   Handle(V3d_View) aView = aWindow->getViewPort()->getView();
1586   gp_Pnt aPoint = CurveCreator_Utils::ConvertClickToPoint( theX, theY, aView );
1587
1588   GeomAPI_ProjectPointOnCurve aProj( aPoint, theCurve );
1589   Standard_Integer aNbPoint = aProj.NbPoints();
1590   if (aNbPoint > 0) {
1591     for (Standard_Integer j = 1; j <= aNbPoint && !isFound; j++) {
1592       gp_Pnt aNewPoint = aProj.Point( j );
1593       theParameter = aProj.Parameter( j );
1594
1595       int aX, anY;
1596       CurveCreator_Utils::ConvertPointToClick( aNewPoint, aView, aX, anY );
1597
1598       int aXDelta = abs( aX - theX );
1599       int anYDelta = abs( anY - theY );
1600       isFound = aXDelta < SCENE_PIXEL_TOLERANCE && anYDelta < SCENE_PIXEL_TOLERANCE;
1601     }
1602   }
1603   return isFound;
1604 }
1605
1606 /**
1607  * Returns a section index from the table
1608  * \param theRowId a table row
1609  */
1610 int CurveCreator_Widget::getSectionId( const int theRowId ) const
1611 {
1612   return myLocalPointView->item( theRowId, 0 )->data( Qt::UserRole ).toInt();
1613 }
1614
1615 /**
1616  * Returns a point index from the table
1617  * \param theRowId a table row
1618  */
1619 int CurveCreator_Widget::getPointId( const int theRowId ) const
1620 {
1621   return myLocalPointView->item( theRowId, 1 )->data( Qt::UserRole ).toInt();
1622 }
1623
1624 /**
1625  * Returns whethe the container has the value
1626  * \param theList a container of values
1627  * \param theValue a value
1628  */
1629 bool CurveCreator_Widget::contains( const CurveCreator_Widget::SectionToPointList& theList,
1630                                     const CurveCreator_Widget::SectionToPoint& theValue ) const
1631 {
1632   bool isFound = false;
1633
1634   SectionToPointList::const_iterator anIt = theList.begin(), aLast = theList.end();
1635   for ( ; anIt != aLast && !isFound; anIt++ )
1636     isFound = anIt->first == theValue.first && anIt->second == theValue.second;
1637
1638   return isFound;
1639 }