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