Debian Codegraph @

src/Gui/Widgets.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QColorDialog>
25 #include <QDebug>
26 #include <QDesktopServices>
27 #include <QDialogButtonBox>
28 #include <QDrag>
29 #include <QEventLoop>
30 #include <QKeyEvent>
31 #include <QMessageBox>
32 #include <QMimeData>
33 #include <QPainter>
34 #include <QPlainTextEdit>
35 #include <QStylePainter>
36 #include <QTextBlock>
37 #include <QTimer>
38 #include <QToolTip>
39
40
41 #include <Base/Exception.h>
42 #include <Base/Interpreter.h>
43 #include <App/ExpressionParser.h>
44 #include <App/Material.h>
45
46 #include "Widgets.h"
47 #include "Action.h"
48 #include "Application.h"
49 #include "BitmapFactory.h"
50 #include "Command.h"
51 #include "Dialogs/DlgExpressionInput.h"
52 #include "PrefWidgets.h"
53 #include "QuantitySpinBox_p.h"
54 #include "Tools.h"
55 #include "Dialogs/ui_DlgTreeWidget.h"
56 #include "MainWindow.h"
57
58 using namespace Gui;
59 using namespace App;
60 using namespace Base;
61
62 /**
63 * Constructs an empty command view with parent \a parent.
64 */
65 CommandIconView::CommandIconView(QWidget* parent)
66 : QListWidget(parent)
67 {
68 connect(this, &QListWidget::currentItemChanged, this, &CommandIconView::onSelectionChanged);
69 }
70
71 /**
72 * Destroys the icon view and deletes all items.
73 */
74 CommandIconView::~CommandIconView() = default;
75
76 /**
77 * Stores the name of the selected commands for drag and drop.
78 */
79 void CommandIconView::startDrag(Qt::DropActions supportedActions)
80 {
81 Q_UNUSED(supportedActions);
82 QList<QListWidgetItem*> items = selectedItems();
83 QByteArray itemData;
84 QDataStream dataStream(&itemData, QIODevice::WriteOnly);
85
86 QPixmap pixmap;
87 dataStream << items.count();
88 for (QList<QListWidgetItem*>::Iterator it = items.begin(); it != items.end(); ++it) {
89 if (it == items.begin()) {
90 pixmap = ((*it)->data(Qt::UserRole)).value<QPixmap>();
91 }
92 dataStream << (*it)->text();
93 }
94
95 auto mimeData = new QMimeData;
96 mimeData->setData(QStringLiteral("text/x-action-items"), itemData);
97
98 auto drag = new QDrag(this);
99 drag->setMimeData(mimeData);
100 drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
101 drag->setPixmap(pixmap);
102 drag->exec(Qt::MoveAction);
103 }
104
105 /**
106 * This slot is called when a new item becomes current. \a item is the new current item
107 * (or 0 if no item is now current). This slot emits the emitSelectionChanged()
108 * signal for its part.
109 */
110 void CommandIconView::onSelectionChanged(QListWidgetItem* item, QListWidgetItem*)
111 {
112 if (item) {
113 Q_EMIT emitSelectionChanged(item->toolTip());
114 }
115 }
116
117 // ------------------------------------------------------------------------------
118
119 /* TRANSLATOR Gui::ActionSelector */
120
121 ActionSelector::ActionSelector(QWidget* parent)
122 : QWidget(parent)
123 {
124 addButton = new QPushButton(this);
125 addButton->setObjectName(QLatin1String("addButton"));
126 addButton->setMinimumSize(QSize(30, 30));
127 addButton->setIcon(BitmapFactory().pixmap("button_right"));
128 gridLayout = new QGridLayout(this);
129 gridLayout->addWidget(addButton, 1, 1, 1, 1);
130
131 spacerItem = new QSpacerItem(33, 57, QSizePolicy::Minimum, QSizePolicy::Expanding);
132 gridLayout->addItem(spacerItem, 5, 1, 1, 1);
133 spacerItem1 = new QSpacerItem(33, 58, QSizePolicy::Minimum, QSizePolicy::Expanding);
134 gridLayout->addItem(spacerItem1, 0, 1, 1, 1);
135
136 removeButton = new QPushButton(this);
137 removeButton->setObjectName(QLatin1String("removeButton"));
138 removeButton->setMinimumSize(QSize(30, 30));
139 removeButton->setIcon(BitmapFactory().pixmap("button_left"));
140 removeButton->setAutoDefault(true);
141 removeButton->setDefault(false);
142
143 gridLayout->addWidget(removeButton, 2, 1, 1, 1);
144
145 upButton = new QPushButton(this);
146 upButton->setObjectName(QLatin1String("upButton"));
147 upButton->setMinimumSize(QSize(30, 30));
148 upButton->setIcon(BitmapFactory().pixmap("button_up"));
149
150 gridLayout->addWidget(upButton, 3, 1, 1, 1);
151
152 downButton = new QPushButton(this);
153 downButton->setObjectName(QLatin1String("downButton"));
154 downButton->setMinimumSize(QSize(30, 30));
155 downButton->setIcon(BitmapFactory().pixmap("button_down"));
156 downButton->setAutoDefault(true);
157
158 gridLayout->addWidget(downButton, 4, 1, 1, 1);
159
160 vboxLayout = new QVBoxLayout();
161 vboxLayout->setContentsMargins(0, 0, 0, 0);
162 labelAvailable = new QLabel(this);
163 vboxLayout->addWidget(labelAvailable);
164
165 availableWidget = new QTreeWidget(this);
166 availableWidget->setObjectName(QLatin1String("availableTreeWidget"));
167 availableWidget->setRootIsDecorated(false);
168 availableWidget->setHeaderLabels(QStringList() << QString());
169 availableWidget->header()->hide();
170 vboxLayout->addWidget(availableWidget);
171
172 gridLayout->addLayout(vboxLayout, 0, 0, 6, 1);
173
174 vboxLayout1 = new QVBoxLayout();
175 vboxLayout1->setContentsMargins(0, 0, 0, 0);
176 labelSelected = new QLabel(this);
177 vboxLayout1->addWidget(labelSelected);
178
179 selectedWidget = new QTreeWidget(this);
180 selectedWidget->setObjectName(QLatin1String("selectedTreeWidget"));
181 selectedWidget->setRootIsDecorated(false);
182 selectedWidget->setHeaderLabels(QStringList() << QString());
183 selectedWidget->header()->hide();
184 vboxLayout1->addWidget(selectedWidget);
185
186 gridLayout->addLayout(vboxLayout1, 0, 2, 6, 1);
187
188 addButton->setText(QString());
189 removeButton->setText(QString());
190 upButton->setText(QString());
191 downButton->setText(QString());
192
193 connect(addButton, &QPushButton::clicked, this, &ActionSelector::onAddButtonClicked);
194 connect(removeButton, &QPushButton::clicked, this, &ActionSelector::onRemoveButtonClicked);
195 connect(upButton, &QPushButton::clicked, this, &ActionSelector::onUpButtonClicked);
196 connect(downButton, &QPushButton::clicked, this, &ActionSelector::onDownButtonClicked);
197
198 connect(availableWidget, &QTreeWidget::itemDoubleClicked, this, &ActionSelector::onItemDoubleClicked);
199 connect(availableWidget, &QTreeWidget::currentItemChanged, this, &ActionSelector::onCurrentItemChanged);
200 connect(selectedWidget, &QTreeWidget::itemDoubleClicked, this, &ActionSelector::onItemDoubleClicked);
201 connect(selectedWidget, &QTreeWidget::currentItemChanged, this, &ActionSelector::onCurrentItemChanged);
202
203 retranslateUi();
204 setButtonsEnabled();
205 }
206
207 ActionSelector::~ActionSelector() = default;
208
209 void ActionSelector::setSelectedLabel(const QString& label)
210 {
211 labelSelected->setText(label);
212 }
213
214 QString ActionSelector::selectedLabel() const
215 {
216 return labelSelected->text();
217 }
218
219 void ActionSelector::setAvailableLabel(const QString& label)
220 {
221 labelAvailable->setText(label);
222 }
223
224 QString ActionSelector::availableLabel() const
225 {
226 return labelAvailable->text();
227 }
228
229 void ActionSelector::retranslateUi()
230 {
231 labelAvailable->setText(QApplication::translate("Gui::ActionSelector", "Available:"));
232 labelSelected->setText(QApplication::translate("Gui::ActionSelector", "Selected:"));
233 addButton->setToolTip(QApplication::translate("Gui::ActionSelector", "Add"));
234 removeButton->setToolTip(QApplication::translate("Gui::ActionSelector", "Remove"));
235 upButton->setToolTip(QApplication::translate("Gui::ActionSelector", "Move up"));
236 downButton->setToolTip(QApplication::translate("Gui::ActionSelector", "Move down"));
237 }
238
239 void ActionSelector::changeEvent(QEvent* event)
240 {
241 if (event->type() == QEvent::LanguageChange) {
242 retranslateUi();
243 }
244 QWidget::changeEvent(event);
245 }
246
247 void ActionSelector::keyPressEvent(QKeyEvent* event)
248 {
249 if ((event->modifiers() & Qt::ControlModifier)) {
250 switch (event->key()) {
251 case Qt::Key_Right:
252 onAddButtonClicked();
253 break;
254 case Qt::Key_Left:
255 onRemoveButtonClicked();
256 break;
257 case Qt::Key_Up:
258 onUpButtonClicked();
259 break;
260 case Qt::Key_Down:
261 onDownButtonClicked();
262 break;
263 default:
264 event->ignore();
265 return;
266 }
267 }
268 }
269
270 void ActionSelector::setButtonsEnabled()
271 {
272 addButton->setEnabled(availableWidget->indexOfTopLevelItem(availableWidget->currentItem()) > -1);
273 removeButton->setEnabled(selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > -1);
274 upButton->setEnabled(selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > 0);
275 downButton->setEnabled(
276 selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > -1
277 && selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem())
278 < selectedWidget->topLevelItemCount() - 1
279 );
280 }
281
282 void ActionSelector::onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)
283 {
284 setButtonsEnabled();
285 }
286
287 void ActionSelector::onItemDoubleClicked(QTreeWidgetItem* item, int column)
288 {
289 Q_UNUSED(column);
290 QTreeWidget* treeWidget = item->treeWidget();
291 if (treeWidget == availableWidget) {
292 int index = availableWidget->indexOfTopLevelItem(item);
293 item = availableWidget->takeTopLevelItem(index);
294 availableWidget->setCurrentItem(nullptr);
295 selectedWidget->addTopLevelItem(item);
296 selectedWidget->setCurrentItem(item);
297 }
298 else if (treeWidget == selectedWidget) {
299 int index = selectedWidget->indexOfTopLevelItem(item);
300 item = selectedWidget->takeTopLevelItem(index);
301 selectedWidget->setCurrentItem(nullptr);
302 availableWidget->addTopLevelItem(item);
303 availableWidget->setCurrentItem(item);
304 }
305 }
306
307 void ActionSelector::onAddButtonClicked()
308 {
309 QTreeWidgetItem* item = availableWidget->currentItem();
310 if (item) {
311 int index = availableWidget->indexOfTopLevelItem(item);
312 item = availableWidget->takeTopLevelItem(index);
313 availableWidget->setCurrentItem(nullptr);
314 selectedWidget->addTopLevelItem(item);
315 selectedWidget->setCurrentItem(item);
316 }
317 }
318
319 void ActionSelector::onRemoveButtonClicked()
320 {
321 QTreeWidgetItem* item = selectedWidget->currentItem();
322 if (item) {
323 int index = selectedWidget->indexOfTopLevelItem(item);
324 item = selectedWidget->takeTopLevelItem(index);
325 selectedWidget->setCurrentItem(nullptr);
326 availableWidget->addTopLevelItem(item);
327 availableWidget->setCurrentItem(item);
328 }
329 }
330
331 void ActionSelector::onUpButtonClicked()
332 {
333 QTreeWidgetItem* item = selectedWidget->currentItem();
334 if (item && item->isSelected()) {
335 int index = selectedWidget->indexOfTopLevelItem(item);
336 if (index > 0) {
337 selectedWidget->takeTopLevelItem(index);
338 selectedWidget->insertTopLevelItem(index - 1, item);
339 selectedWidget->setCurrentItem(item);
340 }
341 }
342 }
343
344 void ActionSelector::onDownButtonClicked()
345 {
346 QTreeWidgetItem* item = selectedWidget->currentItem();
347 if (item && item->isSelected()) {
348 int index = selectedWidget->indexOfTopLevelItem(item);
349 if (index < selectedWidget->topLevelItemCount() - 1) {
350 selectedWidget->takeTopLevelItem(index);
351 selectedWidget->insertTopLevelItem(index + 1, item);
352 selectedWidget->setCurrentItem(item);
353 }
354 }
355 }
356
357 // ------------------------------------------------------------------------------
358
359 /* TRANSLATOR Gui::AccelLineEdit */
360
361 /**
362 * Constructs a line edit with no text.
363 * The \a parent argument is sent to the QKeySequenceEdit constructor.
364 */
365 AccelLineEdit::AccelLineEdit(QWidget* parent)
366 : QKeySequenceEdit(parent)
367 {
368 if (auto le = findChild<QLineEdit*>()) {
369 le->setClearButtonEnabled(true);
370 }
371 }
372
373 AccelLineEdit::AccelLineEdit(const QKeySequence& keySequence, QWidget* parent)
374 : QKeySequenceEdit(keySequence, parent)
375 {
376 if (auto le = findChild<QLineEdit*>()) {
377 le->setClearButtonEnabled(true);
378 }
379 }
380
381 void AccelLineEdit::setReadOnly(bool value)
382 {
383 if (auto le = findChild<QLineEdit*>()) {
384 le->setReadOnly(value);
385 }
386 }
387
388 bool AccelLineEdit::isEmpty() const
389 {
390 return keySequence().isEmpty();
391 }
392
393 QString AccelLineEdit::text() const
394 {
395 return keySequence().toString(QKeySequence::NativeText);
396 }
397
398 // ------------------------------------------------------------------------------
399
400 /* TRANSLATOR Gui::ModifierLineEdit */
401
402 /**
403 * Constructs a line edit with no text.
404 * The \a parent argument is sent to the QLineEdit constructor.
405 */
406 ModifierLineEdit::ModifierLineEdit(QWidget* parent)
407 : QLineEdit(parent)
408 {
409 setPlaceholderText(tr("Press modifier keys"));
410 }
411
412 /**
413 * Checks which modifiers are pressed and show it as text.
414 */
415 void ModifierLineEdit::keyPressEvent(QKeyEvent* e)
416 {
417 int key = e->key();
418 Qt::KeyboardModifiers state = e->modifiers();
419
420 switch (key) {
421 case Qt::Key_Backspace:
422 case Qt::Key_Delete:
423 clear();
424 return;
425 case Qt::Key_Control:
426 case Qt::Key_Shift:
427 case Qt::Key_Alt:
428 case Qt::Key_Meta:
429 break;
430 default:
431 return;
432 }
433
434 clear();
435 QString txtLine;
436
437 // Handles modifiers applying a mask.
438 if ((state & Qt::ControlModifier) == Qt::ControlModifier) {
439 QKeySequence ks(Qt::CTRL);
440 txtLine += ks.toString(QKeySequence::NativeText);
441 }
442 if ((state & Qt::AltModifier) == Qt::AltModifier) {
443 QKeySequence ks(Qt::ALT);
444 txtLine += ks.toString(QKeySequence::NativeText);
445 }
446 if ((state & Qt::ShiftModifier) == Qt::ShiftModifier) {
447 QKeySequence ks(Qt::SHIFT);
448 txtLine += ks.toString(QKeySequence::NativeText);
449 }
450 if ((state & Qt::MetaModifier) == Qt::MetaModifier) {
451 QKeySequence ks(Qt::META);
452 txtLine += ks.toString(QKeySequence::NativeText);
453 }
454
455 setText(txtLine);
456 }
457
458 // ------------------------------------------------------------------------------
459
460 ClearLineEdit::ClearLineEdit(QWidget* parent)
461 : QLineEdit(parent)
462 {
463 clearAction = this->addAction(
464 QIcon(QStringLiteral(":/icons/edit-cleartext.svg")),
465 QLineEdit::TrailingPosition
466 );
467 connect(clearAction, &QAction::triggered, this, &ClearLineEdit::clear);
468 connect(this, &QLineEdit::textChanged, this, &ClearLineEdit::updateClearButton);
469 }
470
471 void ClearLineEdit::resizeEvent(QResizeEvent* e)
472 {
473 QLineEdit::resizeEvent(e);
474 }
475
476 void ClearLineEdit::updateClearButton(const QString& text)
477 {
478 clearAction->setVisible(!text.isEmpty());
479 }
480
481 // ------------------------------------------------------------------------------
482
483 /* TRANSLATOR Gui::CheckListDialog */
484
485 /**
486 * Constructs a CheckListDialog which is a child of 'parent', with the
487 * name 'name' and widget flags set to 'f'
488 *
489 * The dialog will by default be modeless, unless you set 'modal' to
490 * true to construct a modal dialog.
491 */
492 CheckListDialog::CheckListDialog(QWidget* parent, Qt::WindowFlags fl)
493 : QDialog(parent, fl)
494 , ui(new Ui_DlgTreeWidget)
495 {
496 ui->setupUi(this);
497 }
498
499 /**
500 * Destroys the object and frees any allocated resources
501 */
502 CheckListDialog::~CheckListDialog() = default;
503
504 /**
505 * Sets the items to the dialog's list view. By default all items are checkable..
506 */
507 void CheckListDialog::setCheckableItems(const QStringList& items)
508 {
509 for (const auto& it : items) {
510 auto item = new QTreeWidgetItem(ui->treeWidget);
511 item->setText(0, it);
512 item->setCheckState(0, Qt::Unchecked);
513 }
514 }
515
516 /**
517 * Sets the items to the dialog's list view. If the boolean type of a CheckListItem
518 * is set to false the item is not checkable any more.
519 */
520 void CheckListDialog::setCheckableItems(const QList<CheckListItem>& items)
521 {
522 for (const auto& it : items) {
523 auto item = new QTreeWidgetItem(ui->treeWidget);
524 item->setText(0, it.first);
525 item->setCheckState(0, (it.second ? Qt::Checked : Qt::Unchecked));
526 }
527 }
528
529 /**
530 * Returns a list of the check items.
531 */
532 QStringList CheckListDialog::getCheckedItems() const
533 {
534 return checked;
535 }
536
537 /**
538 * Collects all checked items to be able to return them by call \ref getCheckedItems().
539 */
540 void CheckListDialog::accept()
541 {
542 QTreeWidgetItemIterator it(ui->treeWidget, QTreeWidgetItemIterator::Checked);
543 while (*it) {
544 checked.push_back((*it)->text(0));
545 ++it;
546 }
547
548 QDialog::accept();
549 }
550
551 // ------------------------------------------------------------------------------
552
553 namespace Gui
554 {
555 struct ColorButtonP
556 {
557 QColor old, col;
558 QPointer<QColorDialog> cd;
559 bool allowChange {true};
560 bool autoChange {false};
561 bool drawFrame {true};
562 bool allowTransparency {false};
563 bool modal {true};
564 };
565 } // namespace Gui
566
567 /**
568 * Constructs a colored button called \a name with parent \a parent.
569 */
570 ColorButton::ColorButton(QWidget* parent)
571 : QPushButton(parent)
572 {
573 d = new ColorButtonP();
574 d->col = palette().color(QPalette::Active, QPalette::Midlight);
575 connect(this, &ColorButton::clicked, this, &ColorButton::onChooseColor);
576
577 int e = style()->pixelMetric(QStyle::PM_ButtonIconSize);
578 setIconSize(QSize(2 * e, e));
579 }
580
581 /**
582 * Destroys the button.
583 */
584 ColorButton::~ColorButton()
585 {
586 delete d;
587 }
588
589 /**
590 * Sets the color \a c to the button.
591 */
592 void ColorButton::setColor(const QColor& c)
593 {
594 d->col = c;
595 update();
596 }
597
598 /**
599 * Returns the current color of the button.
600 */
601 QColor ColorButton::color() const
602 {
603 return d->col;
604 }
605
606 /**
607 * Sets the packed color \a c to the button.
608 */
609 void ColorButton::setPackedColor(uint32_t c)
610 {
611 Base::Color color;
612 color.setPackedValue(c);
613 d->col.setRedF(color.r);
614 d->col.setGreenF(color.g);
615 d->col.setBlueF(color.b);
616 d->col.setAlphaF(color.a);
617 update();
618 }
619
620 /**
621 * Returns the current packed color of the button.
622 */
623 uint32_t ColorButton::packedColor() const
624 {
625 Base::Color color(d->col.redF(), d->col.greenF(), d->col.blueF(), d->col.alphaF());
626 return color.getPackedValue();
627 }
628
629 void ColorButton::setAllowChangeColor(bool ok)
630 {
631 d->allowChange = ok;
632 }
633
634 bool ColorButton::allowChangeColor() const
635 {
636 return d->allowChange;
637 }
638
639 void ColorButton::setDrawFrame(bool ok)
640 {
641 d->drawFrame = ok;
642 }
643
644 bool ColorButton::drawFrame() const
645 {
646 return d->drawFrame;
647 }
648
649 void Gui::ColorButton::setAllowTransparency(bool allow)
650 {
651 d->allowTransparency = allow;
652 if (d->cd) {
653 d->cd->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, allow);
654 }
655 }
656
657 bool Gui::ColorButton::allowTransparency() const
658 {
659 if (d->cd) {
660 return d->cd->testOption(QColorDialog::ColorDialogOption::ShowAlphaChannel);
661 }
662 else {
663 return d->allowTransparency;
664 }
665 }
666
667 void ColorButton::setModal(bool b)
668 {
669 d->modal = b;
670 }
671
672 bool ColorButton::isModal() const
673 {
674 return d->modal;
675 }
676
677 void ColorButton::setAutoChangeColor(bool on)
678 {
679 d->autoChange = on;
680 }
681
682 bool ColorButton::autoChangeColor() const
683 {
684 return d->autoChange;
685 }
686
687 /**
688 * Draws the button label.
689 */
690 void ColorButton::paintEvent(QPaintEvent* e)
691 {
692 QPushButton::paintEvent(e);
693
694 QSize isize = iconSize();
695 QRectF colorRect(0, 0, isize.width(), isize.height());
696 QPointF buttonCenter = rect().center();
697 colorRect.moveCenter(buttonCenter); // move colorRect to center of button
698
699 QPainter painter(this);
700 if (d->drawFrame) {
701 // frame is drawn on the outside of rectangle
702 // so we need to adjust to get same size as for non-frame button
703 constexpr qreal strokeWidth = 2;
704 colorRect.adjust(strokeWidth, strokeWidth, -strokeWidth, -strokeWidth);
705 painter.setBrush(d->col);
706 painter.setPen(Qt::gray);
707 painter.drawRect(colorRect);
708 }
709 else {
710 painter.fillRect(colorRect, d->col);
711 }
712 }
713
714 void ColorButton::showModeless()
715 {
716 if (d->cd.isNull()) {
717 d->old = d->col;
718
719 QColorDialog* dlg = new QColorDialog(d->col, this);
720 dlg->setAttribute(Qt::WA_DeleteOnClose);
721 if (DialogOptions::dontUseNativeColorDialog()) {
722 dlg->setOptions(QColorDialog::DontUseNativeDialog);
723 }
724 dlg->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, d->allowTransparency);
725 dlg->setCurrentColor(d->old);
726 connect(dlg, &QColorDialog::rejected, this, &ColorButton::onRejected);
727 connect(dlg, &QColorDialog::currentColorChanged, this, &ColorButton::onColorChosen);
728 d->cd = dlg;
729 }
730 d->cd->show();
731 }
732
733 void ColorButton::showModal()
734 {
735 QColor currentColor = d->col;
736 QColorDialog* dlg = new QColorDialog(d->col, this);
737 dlg->setAttribute(Qt::WA_DeleteOnClose);
738 if (DialogOptions::dontUseNativeColorDialog()) {
739 dlg->setOptions(QColorDialog::DontUseNativeDialog);
740 }
741 dlg->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, d->allowTransparency);
742
743 if (d->autoChange) {
744 connect(dlg, &QColorDialog::currentColorChanged, this, &ColorButton::onColorChosen);
745 }
746
747 dlg->setCurrentColor(currentColor);
748 dlg->adjustSize();
749
750 connect(dlg, &QColorDialog::finished, this, [&](int result) {
751 if (result == QDialog::Accepted) {
752 QColor c = dlg->selectedColor();
753 if (c.isValid()) {
754 setColor(c);
755 Q_EMIT changed();
756 }
757 }
758 else if (d->autoChange) {
759 setColor(currentColor);
760 Q_EMIT changed();
761 }
762 setProperty("modal_dialog_active", false);
763 });
764
765 /* A FocusOut event is sent when a native macOS color picker is opened, which
766 * closes the editor and destroys this object. Set a property to ignore this event.
767 */
768 setProperty("modal_dialog_active", true);
769
770 dlg->exec();
771 }
772
773 /**
774 * Opens a QColorDialog to set a new color.
775 */
776 void ColorButton::onChooseColor()
777 {
778 if (!d->allowChange) {
779 return;
780 }
781 if (d->modal) {
782 showModal();
783 }
784 else {
785 showModeless();
786 }
787 }
788
789 void ColorButton::onColorChosen(const QColor& c)
790 {
791 setColor(c);
792 Q_EMIT changed();
793 }
794
795 void ColorButton::onRejected()
796 {
797 setColor(d->old);
798 Q_EMIT changed();
799 }
800
801 // ------------------------------------------------------------------------------
802
803 UrlLabel::UrlLabel(QWidget* parent, Qt::WindowFlags f)
804 : QLabel(parent, f)
805 , _url(QStringLiteral("http://localhost"))
806 , _launchExternal(true)
807 {
808 setToolTip(this->_url);
809 setCursor(Qt::PointingHandCursor);
810 if (qApp->styleSheet().isEmpty()) {
811 setStyleSheet(QStringLiteral("Gui--UrlLabel {color: #0000FF;text-decoration: underline;}"));
812 }
813 }
814
815 UrlLabel::~UrlLabel() = default;
816
817 void Gui::UrlLabel::setLaunchExternal(bool l)
818 {
819 _launchExternal = l;
820 }
821
822 void UrlLabel::mouseReleaseEvent(QMouseEvent*)
823 {
824 if (_launchExternal) {
825 QDesktopServices::openUrl(this->_url);
826 }
827 else {
828 // Someone else will deal with it...
829 Q_EMIT linkClicked(_url);
830 }
831 }
832
833 QString UrlLabel::url() const
834 {
835 return this->_url;
836 }
837
838 bool Gui::UrlLabel::launchExternal() const
839 {
840 return _launchExternal;
841 }
842
843 void UrlLabel::setUrl(const QString& u)
844 {
845 this->_url = u;
846 setToolTip(this->_url);
847 }
848
849 // --------------------------------------------------------------------
850
851 StatefulLabel::StatefulLabel(QWidget* parent)
852 : QLabel(parent)
853 , _overridePreference(false)
854 {
855 // Always attach to the parameter group that stores the main FreeCAD stylesheet
856 _stylesheetGroup = App::GetApplication().GetParameterGroupByPath(
857 "User parameter:BaseApp/Preferences/General"
858 );
859 _stylesheetGroup->Attach(this);
860 }
861
862 StatefulLabel::~StatefulLabel()
863 {
864 if (_parameterGroup.isValid()) {
865 _parameterGroup->Detach(this);
866 }
867 _stylesheetGroup->Detach(this);
868 }
869
870 void StatefulLabel::setDefaultStyle(const QString& defaultStyle)
871 {
872 _defaultStyle = defaultStyle;
873 }
874
875 void StatefulLabel::setParameterGroup(const std::string& groupName)
876 {
877 if (_parameterGroup.isValid()) {
878 _parameterGroup->Detach(this);
879 }
880
881 // Attach to the Parametergroup so we know when it changes
882 _parameterGroup = App::GetApplication().GetParameterGroupByPath(groupName.c_str());
883 if (_parameterGroup.isValid()) {
884 _parameterGroup->Attach(this);
885 }
886 }
887
888 void StatefulLabel::registerState(
889 const QString& state,
890 const QString& styleCSS,
891 const std::string& preferenceName
892 )
893 {
894 _availableStates[state] = {styleCSS, preferenceName};
895 }
896
897 void StatefulLabel::registerState(
898 const QString& state,
899 const QColor& color,
900 const std::string& preferenceName
901 )
902 {
903 QString css;
904 if (color.isValid()) {
905 css = QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}")
906 .arg(color.red())
907 .arg(color.green())
908 .arg(color.blue())
909 .arg(color.alpha());
910 }
911 _availableStates[state] = {css, preferenceName};
912 }
913
914 void StatefulLabel::registerState(
915 const QString& state,
916 const QColor& fg,
917 const QColor& bg,
918 const std::string& preferenceName
919 )
920 {
921 QString colorEntries;
922 if (fg.isValid()) {
923 colorEntries.append(QStringLiteral("color : rgba(%1,%2,%3,%4);")
924 .arg(fg.red())
925 .arg(fg.green())
926 .arg(fg.blue())
927 .arg(fg.alpha()));
928 }
929 if (bg.isValid()) {
930 colorEntries.append(QStringLiteral("background-color : rgba(%1,%2,%3,%4);")
931 .arg(bg.red())
932 .arg(bg.green())
933 .arg(bg.blue())
934 .arg(bg.alpha()));
935 }
936 QString css = QStringLiteral("Gui--StatefulLabel{ %1 }").arg(colorEntries);
937 _availableStates[state] = {css, preferenceName};
938 }
939
940 /** Observes the parameter group and clears the cache if it changes */
941 void StatefulLabel::OnChange(Base::Subject<const char*>& rCaller, const char* rcReason)
942 {
943 Q_UNUSED(rCaller);
944 auto changedItem = std::string(rcReason);
945 if (changedItem == "StyleSheet") {
946 _styleCache.clear();
947 }
948 else {
949 for (const auto& state : _availableStates) {
950 if (state.second.preferenceString == changedItem) {
951 _styleCache.erase(_styleCache.find(state.first));
952 }
953 }
954 }
955 }
956
957 void StatefulLabel::setOverridePreference(bool overridePreference)
958 {
959 _overridePreference = overridePreference;
960 }
961
962 void StatefulLabel::setState(QString state)
963 {
964 _state = state;
965 this->ensurePolished();
966
967 // If the stylesheet insists, ignore all other logic and let it do its thing. This
968 // property is *only* set by the stylesheet.
969 if (_overridePreference) {
970 return;
971 }
972
973 // Check the cache first:
974 if (auto style = _styleCache.find(_state); style != _styleCache.end()) {
975 auto test = style->second.toStdString();
976 this->setStyleSheet(style->second);
977 return;
978 }
979
980 if (auto entry = _availableStates.find(state); entry != _availableStates.end()) {
981 // Order of precedence: first, check if the user has set this in their preferences:
982 if (!entry->second.preferenceString.empty()) {
983 // First, try to see if it's just stored a color (as an unsigned int):
984 auto availableColorPrefs = _parameterGroup->GetUnsignedMap();
985 std::string lookingForGroup = entry->second.preferenceString;
986 for (const auto& unsignedEntry : availableColorPrefs) {
987 std::string foundGroup = unsignedEntry.first;
988 if (unsignedEntry.first == entry->second.preferenceString) {
989 // Convert the stored Uint into usable color data:
990 unsigned int col = unsignedEntry.second;
991 QColor qcolor(Base::Color::fromPackedRGB<QColor>(col));
992 this->setStyleSheet(
993 QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}")
994 .arg(qcolor.red())
995 .arg(qcolor.green())
996 .arg(qcolor.blue())
997 .arg(qcolor.alpha())
998 );
999 _styleCache[state] = this->styleSheet();
1000 return;
1001 }
1002 }
1003
1004 // If not, try to see if there's an entire style string set as ASCII:
1005 auto availableStringPrefs = _parameterGroup->GetASCIIMap();
1006 for (const auto& stringEntry : availableStringPrefs) {
1007 if (stringEntry.first == entry->second.preferenceString) {
1008 QString css = QStringLiteral("Gui--StatefulLabel{ %1 }")
1009 .arg(QString::fromStdString(stringEntry.second));
1010 this->setStyleSheet(css);
1011 _styleCache[state] = this->styleSheet();
1012 return;
1013 }
1014 }
1015 }
1016
1017 // If there is no preferences entry for this label, allow the stylesheet to set it, and only
1018 // set to the default formatting if there is no stylesheet entry
1019 if (qApp->styleSheet().isEmpty()) {
1020 this->setStyleSheet(entry->second.defaultCSS);
1021 _styleCache[state] = this->styleSheet();
1022 return;
1023 }
1024 // else the stylesheet sets our appearance: make sure it recalculates the appearance:
1025 this->setStyleSheet(QString());
1026 this->setStyle(qApp->style());
1027 this->style()->unpolish(this);
1028 this->style()->polish(this);
1029 }
1030 else {
1031 if (styleSheet().isEmpty()) {
1032 this->setStyleSheet(_defaultStyle);
1033 _styleCache[state] = this->styleSheet();
1034 }
1035 }
1036 }
1037
1038 // --------------------------------------------------------------------
1039
1040 /* TRANSLATOR Gui::LabelButton */
1041
1042 /**
1043 * Constructs a file chooser called \a name with the parent \a parent.
1044 */
1045 LabelButton::LabelButton(QWidget* parent)
1046 : QWidget(parent)
1047 {
1048 auto layout = new QHBoxLayout(this);
1049 layout->setContentsMargins(0, 0, 0, 0);
1050 layout->setSpacing(1);
1051
1052 label = new QLabel(this);
1053 label->setAutoFillBackground(true);
1054 layout->addWidget(label);
1055
1056 button = new QPushButton(QStringLiteral("…"), this);
1057 #if defined(Q_OS_MACOS)
1058 button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct
1059 #endif
1060 layout->addWidget(button);
1061
1062 connect(button, &QPushButton::clicked, this, &LabelButton::browse);
1063 connect(button, &QPushButton::clicked, this, &LabelButton::buttonClicked);
1064 }
1065
1066 LabelButton::~LabelButton() = default;
1067
1068 void LabelButton::resizeEvent(QResizeEvent* e)
1069 {
1070 button->setFixedWidth(e->size().height());
1071 button->setFixedHeight(e->size().height());
1072 }
1073
1074 QLabel* LabelButton::getLabel() const
1075 {
1076 return label;
1077 }
1078
1079 QPushButton* LabelButton::getButton() const
1080 {
1081 return button;
1082 }
1083
1084 QVariant LabelButton::value() const
1085 {
1086 return _val;
1087 }
1088
1089 void LabelButton::setValue(const QVariant& val)
1090 {
1091 _val = val;
1092 showValue(_val);
1093 Q_EMIT valueChanged(_val);
1094 }
1095
1096 void LabelButton::showValue(const QVariant& data)
1097 {
1098 label->setText(data.toString());
1099 }
1100
1101 void LabelButton::browse()
1102 {}
1103
1104 // ----------------------------------------------------------------------
1105
1106 ToolTip* ToolTip::inst = nullptr;
1107
1108 ToolTip* ToolTip::instance()
1109 {
1110 if (!inst) {
1111 inst = new ToolTip();
1112 }
1113 return inst;
1114 }
1115
1116 ToolTip::ToolTip()
1117 : installed(false)
1118 , hidden(true)
1119 {}
1120
1121 ToolTip::~ToolTip() = default;
1122
1123 void ToolTip::installEventFilter()
1124 {
1125 if (this->installed) {
1126 return;
1127 }
1128 qApp->installEventFilter(this);
1129 this->installed = true;
1130 }
1131
1132 void ToolTip::removeEventFilter()
1133 {
1134 if (!this->installed) {
1135 return;
1136 }
1137 qApp->removeEventFilter(this);
1138 this->installed = false;
1139 }
1140
1141 void ToolTip::showText(const QPoint& pos, const QString& text, QWidget* w)
1142 {
1143 ToolTip* tip = instance();
1144 if (!text.isEmpty()) {
1145 // install this object to filter timer events for the tooltip label
1146 tip->installEventFilter();
1147 tip->pos = pos;
1148 tip->text = text;
1149 tip->w = w;
1150 // show text with a short delay
1151 tip->tooltipTimer.start(80, tip);
1152 tip->displayTime.start();
1153 }
1154 else {
1155 hideText();
1156 }
1157 }
1158
1159 void ToolTip::hideText()
1160 {
1161 instance()->tooltipTimer.stop();
1162 instance()->hidden = true;
1163 QToolTip::hideText();
1164 }
1165
1166 void ToolTip::timerEvent(QTimerEvent* e)
1167 {
1168 if (e->timerId() == tooltipTimer.timerId()) {
1169 QToolTip::showText(pos, text, w);
1170 tooltipTimer.stop();
1171 displayTime.restart();
1172 }
1173 }
1174
1175 bool ToolTip::eventFilter(QObject* o, QEvent* e)
1176 {
1177 if (!o->isWidgetType()) {
1178 return false;
1179 }
1180 switch (e->type()) {
1181 case QEvent::MouseButtonPress:
1182 hideText();
1183 break;
1184 case QEvent::KeyPress:
1185 if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
1186 hideText();
1187 }
1188 break;
1189 case QEvent::Leave:
1190 hideText();
1191 break;
1192 case QEvent::Timer:
1193 case QEvent::Show:
1194 case QEvent::Hide:
1195 if (auto label = qobject_cast<QLabel*>(o)) {
1196 if (label->objectName() == QStringLiteral("qtooltip_label")) {
1197 // This is a trick to circumvent that the tooltip gets hidden immediately
1198 // after it gets visible. We just filter out all timer events to keep the
1199 // label visible.
1200
1201 // Ignore the timer events to prevent from being closed
1202 if (e->type() == QEvent::Show) {
1203 this->hidden = false;
1204 }
1205 else if (e->type() == QEvent::Hide) {
1206 // removeEventFilter();
1207 this->hidden = true;
1208 }
1209 else if (e->type() == QEvent::Timer && !this->hidden
1210 && displayTime.elapsed() < 5000) {
1211 return true;
1212 }
1213 }
1214 }
1215 break;
1216 default:
1217 break;
1218 }
1219 return false;
1220 }
1221
1222 // ----------------------------------------------------------------------
1223
1224 StatusWidget::StatusWidget(QWidget* parent)
1225 : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint)
1226 {
1227 label = new QLabel(this);
1228 label->setAlignment(Qt::AlignCenter);
1229
1230 auto gridLayout = new QGridLayout(this);
1231 gridLayout->setSpacing(6);
1232 gridLayout->setContentsMargins(9, 9, 9, 9);
1233 gridLayout->addWidget(label, 0, 0, 1, 1);
1234 }
1235
1236 StatusWidget::~StatusWidget() = default;
1237
1238 void StatusWidget::setStatusText(const QString& s)
1239 {
1240 label->setText(s);
1241 }
1242
1243 void StatusWidget::showText(int ms)
1244 {
1245 show();
1246 QTimer timer;
1247 QEventLoop loop;
1248 QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
1249 timer.start(ms);
1250 loop.exec(QEventLoop::ExcludeUserInputEvents);
1251 hide();
1252 }
1253
1254 QSize StatusWidget::sizeHint() const
1255 {
1256 return {250, 100};
1257 }
1258
1259 void StatusWidget::showEvent(QShowEvent* event)
1260 {
1261 QDialog::showEvent(event);
1262 }
1263
1264 void StatusWidget::hideEvent(QHideEvent*)
1265 {}
1266
1267 // --------------------------------------------------------------------
1268
1269 class LineNumberArea: public QWidget
1270 {
1271 public:
1272 explicit LineNumberArea(PropertyListEditor* editor)
1273 : QWidget(editor)
1274 {
1275 codeEditor = editor;
1276 }
1277
1278 QSize sizeHint() const override
1279 {
1280 return {codeEditor->lineNumberAreaWidth(), 0};
1281 }
1282
1283 protected:
1284 void paintEvent(QPaintEvent* event) override
1285 {
1286 codeEditor->lineNumberAreaPaintEvent(event);
1287 }
1288
1289 private:
1290 PropertyListEditor* codeEditor;
1291 };
1292
1293 PropertyListEditor::PropertyListEditor(QWidget* parent)
1294 : QPlainTextEdit(parent)
1295 {
1296 lineNumberArea = new LineNumberArea(this);
1297
1298 connect(this, &QPlainTextEdit::blockCountChanged, this, &PropertyListEditor::updateLineNumberAreaWidth);
1299 connect(this, &QPlainTextEdit::updateRequest, this, &PropertyListEditor::updateLineNumberArea);
1300 connect(this, &QPlainTextEdit::cursorPositionChanged, this, &PropertyListEditor::highlightCurrentLine);
1301
1302 updateLineNumberAreaWidth(0);
1303 highlightCurrentLine();
1304 }
1305
1306 int PropertyListEditor::lineNumberAreaWidth()
1307 {
1308 int digits = 1;
1309 int max = qMax(1, blockCount());
1310 while (max >= 10) {
1311 max /= 10;
1312 ++digits;
1313 }
1314
1315 int space = 3 + QtTools::horizontalAdvance(fontMetrics(), QLatin1Char('9')) * digits;
1316
1317 return space;
1318 }
1319
1320 void PropertyListEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
1321 {
1322 setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
1323 }
1324
1325 void PropertyListEditor::updateLineNumberArea(const QRect& rect, int dy)
1326 {
1327 if (dy) {
1328 lineNumberArea->scroll(0, dy);
1329 }
1330 else {
1331 lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
1332 }
1333
1334 if (rect.contains(viewport()->rect())) {
1335 updateLineNumberAreaWidth(0);
1336 }
1337 }
1338
1339 void PropertyListEditor::resizeEvent(QResizeEvent* e)
1340 {
1341 QPlainTextEdit::resizeEvent(e);
1342
1343 QRect cr = contentsRect();
1344 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
1345 }
1346
1347 void PropertyListEditor::highlightCurrentLine()
1348 {
1349 QList<QTextEdit::ExtraSelection> extraSelections;
1350 if (!isReadOnly()) {
1351 QTextEdit::ExtraSelection selection;
1352
1353 QPalette palette = style()->standardPalette();
1354 selection.format.setBackground(palette.highlight().color());
1355 selection.format.setForeground(palette.highlightedText().color());
1356
1357 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
1358 selection.cursor = textCursor();
1359 selection.cursor.clearSelection();
1360 extraSelections.append(selection);
1361 }
1362
1363 setExtraSelections(extraSelections);
1364 }
1365
1366 void PropertyListEditor::lineNumberAreaPaintEvent(QPaintEvent* event)
1367 {
1368 QPainter painter(lineNumberArea);
1369 painter.fillRect(event->rect(), Qt::lightGray);
1370
1371 QTextBlock block = firstVisibleBlock();
1372 int blockNumber = block.blockNumber();
1373 int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top();
1374 int bottom = top + (int)blockBoundingRect(block).height();
1375
1376 while (block.isValid() && top <= event->rect().bottom()) {
1377 if (block.isVisible() && bottom >= event->rect().top()) {
1378 QString number = QString::number(blockNumber + 1);
1379 painter.setPen(Qt::black);
1380 painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number);
1381 }
1382
1383 block = block.next();
1384 top = bottom;
1385 bottom = top + (int)blockBoundingRect(block).height();
1386 ++blockNumber;
1387 }
1388 }
1389
1390 class PropertyListDialog: public QDialog
1391 {
1392 int type;
1393
1394 public:
1395 PropertyListDialog(int type, QWidget* parent)
1396 : QDialog(parent)
1397 , type(type)
1398 {}
1399
1400 void accept() override
1401 {
1402 auto edit = this->findChild<PropertyListEditor*>();
1403 QStringList lines;
1404 if (edit) {
1405 QString inputText = edit->toPlainText();
1406 if (!inputText.isEmpty()) { // let pass empty input, regardless of the type, so user
1407 // can void the value
1408 lines = inputText.split(QStringLiteral("\n"));
1409 }
1410 }
1411 if (!lines.isEmpty()) {
1412 if (type == 1) { // floats
1413 bool ok;
1414 int line = 1;
1415 for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) {
1416 it->toDouble(&ok);
1417 if (!ok) {
1418 QMessageBox::critical(
1419 this,
1420 tr("Invalid input"),
1421 tr("Input in line %1 is not a number").arg(line)
1422 );
1423 return;
1424 }
1425 }
1426 }
1427 else if (type == 2) { // integers
1428 bool ok;
1429 int line = 1;
1430 for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) {
1431 it->toInt(&ok);
1432 if (!ok) {
1433 QMessageBox::critical(
1434 this,
1435 tr("Invalid input"),
1436 tr("Input in line %1 is not a number").arg(line)
1437 );
1438 return;
1439 }
1440 }
1441 }
1442 }
1443 QDialog::accept();
1444 }
1445 };
1446
1447 // --------------------------------------------------------------------
1448
1449 LabelEditor::LabelEditor(QWidget* parent)
1450 : QWidget(parent)
1451 {
1452 type = String;
1453 auto layout = new QHBoxLayout(this);
1454 layout->setContentsMargins(0, 0, 0, 0);
1455 layout->setSpacing(2);
1456
1457 lineEdit = new QLineEdit(this);
1458 layout->addWidget(lineEdit);
1459
1460 connect(lineEdit, &QLineEdit::textChanged, this, &LabelEditor::validateText);
1461
1462 button = new QPushButton(QStringLiteral("…"), this);
1463 #if defined(Q_OS_MACOS)
1464 button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct
1465 #endif
1466 layout->addWidget(button);
1467
1468 connect(button, &QPushButton::clicked, this, &LabelEditor::changeText);
1469
1470 setFocusProxy(lineEdit);
1471 }
1472
1473 LabelEditor::~LabelEditor() = default;
1474
1475 void LabelEditor::resizeEvent(QResizeEvent* e)
1476 {
1477 button->setFixedWidth(e->size().height());
1478 button->setFixedHeight(e->size().height());
1479 }
1480
1481 QString LabelEditor::text() const
1482 {
1483 return this->plainText;
1484 }
1485
1486 void LabelEditor::setText(const QString& s)
1487 {
1488 this->plainText = s;
1489
1490 QString text = QStringLiteral("[%1]").arg(this->plainText);
1491 lineEdit->setText(text);
1492 }
1493
1494 void LabelEditor::changeText()
1495 {
1496 PropertyListDialog* dlg = new PropertyListDialog(static_cast<int>(type), this);
1497 dlg->setAttribute(Qt::WA_DeleteOnClose);
1498 dlg->setWindowTitle(tr("List"));
1499
1500 auto hboxLayout = new QVBoxLayout(dlg);
1501 auto buttonBox = new QDialogButtonBox(dlg);
1502 buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
1503
1504 auto edit = new PropertyListEditor(dlg);
1505 edit->setPlainText(this->plainText);
1506
1507 hboxLayout->addWidget(edit);
1508 hboxLayout->addWidget(buttonBox);
1509 connect(buttonBox, &QDialogButtonBox::accepted, dlg, &PropertyListDialog::accept);
1510 connect(buttonBox, &QDialogButtonBox::rejected, dlg, &PropertyListDialog::reject);
1511 connect(dlg, &PropertyListDialog::accepted, this, [&] {
1512 QString inputText = edit->toPlainText();
1513 QString text = QStringLiteral("[%1]").arg(inputText);
1514 lineEdit->setText(text);
1515 });
1516
1517 dlg->exec();
1518 }
1519
1520 /**
1521 * Validates if the input of the lineedit is a valid list.
1522 */
1523 void LabelEditor::validateText(const QString& text)
1524 {
1525 if (text.startsWith(QLatin1String("[")) && text.endsWith(QLatin1String("]"))) {
1526 this->plainText = text.mid(1, text.size() - 2);
1527 Q_EMIT textChanged(this->plainText);
1528 }
1529 }
1530
1531 /**
1532 * Sets the browse button's text to \a txt.
1533 */
1534 void LabelEditor::setButtonText(const QString& txt)
1535 {
1536 button->setText(txt);
1537 int w1 = 2 * QtTools::horizontalAdvance(button->fontMetrics(), txt);
1538 int w2 = 2 * QtTools::horizontalAdvance(button->fontMetrics(), QStringLiteral(" … "));
1539 button->setFixedWidth((w1 > w2 ? w1 : w2));
1540 }
1541
1542 /**
1543 * Returns the browse button's text.
1544 */
1545 QString LabelEditor::buttonText() const
1546 {
1547 return button->text();
1548 }
1549
1550 void LabelEditor::setInputType(InputType t)
1551 {
1552 this->type = t;
1553 }
1554
1555 // --------------------------------------------------------------------
1556
1557 ExpLineEdit::ExpLineEdit(QWidget* parent, bool expressionOnly)
1558 : QLineEdit(parent)
1559 , autoClose(expressionOnly)
1560 {
1561 makeLabel(this);
1562
1563 QObject::connect(iconLabel, &ExpressionLabel::clicked, this, &ExpLineEdit::openFormulaDialog);
1564 if (expressionOnly) {
1565 QMetaObject::invokeMethod(
1566 this,
1567 "openFormulaDialog",
1568 Qt::QueuedConnection,
1569 QGenericReturnArgument()
1570 );
1571 }
1572 }
1573
1574 bool ExpLineEdit::apply(const std::string& propName)
1575 {
1576
1577 if (!ExpressionBinding::apply(propName)) {
1578 if (!autoClose) {
1579 QString val = QString::fromUtf8(Base::Interpreter().strToPython(text().toUtf8()).c_str());
1580 Gui::Command::doCommand(
1581 Gui::Command::Doc,
1582 "%s = \"%s\"",
1583 propName.c_str(),
1584 val.toUtf8().constData()
1585 );
1586 }
1587 return true;
1588 }
1589
1590 return false;
1591 }
1592
1593 void ExpLineEdit::bind(const ObjectIdentifier& _path)
1594 {
1595
1596 ExpressionBinding::bind(_path);
1597
1598 int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth);
1599 setStyleSheet(QStringLiteral("QLineEdit { padding-right: %1px } ")
1600 .arg(iconLabel->sizeHint().width() + frameWidth + 1));
1601
1602 iconLabel->show();
1603 }
1604
1605 void ExpLineEdit::setExpression(std::shared_ptr<Expression> expr)
1606 {
1607 Q_ASSERT(isBound());
1608
1609 try {
1610 ExpressionBinding::setExpression(expr);
1611 }
1612 catch (const Base::Exception&) {
1613 setReadOnly(true);
1614 QPalette p(palette());
1615 p.setColor(QPalette::Active, QPalette::Text, Qt::red);
1616 setPalette(p);
1617 iconLabel->setToolTip(tr("An error occurred -- see Report View for information"));
1618 }
1619 }
1620
1621 void ExpLineEdit::onChange()
1622 {
1623
1624 if (getExpression()) {
1625 std::unique_ptr<Expression> result(getExpression()->eval());
1626 if (result->isDerivedFrom<App::StringExpression>()) {
1627 setText(
1628 QString::fromUtf8(static_cast<App::StringExpression*>(result.get())->getText().c_str())
1629 );
1630 }
1631 else {
1632 setText(QString::fromUtf8(result->toString().c_str()));
1633 }
1634 setReadOnly(true);
1635 iconLabel->setPixmap(getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight)));
1636
1637 QPalette p(palette());
1638 p.setColor(QPalette::Text, Qt::lightGray);
1639 setPalette(p);
1640 iconLabel->setExpressionText(QString::fromStdString(getExpression()->toString()));
1641 }
1642 else {
1643 setReadOnly(false);
1644 iconLabel->setPixmap(
1645 getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight))
1646 );
1647 QPalette p(palette());
1648 p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text));
1649 setPalette(p);
1650 iconLabel->setExpressionText(QString());
1651 }
1652 }
1653
1654 void ExpLineEdit::resizeEvent(QResizeEvent* event)
1655 {
1656 QLineEdit::resizeEvent(event);
1657
1658 int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth);
1659
1660 QSize sz = iconLabel->sizeHint();
1661 iconLabel->move(rect().right() - frameWidth - sz.width(), rect().center().y() - sz.height() / 2);
1662
1663 try {
1664 if (isBound() && getExpression()) {
1665 setReadOnly(true);
1666 QPixmap pixmap = getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight));
1667 iconLabel->setPixmap(pixmap);
1668
1669 QPalette p(palette());
1670 p.setColor(QPalette::Text, Qt::lightGray);
1671 setPalette(p);
1672 iconLabel->setExpressionText(QString::fromStdString(getExpression()->toString()));
1673 }
1674 else {
1675 setReadOnly(false);
1676 QPixmap pixmap
1677 = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight));
1678 iconLabel->setPixmap(pixmap);
1679
1680 QPalette p(palette());
1681 p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text));
1682 setPalette(p);
1683 iconLabel->setExpressionText(QString());
1684 }
1685 }
1686 catch (const Base::Exception&) {
1687 setReadOnly(true);
1688 QPalette p(palette());
1689 p.setColor(QPalette::Active, QPalette::Text, Qt::red);
1690 setPalette(p);
1691 iconLabel->setToolTip(tr("An error occurred -- see Report View for information"));
1692 }
1693 }
1694
1695 void ExpLineEdit::openFormulaDialog()
1696 {
1697 Q_ASSERT(isBound());
1698
1699 auto box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), Unit(), this);
1700 connect(box, &Dialog::DlgExpressionInput::finished, this, &ExpLineEdit::finishFormulaDialog);
1701 box->show();
1702
1703 QPoint pos = mapToGlobal(QPoint(0, 0));
1704 box->move(pos - box->expressionPosition());
1705 Gui::adjustDialogPosition(box);
1706 }
1707
1708 void ExpLineEdit::finishFormulaDialog()
1709 {
1710 auto box = qobject_cast<Gui::Dialog::DlgExpressionInput*>(sender());
1711 if (!box) {
1712 qWarning() << "Sender is not a Gui::Dialog::DlgExpressionInput";
1713 return;
1714 }
1715
1716 if (box->result() == QDialog::Accepted) {
1717 setExpression(box->getExpression());
1718 }
1719 else if (box->discardedFormula()) {
1720 setExpression(std::shared_ptr<Expression>());
1721 }
1722
1723 onChange();
1724 box->deleteLater();
1725
1726 if (autoClose) {
1727 this->deleteLater();
1728 }
1729 }
1730
1731 void ExpLineEdit::keyPressEvent(QKeyEvent* event)
1732 {
1733 if (!hasExpression()) {
1734 QLineEdit::keyPressEvent(event);
1735 }
1736 }
1737
1738 // --------------------------------------------------------------------
1739
1740 ButtonGroup::ButtonGroup(QObject* parent)
1741 : QButtonGroup(parent)
1742 , _exclusive(true)
1743 {
1744 QButtonGroup::setExclusive(false);
1745
1746 connect(
1747 this,
1748 qOverload<QAbstractButton*>(&QButtonGroup::buttonClicked),
1749 [this](QAbstractButton* button) {
1750 if (exclusive()) {
1751 const auto btns = buttons();
1752 for (auto btn : btns) {
1753 if (btn && btn != button && btn->isCheckable()) {
1754 btn->setChecked(false);
1755 }
1756 }
1757 }
1758 }
1759 );
1760 }
1761
1762 void ButtonGroup::setExclusive(bool on)
1763 {
1764 _exclusive = on;
1765 }
1766
1767 bool ButtonGroup::exclusive() const
1768 {
1769 return _exclusive;
1770 }
1771
1772 namespace Gui
1773 {
1774
1775 void adjustDialogPosition(QDialog* dialog)
1776 {
1777 if (!dialog) {
1778 return;
1779 }
1780 const MainWindow* mw = getMainWindow();
1781 if (!mw) {
1782 return;
1783 }
1784
1785 dialog->adjustSize(); // ensure correct size
1786
1787 const QRect mainWindowRect {mw->mapToGlobal(QPoint(0, 0)), mw->size()};
1788 const QRect dialogRect {dialog->frameGeometry()};
1789
1790 const bool isFullyInside = mainWindowRect.contains(dialogRect);
1791 if (isFullyInside) {
1792 return;
1793 }
1794
1795 const bool isCompletelyOutside = !mainWindowRect.intersects(dialogRect);
1796 if (isCompletelyOutside) {
1797 return;
1798 }
1799
1800 const int margin = 5;
1801 const QRect availableArea = mainWindowRect.adjusted(margin, margin, -margin, -margin);
1802
1803 QPoint adjustedTopLeft = dialogRect.topLeft();
1804
1805 adjustedTopLeft.setX(
1806 std::clamp(adjustedTopLeft.x(), availableArea.left(), availableArea.right() - dialogRect.width())
1807 );
1808
1809 adjustedTopLeft.setY(
1810 std::clamp(adjustedTopLeft.y(), availableArea.top(), availableArea.bottom() - dialogRect.height())
1811 );
1812
1813 dialog->move(adjustedTopLeft);
1814 }
1815
1816 } // namespace Gui
1817
1818 #include "moc_Widgets.cpp"