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