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