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