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