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