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