Debian Codegraph @

src/Gui/EditableDatumLabel.cpp

raw
1 /// SPDX-License-Identifier: LGPL-2.1-or-later
2 /****************************************************************************
3 * *
4 * Copyright (c) 2023 Ondsel <[email protected]> *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 ***************************************************************************/
23
24 #include <limits>
25 #include <Inventor/sensors/SoNodeSensor.h>
26 #include <Inventor/nodes/SoAnnotation.h>
27 #include <Inventor/nodes/SoOrthographicCamera.h>
28 #include <Inventor/nodes/SoTransform.h>
29 #include <Inventor/nodes/SoSwitch.h>
30
31 #include <QEvent>
32 #include <QKeyEvent>
33 #include <QPixmap>
34 #include <QLabel>
35 #include <QHBoxLayout>
36 #include <QString>
37
38 #include <Gui/Application.h>
39 #include <Gui/BitmapFactory.h>
40 #include <Gui/View3DInventor.h>
41 #include <Gui/View3DInventorViewer.h>
42
43 #include "EditableDatumLabel.h"
44
45
46 using namespace Gui;
47
48
49 struct NodeData
50 {
51 EditableDatumLabel* label;
52 };
53
54 EditableDatumLabel::EditableDatumLabel(
55 View3DInventorViewer* view,
56 const Base::Placement& plc,
57 SbColor color,
58 bool autoDistance,
59 bool avoidMouseCursor
60 )
61 : isSet(false)
62 , hasFinishedEditing(false)
63 , autoDistance(autoDistance)
64 , autoDistanceReverse(false)
65 , avoidMouseCursor(avoidMouseCursor)
66 , value(0.0)
67 , viewer(view)
68 , spinBox(nullptr)
69 , lockIconLabel(nullptr)
70 , cameraSensor(nullptr)
71 , function(Function::Positioning)
72 {
73 // NOLINTBEGIN
74 root = new SoSwitch;
75 root->ref();
76
77 annotation = new SoAnnotation;
78 annotation->ref();
79 annotation->renderCaching = SoSeparator::OFF;
80 root->addChild(annotation);
81
82 transform = new SoTransform();
83 transform->ref();
84 annotation->addChild(transform);
85
86 label = new SoDatumLabel();
87 label->ref();
88 label->string = " ";
89 label->textColor = color;
90 label->size.setValue(17);
91 label->lineWidth = 2.0;
92 label->useAntialiasing = false;
93 label->datumtype = SoDatumLabel::DISTANCE;
94 label->param1 = 0.;
95 label->param2 = 0.;
96 label->param3 = 0.;
97 if (autoDistance) {
98 setLabelRecommendedDistance();
99 }
100 annotation->addChild(label);
101
102 setPlacement(plc);
103 // NOLINTEND
104
105 static_cast<SoSeparator*>(viewer->getSceneGraph())->addChild(root); // NOLINT
106 }
107
108 EditableDatumLabel::~EditableDatumLabel()
109 {
110 deactivate();
111 transform->unref();
112 annotation->unref();
113 root->unref();
114 label->unref();
115 }
116
117 void EditableDatumLabel::activate()
118 {
119 if (!viewer || isActive()) {
120 return;
121 }
122
123 root->whichChild = 0;
124
125 // track camera movements to update spinbox position.
126 auto info = new NodeData {this};
127 cameraSensor = new SoNodeSensor(
128 [](void* data, SoSensor* sensor) {
129 Q_UNUSED(sensor);
130 auto info = static_cast<NodeData*>(data);
131 info->label->positionSpinbox();
132 if (info->label->autoDistance) {
133 info->label->setLabelRecommendedDistance();
134 }
135 },
136 info
137 );
138 cameraSensor->attach(viewer->getCamera());
139 }
140
141 void EditableDatumLabel::deactivate()
142 {
143 stopEdit();
144
145 if (cameraSensor) {
146 auto data = static_cast<NodeData*>(cameraSensor->getData());
147 delete data;
148 cameraSensor->detach();
149 delete cameraSensor;
150 cameraSensor = nullptr;
151 }
152
153 root->whichChild = SO_SWITCH_NONE;
154 }
155
156 void EditableDatumLabel::startEdit(double val, QObject* eventFilteringObj, bool visibleToMouse)
157 {
158 if (isInEdit()) {
159 return;
160 }
161
162 // Reset locked state when starting to edit
163 this->resetLockedState();
164
165 QWidget* mdi = viewer->parentWidget();
166
167 label->string = " ";
168
169 spinBox = new QuantitySpinBox(mdi);
170 spinBox->setUnit(Base::Unit::Length);
171 spinBox->setMinimum(-std::numeric_limits<int>::max());
172 spinBox->setMaximum(std::numeric_limits<int>::max());
173 spinBox->setButtonSymbols(QAbstractSpinBox::NoButtons);
174 spinBox->setFocusPolicy(Qt::ClickFocus); // prevent passing focus with tab.
175 spinBox->setAutoNormalize(false);
176 spinBox->setKeyboardTracking(true);
177 spinBox->installEventFilter(this);
178
179 if (eventFilteringObj) {
180 spinBox->installEventFilter(eventFilteringObj);
181 }
182
183 if (!visibleToMouse) {
184 setSpinboxVisibleToMouse(visibleToMouse);
185 }
186
187 spinBox->show();
188 setSpinboxValue(val);
189 // Note: adjustSize apparently uses the Min/Max values to set the size. So if we don't set them
190 // to INT_MAX, the spinbox are much too big.
191 spinBox->adjustSize();
192 setFocusToSpinbox();
193
194 const auto validateAndFinish = [this]() {
195 // this event can be fired after spinBox was already disposed
196 // in such case we need to skip processing that event
197 if (!spinBox) {
198 return;
199 }
200
201 if (!spinBox->hasValidInput()) {
202 // unset parameters in DrawSketchController, this is needed in a case
203 // when user removes values we reset state of the OVP
204 Q_EMIT this->parameterUnset();
205 return;
206 }
207
208 value = spinBox->rawValue();
209
210 isSet = true;
211
212 if (this->hasFinishedEditing) {
213 this->setLockedAppearance(true);
214 }
215
216 Q_EMIT this->valueChanged(value);
217 };
218
219 connect(spinBox, qOverload<double>(&QuantitySpinBox::valueChanged), this, validateAndFinish);
220 }
221
222 bool EditableDatumLabel::eventFilter(QObject* watched, QEvent* event)
223 {
224 if (event->type() == QEvent::KeyPress) {
225 auto* keyEvent = static_cast<QKeyEvent*>(event);
226 if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter
227 || keyEvent->key() == Qt::Key_Tab) {
228
229 if (auto* spinBox = qobject_cast<QAbstractSpinBox*>(watched)) {
230 // if tab has been pressed and user did not type anything previously,
231 // then just cycle but don't lock anything, otherwise we lock the label
232 if (keyEvent->key() == Qt::Key_Tab && !this->isSet) {
233 if (!this->spinBox->hasValidInput()) {
234 Q_EMIT this->spinBox->valueChanged(this->value);
235 return true;
236 }
237 return false;
238 }
239
240 // for ctrl + enter we accept values as they are
241 if (keyEvent->modifiers() & Qt::ControlModifier) {
242 Q_EMIT this->finishEditingOnAllOVPs();
243 return true;
244 }
245 else {
246 // regular enter
247 this->hasFinishedEditing = true;
248 Q_EMIT this->spinBox->valueChanged(this->value);
249 return true;
250 }
251 }
252 }
253 else if (this->hasFinishedEditing && keyEvent->key() != Qt::Key_Tab) {
254 this->setLockedAppearance(false);
255 return false;
256 }
257 }
258
259 return QObject::eventFilter(watched, event);
260 }
261
262 void EditableDatumLabel::stopEdit()
263 {
264 if (spinBox) {
265 // write the spinbox value in the label.
266 Base::Quantity quantity = spinBox->value();
267
268 double factor {};
269 std::string unitStr;
270 std::string valueStr;
271 valueStr = quantity.getUserString(factor, unitStr);
272 label->string = SbString(valueStr.c_str());
273
274 spinBox->deleteLater();
275 spinBox = nullptr;
276
277 // Lock icon will be automatically destroyed as it's a child of spinbox
278 lockIconLabel = nullptr;
279 }
280 }
281
282 bool EditableDatumLabel::isActive() const
283 {
284 return cameraSensor != nullptr;
285 }
286
287 bool EditableDatumLabel::isInEdit() const
288 {
289 return spinBox != nullptr;
290 }
291
292
293 double EditableDatumLabel::getValue() const
294 {
295 // We use value rather than spinBox->rawValue() in case edit stopped.
296 return value;
297 }
298
299 void EditableDatumLabel::setSpinboxValue(double val, const Base::Unit& unit)
300 {
301 if (!spinBox) {
302 Base::Console().developerWarning(
303 "EditableDatumLabel::setSpinboxValue",
304 "Spinbox doesn't exist in"
305 );
306 return;
307 }
308
309 QSignalBlocker block(spinBox);
310 spinBox->setValue(Base::Quantity(val, unit));
311 value = val;
312 positionSpinbox();
313
314 if (spinBox->hasFocus()) {
315 spinBox->selectNumber();
316 }
317 }
318
319 void EditableDatumLabel::setFocusToSpinbox()
320 {
321 if (!spinBox) {
322 Base::Console().developerWarning(
323 "EditableDatumLabel::setFocusToSpinbox",
324 "Spinbox doesn't exist in"
325 );
326 return;
327 }
328 if (!spinBox->hasFocus()) {
329 spinBox->setFocus();
330 spinBox->selectNumber();
331 }
332 }
333
334 void EditableDatumLabel::positionSpinbox()
335 {
336 if (!spinBox) {
337 return;
338 }
339
340 if (spinBox->hasFocus()) {
341 spinBox->raise();
342 }
343
344 QSize wSize = spinBox->size();
345 QSize vSize = viewer->size();
346 QPoint pxCoord = viewer->toQPoint(viewer->getPointOnViewport(getTextCenterPoint()));
347
348 int posX = std::min(std::max(pxCoord.x() - wSize.width() / 2, 0), vSize.width() - wSize.width());
349 int posY = std::min(std::max(pxCoord.y() - wSize.height() / 2, 0), vSize.height() - wSize.height());
350
351 if (avoidMouseCursor) {
352 QPoint cursorPos = viewer->mapFromGlobal(QCursor::pos());
353 int margin = static_cast<int>(wSize.height() * 0.7); // NOLINT
354 if ((cursorPos.x() > posX - margin && cursorPos.x() < posX + wSize.width() + margin)
355 && (cursorPos.y() > posY - margin && cursorPos.y() < posY + wSize.height() + margin)) {
356 posY = cursorPos.y()
357 + ((cursorPos.y() > pxCoord.y()) ? -wSize.height() - margin : margin);
358 }
359 }
360
361 pxCoord.setX(posX);
362 pxCoord.setY(posY);
363 spinBox->move(pxCoord);
364
365 // Update lock icon position inside the spinbox if it exists and is visible
366 if (lockIconLabel && lockIconLabel->isVisible()) {
367 int iconSize = 14;
368 int padding = 4;
369 QSize spinboxSize = spinBox->size();
370 lockIconLabel->setGeometry(
371 spinboxSize.width() - iconSize - padding,
372 (spinboxSize.height() - iconSize) / 2,
373 iconSize,
374 iconSize
375 );
376 }
377 }
378
379 SbVec3f EditableDatumLabel::getTextCenterPoint() const
380 {
381 // Here we need the 3d point and not the 2d point as are the SoLabel points.
382 // First we get the 2D point (on the sketch/image plane) of the middle of the text label.
383 SbVec3f point2D = label->getLabelTextCenter();
384 // Get the translation and rotation values from the transform
385 SbVec3f translation = transform->translation.getValue();
386 SbRotation rotation = transform->rotation.getValue();
387
388 // Calculate the inverse transformation
389 SbVec3f invTranslation = -translation;
390 SbRotation invRotation = rotation.inverse();
391
392 // Transform the 2D coordinates to 3D
393 // Plane form
394 SbVec3f RX(1, 0, 0);
395 SbVec3f RY(0, 1, 0);
396
397 // move to position of Sketch
398 invRotation.multVec(RX, RX);
399 invRotation.multVec(RY, RY);
400 invRotation.multVec(invTranslation, invTranslation);
401
402 // we use invTranslation as the Base because in setPlacement we set transform->translation using
403 // placement.getPosition() to fix the Zoffset. But this applies the X & Y translation too.
404 Base::Vector3d pos(invTranslation[0], invTranslation[1], invTranslation[2]);
405 Base::Vector3d RXb(RX[0], RX[1], RX[2]);
406 Base::Vector3d RYb(RY[0], RY[1], RY[2]);
407 Base::Vector3d P2D(point2D[0], point2D[1], point2D[2]);
408 P2D.TransformToCoordinateSystem(pos, RXb, RYb);
409
410 return {float(P2D.x), float(P2D.y), float(P2D.z)};
411 }
412
413 void EditableDatumLabel::setPlacement(const Base::Placement& plc)
414 {
415 double x {}, y {}, z {}, w {}; // NOLINT
416 plc.getRotation().getValue(x, y, z, w);
417 transform->rotation.setValue(x, y, z, w); // NOLINT
418
419 Base::Vector3d pos = plc.getPosition();
420 transform->translation.setValue(float(pos.x), float(pos.y), float(pos.z));
421
422 Base::Vector3d RN(0, 0, 1);
423 RN = plc.getRotation().multVec(RN);
424 label->norm.setValue(SbVec3f(float(RN.x), float(RN.y), float(RN.z)));
425 }
426
427 // NOLINTNEXTLINE
428 void EditableDatumLabel::setColor(SbColor color)
429 {
430 label->textColor = color;
431 }
432
433 void EditableDatumLabel::setFocus()
434 {
435 if (spinBox) {
436 spinBox->selectNumber();
437 }
438 }
439
440 void EditableDatumLabel::setPoints(SbVec3f p1, SbVec3f p2)
441 {
442 label->setPoints(p1, p2);
443 // TODO: here the position of the spinbox is not going to be center of p1, p2 because the point
444 // given by getTextCenterPoint
445 // is not updated yet. it will be only on redraw so it is actually positioning on previous position.
446
447 positionSpinbox();
448 if (autoDistance) {
449 setLabelRecommendedDistance();
450 }
451 }
452
453 void EditableDatumLabel::setPoints(Base::Vector3d p1, Base::Vector3d p2)
454 {
455 setPoints(
456 SbVec3f(float(p1.x), float(p1.y), float(p1.z)),
457 SbVec3f(float(p2.x), float(p2.y), float(p2.z))
458 );
459 }
460
461 // NOLINTNEXTLINE
462 void EditableDatumLabel::setLabelType(SoDatumLabel::Type type, Function funct)
463 {
464 label->datumtype = type;
465 function = funct;
466 }
467
468 // NOLINTNEXTLINE
469 void EditableDatumLabel::setLabelDistance(double val)
470 {
471 label->param1 = float(val);
472 }
473
474 // NOLINTNEXTLINE
475 void EditableDatumLabel::setLabelStartAngle(double val)
476 {
477 label->param2 = float(val);
478 }
479
480 // NOLINTNEXTLINE
481 void EditableDatumLabel::setLabelRange(double val)
482 {
483 label->param3 = float(val);
484 }
485
486 void EditableDatumLabel::setLabelRecommendedDistance()
487 {
488 // Takes the 3d view size, and set the label distance to a % of that, such that the distance
489 // does not depend on the zoom level.
490 float width = -1.;
491 float length = -1.;
492 viewer->getDimensions(width, length);
493
494 if (width == -1. || length == -1.) {
495 return;
496 }
497
498 label->param1 = (autoDistanceReverse ? -1.0F : 1.0F) * (width + length) * 0.03F; // NOLINT
499 }
500
501 void EditableDatumLabel::setLabelAutoDistanceReverse(bool val)
502 {
503 autoDistanceReverse = val;
504 }
505
506 void EditableDatumLabel::setSpinboxVisibleToMouse(bool val)
507 {
508 spinBox->setAttribute(Qt::WA_TransparentForMouseEvents, !val);
509 }
510
511 void EditableDatumLabel::setLockedAppearance(bool locked)
512 {
513 if (locked) {
514 if (spinBox) {
515
516 // create lock icon label it it doesn't exist, if it does - show it
517 if (!lockIconLabel) {
518 lockIconLabel = new QLabel(spinBox);
519 lockIconLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true);
520 lockIconLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
521
522 // load icon and scale it to fit in spinbox
523 QPixmap lockIcon = Gui::BitmapFactory().pixmap("Constraint_Lock");
524 QPixmap scaledIcon
525 = lockIcon.scaled(14, 14, Qt::KeepAspectRatio, Qt::SmoothTransformation);
526 lockIconLabel->setPixmap(scaledIcon);
527
528 // position lock icon inside the spinbox
529 int iconSize = 14;
530 int padding = 4;
531 QSize spinboxSize = spinBox->size();
532 lockIconLabel->setGeometry(
533 spinboxSize.width() - iconSize - padding,
534 (spinboxSize.height() - iconSize) / 2,
535 iconSize,
536 iconSize
537 );
538 // style spinbox and add padding for lock
539 QString styleSheet = QString::fromLatin1(
540 "QSpinBox { "
541 "padding-right: %1px; "
542 "}"
543 )
544 .arg(iconSize + padding + 2);
545
546 spinBox->setStyleSheet(styleSheet);
547 }
548
549 lockIconLabel->show();
550 }
551 }
552 else {
553 this->hasFinishedEditing = false;
554
555 // if spinbox exists, reset its appearance
556 if (spinBox) {
557 spinBox->setStyleSheet(QString());
558
559 // hide lock icon if it exists for later reuse
560 if (lockIconLabel) {
561 lockIconLabel->hide();
562 }
563 }
564 }
565 }
566
567 void EditableDatumLabel::resetLockedState()
568 {
569 hasFinishedEditing = false;
570 setLockedAppearance(false);
571 }
572
573 EditableDatumLabel::Function EditableDatumLabel::getFunction()
574 {
575 return function;
576 }
577
578 #include "moc_EditableDatumLabel.cpp" // NOLINT