Gui: Prepare for clang-format (#16051)

* Gui: Prepare for clang-format

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
wwmayer
2024-09-02 17:48:55 +02:00
committed by GitHub
parent e98ffc3060
commit 977e13795a
31 changed files with 4133 additions and 3093 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -23,12 +23,12 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Inventor/actions/SoGetBoundingBoxAction.h>
# include <Inventor/nodes/SoClipPlane.h>
# include <Inventor/nodes/SoGroup.h>
# include <Inventor/sensors/SoTimerSensor.h>
# include <QDockWidget>
# include <QPointer>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/nodes/SoClipPlane.h>
#include <Inventor/nodes/SoGroup.h>
#include <Inventor/sensors/SoTimerSensor.h>
#include <QDockWidget>
#include <QPointer>
#endif
#include "Clipping.h"
@@ -39,7 +39,8 @@
using namespace Gui::Dialog;
class Clipping::Private {
class Clipping::Private
{
public:
Ui_Clipping ui;
QPointer<Gui::View3DInventor> view;
@@ -48,30 +49,30 @@ public:
SoClipPlane* clipY;
SoClipPlane* clipZ;
SoClipPlane* clipView;
bool flipX{false};
bool flipY{false};
bool flipZ{false};
bool flipX {false};
bool flipY {false};
bool flipZ {false};
SoTimerSensor* sensor;
Private()
{
clipX = new SoClipPlane();
clipX->on.setValue(false);
clipX->plane.setValue(SbPlane(SbVec3f(1,0,0),0));
clipX->plane.setValue(SbPlane(SbVec3f(1, 0, 0), 0));
clipX->ref();
clipY = new SoClipPlane();
clipY->on.setValue(false);
clipY->plane.setValue(SbPlane(SbVec3f(0,1,0),0));
clipY->plane.setValue(SbPlane(SbVec3f(0, 1, 0), 0));
clipY->ref();
clipZ = new SoClipPlane();
clipZ->on.setValue(false);
clipZ->plane.setValue(SbPlane(SbVec3f(0,0,1),0));
clipZ->plane.setValue(SbPlane(SbVec3f(0, 0, 1), 0));
clipZ->ref();
clipView = new SoClipPlane();
clipView->on.setValue(false);
clipView->plane.setValue(SbPlane(SbVec3f(0,0,1),0));
clipView->plane.setValue(SbPlane(SbVec3f(0, 0, 1), 0));
clipView->ref();
node = nullptr;
@@ -85,7 +86,7 @@ public:
clipView->unref();
delete sensor;
}
static void moveCallback(void * data, SoSensor * sensor)
static void moveCallback(void* data, SoSensor* sensor)
{
Q_UNUSED(sensor);
auto self = static_cast<Private*>(data);
@@ -93,7 +94,7 @@ public:
Gui::View3DInventorViewer* view = self->view->getViewer();
SoClipPlane* clip = self->clipView;
SbPlane pln = clip->plane.getValue();
clip->plane.setValue(SbPlane(view->getViewDirection(),pln.getDistanceFromOrigin()));
clip->plane.setValue(SbPlane(view->getViewDirection(), pln.getDistanceFromOrigin()));
}
}
};
@@ -101,27 +102,27 @@ public:
/* TRANSLATOR Gui::Dialog::Clipping */
Clipping::Clipping(Gui::View3DInventor* view, QWidget* parent)
: QDialog(parent)
, d(new Private)
: QDialog(parent)
, d(new Private)
{
// create widgets
d->ui.setupUi(this);
setupConnections();
d->ui.clipView->setRange(-INT_MAX,INT_MAX);
d->ui.clipView->setRange(-INT_MAX, INT_MAX);
d->ui.clipView->setSingleStep(0.1f);
d->ui.clipX->setRange(-INT_MAX,INT_MAX);
d->ui.clipX->setRange(-INT_MAX, INT_MAX);
d->ui.clipX->setSingleStep(0.1f);
d->ui.clipY->setRange(-INT_MAX,INT_MAX);
d->ui.clipY->setRange(-INT_MAX, INT_MAX);
d->ui.clipY->setSingleStep(0.1f);
d->ui.clipZ->setRange(-INT_MAX,INT_MAX);
d->ui.clipZ->setRange(-INT_MAX, INT_MAX);
d->ui.clipZ->setSingleStep(0.1f);
d->ui.dirX->setRange(-INT_MAX,INT_MAX);
d->ui.dirX->setRange(-INT_MAX, INT_MAX);
d->ui.dirX->setSingleStep(0.1f);
d->ui.dirY->setRange(-INT_MAX,INT_MAX);
d->ui.dirY->setRange(-INT_MAX, INT_MAX);
d->ui.dirY->setSingleStep(0.1f);
d->ui.dirZ->setRange(-INT_MAX,INT_MAX);
d->ui.dirZ->setRange(-INT_MAX, INT_MAX);
d->ui.dirZ->setSingleStep(0.1f);
d->ui.dirZ->setValue(1.0f);
@@ -146,7 +147,7 @@ Clipping::Clipping(Gui::View3DInventor* view, QWidget* parent)
d->ui.clipZ->setValue(cnt[2]);
int minDecimals = 2;
float lenx, leny,lenz;
float lenx, leny, lenz;
box.getSize(lenx, leny, lenz);
int steps = 100;
float minlen = std::min<float>(lenx, std::min<float>(leny, lenz));
@@ -192,7 +193,7 @@ Clipping* Clipping::makeDockWidget(Gui::View3DInventor* view)
auto clipping = new Clipping(view);
Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance();
QDockWidget* dw = pDockMgr->addDockWindow("Clipping", clipping, Qt::LeftDockWidgetArea);
dw->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable);
dw->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
dw->show();
return clipping;
@@ -211,6 +212,7 @@ Clipping::~Clipping()
void Clipping::setupConnections()
{
// clang-format off
connect(d->ui.groupBoxX, &QGroupBox::toggled,
this, &Clipping::onGroupBoxXToggled);
connect(d->ui.groupBoxY, &QGroupBox::toggled,
@@ -243,6 +245,7 @@ void Clipping::setupConnections()
this, &Clipping::onDirYValueChanged);
connect(d->ui.dirZ, qOverload<double>(&QDoubleSpinBox::valueChanged),
this, &Clipping::onDirZValueChanged);
// clang-format on
}
void Clipping::reject()
@@ -284,40 +287,40 @@ void Clipping::onGroupBoxZToggled(bool on)
void Clipping::onClipXValueChanged(double val)
{
SbPlane pln = d->clipX->plane.getValue();
d->clipX->plane.setValue(SbPlane(pln.getNormal(),d->flipX ? -val : val));
d->clipX->plane.setValue(SbPlane(pln.getNormal(), d->flipX ? -val : val));
}
void Clipping::onClipYValueChanged(double val)
{
SbPlane pln = d->clipY->plane.getValue();
d->clipY->plane.setValue(SbPlane(pln.getNormal(),d->flipY ? -val : val));
d->clipY->plane.setValue(SbPlane(pln.getNormal(), d->flipY ? -val : val));
}
void Clipping::onClipZValueChanged(double val)
{
SbPlane pln = d->clipZ->plane.getValue();
d->clipZ->plane.setValue(SbPlane(pln.getNormal(),d->flipZ ? -val : val));
d->clipZ->plane.setValue(SbPlane(pln.getNormal(), d->flipZ ? -val : val));
}
void Clipping::onFlipClipXClicked()
{
d->flipX = !d->flipX;
SbPlane pln = d->clipX->plane.getValue();
d->clipX->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin()));
d->clipX->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin()));
}
void Clipping::onFlipClipYClicked()
{
d->flipY = !d->flipY;
SbPlane pln = d->clipY->plane.getValue();
d->clipY->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin()));
d->clipY->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin()));
}
void Clipping::onFlipClipZClicked()
{
d->flipZ = !d->flipZ;
SbPlane pln = d->clipZ->plane.getValue();
d->clipZ->plane.setValue(SbPlane(-pln.getNormal(),-pln.getDistanceFromOrigin()));
d->clipZ->plane.setValue(SbPlane(-pln.getNormal(), -pln.getDistanceFromOrigin()));
}
void Clipping::onGroupBoxViewToggled(bool on)
@@ -334,7 +337,7 @@ void Clipping::onGroupBoxViewToggled(bool on)
void Clipping::onClipViewValueChanged(double val)
{
SbPlane pln = d->clipView->plane.getValue();
d->clipView->plane.setValue(SbPlane(pln.getNormal(),val));
d->clipView->plane.setValue(SbPlane(pln.getNormal(), val));
}
void Clipping::onFromViewClicked()
@@ -343,7 +346,7 @@ void Clipping::onFromViewClicked()
Gui::View3DInventorViewer* view = d->view->getViewer();
SbVec3f dir = view->getViewDirection();
SbPlane pln = d->clipView->plane.getValue();
d->clipView->plane.setValue(SbPlane(dir,pln.getDistanceFromOrigin()));
d->clipView->plane.setValue(SbPlane(dir, pln.getDistanceFromOrigin()));
}
}
@@ -354,10 +357,12 @@ void Clipping::onAdjustViewdirectionToggled(bool on)
d->ui.dirZ->setDisabled(on);
d->ui.fromView->setDisabled(on);
if (on)
if (on) {
d->sensor->schedule();
else
}
else {
d->sensor->unschedule();
}
}
void Clipping::onDirXValueChanged(double)
@@ -367,9 +372,10 @@ void Clipping::onDirXValueChanged(double)
double z = d->ui.dirZ->value();
SbPlane pln = d->clipView->plane.getValue();
SbVec3f normal(x,y,z);
if (normal.sqrLength() > 0.0f)
d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin()));
SbVec3f normal(x, y, z);
if (normal.sqrLength() > 0.0f) {
d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin()));
}
}
void Clipping::onDirYValueChanged(double)
@@ -379,9 +385,10 @@ void Clipping::onDirYValueChanged(double)
double z = d->ui.dirZ->value();
SbPlane pln = d->clipView->plane.getValue();
SbVec3f normal(x,y,z);
if (normal.sqrLength() > 0.0f)
d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin()));
SbVec3f normal(x, y, z);
if (normal.sqrLength() > 0.0f) {
d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin()));
}
}
void Clipping::onDirZValueChanged(double)
@@ -391,9 +398,10 @@ void Clipping::onDirZValueChanged(double)
double z = d->ui.dirZ->value();
SbPlane pln = d->clipView->plane.getValue();
SbVec3f normal(x,y,z);
if (normal.sqrLength() > 0.0f)
d->clipView->plane.setValue(SbPlane(normal,pln.getDistanceFromOrigin()));
SbVec3f normal(x, y, z);
if (normal.sqrLength() > 0.0f) {
d->clipView->plane.setValue(SbPlane(normal, pln.getDistanceFromOrigin()));
}
}
#include "moc_Clipping.cpp"

View File

@@ -22,9 +22,9 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QCursor>
# include <QTimer>
# include <Inventor/nodes/SoCamera.h>
#include <QCursor>
#include <QTimer>
#include <Inventor/nodes/SoCamera.h>
#endif
#include <Base/Tools.h>
@@ -43,7 +43,9 @@ using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::DemoMode */
DemoMode::DemoMode(QWidget* /*parent*/, Qt::WindowFlags fl)
: QDialog(nullptr, fl | Qt::WindowStaysOnTopHint), viewAxis(0, 0, -1), ui(new Ui_DemoMode)
: QDialog(nullptr, fl | Qt::WindowStaysOnTopHint)
, viewAxis(0, 0, -1)
, ui(new Ui_DemoMode)
{
// create widgets
ui->setupUi(this);
@@ -69,6 +71,7 @@ DemoMode::~DemoMode()
void DemoMode::setupConnections()
{
// clang-format off
connect(ui->playButton, &QPushButton::clicked,
this, &DemoMode::onPlayButtonToggled);
connect(ui->fullscreen, &QCheckBox::toggled,
@@ -81,16 +84,18 @@ void DemoMode::setupConnections()
this, &DemoMode::onAngleSliderValueChanged);
connect(ui->timeout, qOverload<int>(&QSpinBox::valueChanged),
this, &DemoMode::onTimeoutValueChanged);
// clang-format on
}
void DemoMode::reset()
{
onFullscreenToggled(false);
Gui::View3DInventor* view = activeView();
if (view)
if (view) {
view->getViewer()->stopAnimating();
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/View");
}
ParameterGrp::handle hGrp =
App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
hGrp->Notify("UseNavigationAnimations");
}
@@ -106,7 +111,7 @@ void DemoMode::reject()
QDialog::reject();
}
bool DemoMode::eventFilter(QObject *obj, QEvent *event)
bool DemoMode::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::MouseMove) {
if (ui->fullscreen->isChecked()) {
@@ -120,14 +125,15 @@ bool DemoMode::eventFilter(QObject *obj, QEvent *event)
return QDialog::eventFilter(obj, event);
}
void DemoMode::showEvent(QShowEvent *)
void DemoMode::showEvent(QShowEvent*)
{
if (this->wasHidden)
if (this->wasHidden) {
this->move(this->pnt);
}
this->wasHidden = false;
}
void DemoMode::hideEvent(QHideEvent *)
void DemoMode::hideEvent(QHideEvent*)
{
this->pnt = this->pos();
this->wasHidden = true;
@@ -150,21 +156,23 @@ Gui::View3DInventor* DemoMode::activeView() const
float DemoMode::getSpeed(int v) const
{
float speed = (static_cast<float>(v)) / 10.0f; // let 10.0 be the maximum speed
float speed = (static_cast<float>(v)) / 10.0f; // let 10.0 be the maximum speed
return speed;
}
SbVec3f DemoMode::getDirection(Gui::View3DInventor* view) const
{
SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera();
if (!cam)
if (!cam) {
return this->viewAxis;
}
SbRotation rot = cam->orientation.getValue();
SbRotation inv = rot.inverse();
SbVec3f vec(this->viewAxis);
inv.multVec(vec, vec);
if (vec.length() < FLT_EPSILON)
if (vec.length() < FLT_EPSILON) {
vec = this->viewAxis;
}
vec.normalize();
return vec;
}
@@ -174,11 +182,12 @@ void DemoMode::onAngleSliderValueChanged(int v)
Gui::View3DInventor* view = activeView();
if (view) {
SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera();
if (!cam)
if (!cam) {
return;
auto angle = Base::toRadians<float>(/*90-v*/v - this->oldvalue);
}
auto angle = Base::toRadians<float>(/*90-v*/ v - this->oldvalue);
SbRotation rot(SbVec3f(-1, 0, 0), angle);
reorientCamera(cam ,rot);
reorientCamera(cam, rot);
this->oldvalue = v;
if (view->getViewer()->isSpinning()) {
startAnimation(view);
@@ -186,13 +195,12 @@ void DemoMode::onAngleSliderValueChanged(int v)
}
}
void DemoMode::reorientCamera(SoCamera * cam, const SbRotation & rot)
void DemoMode::reorientCamera(SoCamera* cam, const SbRotation& rot)
{
// Find global coordinates of focal point.
SbVec3f direction;
cam->orientation.getValue().multVec(SbVec3f(0, 0, -1), direction);
SbVec3f focalpoint = cam->position.getValue() +
cam->focalDistance.getValue() * direction;
SbVec3f focalpoint = cam->position.getValue() + cam->focalDistance.getValue() * direction;
// Set new orientation value by accumulating the new rotation.
cam->orientation = rot * cam->orientation.getValue();
@@ -220,7 +228,7 @@ void DemoMode::onPlayButtonToggled(bool pressed)
SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera();
if (cam) {
SbRotation rot = cam->orientation.getValue();
SbVec3f vec(0,-1,0);
SbVec3f vec(0, -1, 0);
rot.multVec(vec, this->viewAxis);
}
}
@@ -239,9 +247,11 @@ void DemoMode::onFullscreenToggled(bool on)
{
Gui::View3DInventor* view = activeView();
if (view) {
CommandManager &rcCmdMgr = Application::Instance->commandManager();
CommandManager& rcCmdMgr = Application::Instance->commandManager();
Command* cmd = rcCmdMgr.getCommandByName("Std_ViewDockUndockFullscreen");
if (cmd) cmd->invoke(on ? MDIView::FullScreen : MDIView::Child);
if (cmd) {
cmd->invoke(on ? MDIView::FullScreen : MDIView::Child);
}
this->activateWindow();
ui->playButton->setChecked(false);
}
@@ -277,16 +287,19 @@ void DemoMode::startAnimation(Gui::View3DInventor* view)
void DemoMode::onTimerCheckToggled(bool on)
{
if (on)
if (on) {
timer->start();
else
}
else {
timer->stop();
}
}
void DemoMode::changeEvent(QEvent *e)
void DemoMode::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange)
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
}
QDialog::changeEvent(e);
}

View File

@@ -22,15 +22,15 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QDialogButtonBox>
# include <QDir>
# include <QFileDialog>
# include <QFileInfo>
# include <QHeaderView>
# include <QImageReader>
# include <QKeySequence>
# include <QLineEdit>
# include <QMessageBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QHeaderView>
#include <QImageReader>
#include <QKeySequence>
#include <QLineEdit>
#include <QMessageBox>
#endif
#include "DlgActionsImp.h"
@@ -54,31 +54,35 @@ using namespace Gui::Dialog;
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgCustomActionsImp::DlgCustomActionsImp( QWidget* parent )
: CustomizeActionPage(parent)
, ui(new Ui_DlgCustomActions)
DlgCustomActionsImp::DlgCustomActionsImp(QWidget* parent)
: CustomizeActionPage(parent)
, ui(new Ui_DlgCustomActions)
{
ui->setupUi(this);
setupConnections();
// search for all macros
std::string cMacroPath = App::GetApplication().
GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath",App::Application::getUserMacroDir().c_str());
std::string cMacroPath =
App::GetApplication()
.GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str());
QDir d(QString::fromUtf8(cMacroPath.c_str()), QLatin1String("*.FCMacro *.py"));
for (unsigned int i=0; i<d.count(); i++ )
ui->actionMacros->insertItem(0,d[i],QVariant(false));
for (unsigned int i = 0; i < d.count(); i++) {
ui->actionMacros->insertItem(0, d[i], QVariant(false));
}
QString systemMacroDirStr = QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro");
QString systemMacroDirStr =
QString::fromStdString(App::Application::getHomePath()) + QString::fromLatin1("Macro");
d = QDir(systemMacroDirStr, QLatin1String("*.FCMacro *.py"));
if (d.exists()) {
for (unsigned int i=0; i<d.count(); i++ ) {
ui->actionMacros->insertItem(0,d[i],QVariant(true));
for (unsigned int i = 0; i < d.count(); i++) {
ui->actionMacros->insertItem(0, d[i], QVariant(true));
}
}
QStringList labels; labels << tr("Icons") << tr("Macros");
QStringList labels;
labels << tr("Icons") << tr("Macros");
ui->actionListWidget->setHeaderLabels(labels);
ui->actionListWidget->header()->hide();
ui->actionListWidget->setIconSize(QSize(32, 32));
@@ -90,12 +94,14 @@ DlgCustomActionsImp::DlgCustomActionsImp( QWidget* parent )
/** Destroys the object and frees any allocated resources */
DlgCustomActionsImp::~DlgCustomActionsImp()
{
if (bChanged)
if (bChanged) {
MacroCommand::save();
}
}
void DlgCustomActionsImp::setupConnections()
{
// clang-format off
connect(ui->actionListWidget, &QTreeWidget::itemActivated,
this, &DlgCustomActionsImp::onActionListWidgetItemActivated);
connect(ui->buttonChoosePixmap, &QToolButton::clicked,
@@ -106,10 +112,12 @@ void DlgCustomActionsImp::setupConnections()
this, &DlgCustomActionsImp::onButtonRemoveActionClicked);
connect(ui->buttonReplaceAction, &QPushButton::clicked,
this, &DlgCustomActionsImp::onButtonReplaceActionClicked);
// clang-format on
}
bool DlgCustomActionsImp::event(QEvent* e)
{
// clang-format off
bool ok = QWidget::event(e);
if (e->type() == QEvent::ParentChange || e->type() == QEvent::ParentAboutToChange)
@@ -139,6 +147,7 @@ bool DlgCustomActionsImp::event(QEvent* e)
}
}
}
// clang-format on
return ok;
}
@@ -148,7 +157,7 @@ void DlgCustomActionsImp::onAddMacroAction(const QByteArray&)
bChanged = true;
}
void DlgCustomActionsImp::onRemoveMacroAction(const QByteArray &name)
void DlgCustomActionsImp::onRemoveMacroAction(const QByteArray& name)
{
bChanged = true;
ShortcutManager::instance()->reset(name.constData());
@@ -163,22 +172,23 @@ void DlgCustomActionsImp::showActions()
{
CommandManager& rclMan = Application::Instance->commandManager();
std::vector<Command*> aclCurMacros = rclMan.getGroupCommands("Macros");
for (const auto & aclCurMacro : aclCurMacros)
{
for (const auto& aclCurMacro : aclCurMacros) {
auto item = new QTreeWidgetItem(ui->actionListWidget);
QByteArray actionName = aclCurMacro->getName();
item->setData(1, Qt::UserRole, actionName);
item->setText(1, QString::fromUtf8(aclCurMacro->getMenuText()));
item->setSizeHint(0, QSize(32, 32));
if ( aclCurMacro->getPixmap() )
if (aclCurMacro->getPixmap()) {
item->setIcon(0, BitmapFactory().pixmap(aclCurMacro->getPixmap()));
}
}
}
void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem *item)
void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem* item)
{
if (!item)
return; // no valid item
if (!item) {
return; // no valid item
}
// search for the command in the manager and if necessary in the temporary created ones
QByteArray actionName = item->data(1, Qt::UserRole).toByteArray();
@@ -187,105 +197,108 @@ void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem *item)
auto pScript = dynamic_cast<MacroCommand*>(pCmd);
// if valid command
if ( pScript )
{
if (pScript) {
bool bFound = false;
QString scriptName = QString::fromUtf8(pScript->getScriptName());
for (int i = 0; i<ui->actionMacros->count(); i++)
{
if (ui->actionMacros->itemText(i).startsWith(scriptName, Qt::CaseSensitive))
{
for (int i = 0; i < ui->actionMacros->count(); i++) {
if (ui->actionMacros->itemText(i).startsWith(scriptName, Qt::CaseSensitive)) {
bFound = true;
ui->actionMacros->setCurrentIndex(i);
break;
}
}
if (!bFound)
{
QMessageBox::critical(this, tr("Macro not found"),
tr("Sorry, couldn't find macro file '%1'.").arg(scriptName));
if (!bFound) {
QMessageBox::critical(this,
tr("Macro not found"),
tr("Sorry, couldn't find macro file '%1'.").arg(scriptName));
}
// fill up labels with the command's data
ui->actionWhatsThis -> setText(QString::fromUtf8(pScript->getWhatsThis()));
ui->actionMenu -> setText(QString::fromUtf8(pScript->getMenuText()));
ui->actionToolTip -> setText(QString::fromUtf8(pScript->getToolTipText()));
ui->actionStatus -> setText(QString::fromUtf8(pScript->getStatusTip()));
ui->actionAccel -> setText(ShortcutManager::instance()->getShortcut(
actionName.constData(), pScript->getAccel()));
ui->actionWhatsThis->setText(QString::fromUtf8(pScript->getWhatsThis()));
ui->actionMenu->setText(QString::fromUtf8(pScript->getMenuText()));
ui->actionToolTip->setText(QString::fromUtf8(pScript->getToolTipText()));
ui->actionStatus->setText(QString::fromUtf8(pScript->getStatusTip()));
ui->actionAccel->setText(
ShortcutManager::instance()->getShortcut(actionName.constData(), pScript->getAccel()));
ui->pixmapLabel->clear();
m_sPixmap.clear();
const char* name = pScript->getPixmap();
if (name && std::strlen(name) > 2)
{
if (name && std::strlen(name) > 2) {
QPixmap p = Gui::BitmapFactory().pixmap(pScript->getPixmap());
ui->pixmapLabel->setPixmap(p);
m_sPixmap = QString::fromUtf8(name); // can also be a path
m_sPixmap = QString::fromUtf8(name); // can also be a path
}
}
}
void DlgCustomActionsImp::onButtonAddActionClicked()
{
if (ui->actionMacros-> currentText().isEmpty())
{
QMessageBox::warning(this, tr("Empty macro"),tr("Please specify the macro first."));
if (ui->actionMacros->currentText().isEmpty()) {
QMessageBox::warning(this, tr("Empty macro"), tr("Please specify the macro first."));
return;
}
if (ui->actionMenu->text().isEmpty())
{
QMessageBox::warning(this, tr("Empty text"),tr("Please specify the menu text first."));
if (ui->actionMenu->text().isEmpty()) {
QMessageBox::warning(this, tr("Empty text"), tr("Please specify the menu text first."));
return;
}
// search for the command in the manager
CommandManager& rclMan = Application::Instance->commandManager();
QByteArray actionName = QString::fromStdString(rclMan.newMacroName()).toLatin1();
auto macro = new MacroCommand(actionName, ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool());
rclMan.addCommand( macro );
auto macro =
new MacroCommand(actionName,
ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool());
rclMan.addCommand(macro);
// add new action
auto item = new QTreeWidgetItem(ui->actionListWidget);
item->setData(1, Qt::UserRole, actionName);
item->setText(1, ui->actionMenu->text());
item->setSizeHint(0, QSize(32, 32));
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
item->setIcon(0, ui->pixmapLabel->pixmap(Qt::ReturnByValue));
#else
if (ui->pixmapLabel->pixmap())
if (ui->pixmapLabel->pixmap()) {
item->setIcon(0, *ui->pixmapLabel->pixmap());
}
#endif
// Convert input text into utf8
if (!ui->actionWhatsThis->text().isEmpty())
if (!ui->actionWhatsThis->text().isEmpty()) {
macro->setWhatsThis(ui->actionWhatsThis->text().toUtf8());
}
ui->actionWhatsThis->clear();
if (!ui->actionMacros-> currentText().isEmpty())
if (!ui->actionMacros->currentText().isEmpty()) {
macro->setScriptName(ui->actionMacros->currentText().toUtf8());
}
if (!ui->actionMenu->text().isEmpty())
if (!ui->actionMenu->text().isEmpty()) {
macro->setMenuText(ui->actionMenu->text().toUtf8());
}
ui->actionMenu->clear();
if (!ui->actionToolTip->text().isEmpty())
if (!ui->actionToolTip->text().isEmpty()) {
macro->setToolTipText(ui->actionToolTip->text().toUtf8());
}
ui->actionToolTip->clear();
if (!ui->actionStatus->text().isEmpty())
if (!ui->actionStatus->text().isEmpty()) {
macro->setStatusTip(ui->actionStatus->text().toUtf8());
}
ui->actionStatus->clear();
if (!m_sPixmap.isEmpty())
if (!m_sPixmap.isEmpty()) {
macro->setPixmap(m_sPixmap.toLatin1());
}
ui->pixmapLabel->clear();
m_sPixmap.clear();
if (!ui->actionAccel->text().isEmpty()) {
ShortcutManager::instance()->setShortcut(
actionName.constData(), ui->actionAccel->text().toLatin1().constData());
ShortcutManager::instance()->setShortcut(actionName.constData(),
ui->actionAccel->text().toLatin1().constData());
}
ui->actionAccel->clear();
@@ -296,15 +309,13 @@ void DlgCustomActionsImp::onButtonAddActionClicked()
void DlgCustomActionsImp::onButtonReplaceActionClicked()
{
QTreeWidgetItem* item = ui->actionListWidget->currentItem();
if (!item)
{
QMessageBox::warning(this, tr("No item selected"),tr("Please select a macro item first."));
if (!item) {
QMessageBox::warning(this, tr("No item selected"), tr("Please select a macro item first."));
return;
}
if (ui->actionMenu->text().isEmpty())
{
QMessageBox::warning(this, tr("Empty text"),tr("Please specify the menu text first."));
if (ui->actionMenu->text().isEmpty()) {
QMessageBox::warning(this, tr("Empty text"), tr("Please specify the menu text first."));
return;
}
@@ -314,30 +325,37 @@ void DlgCustomActionsImp::onButtonReplaceActionClicked()
CommandManager& rclMan = Application::Instance->commandManager();
Command* pCmd = rclMan.getCommandByName(actionName.constData());
auto macro = dynamic_cast<MacroCommand*>(pCmd);
if (!macro)
if (!macro) {
return;
}
if (!ui->actionWhatsThis->text().isEmpty())
if (!ui->actionWhatsThis->text().isEmpty()) {
macro->setWhatsThis(ui->actionWhatsThis->text().toUtf8());
}
ui->actionWhatsThis->clear();
if (!ui->actionMacros-> currentText().isEmpty())
if (!ui->actionMacros->currentText().isEmpty()) {
macro->setScriptName(ui->actionMacros->currentText().toUtf8());
}
if (!ui->actionMenu->text().isEmpty())
if (!ui->actionMenu->text().isEmpty()) {
macro->setMenuText(ui->actionMenu->text().toUtf8());
}
ui->actionMenu->clear();
if (!ui->actionToolTip->text().isEmpty())
if (!ui->actionToolTip->text().isEmpty()) {
macro->setToolTipText(ui->actionToolTip->text().toUtf8());
}
ui->actionToolTip->clear();
if (!ui->actionStatus->text().isEmpty())
if (!ui->actionStatus->text().isEmpty()) {
macro->setStatusTip(ui->actionStatus->text().toUtf8());
}
ui->actionStatus->clear();
if (!m_sPixmap.isEmpty())
if (!m_sPixmap.isEmpty()) {
macro->setPixmap(m_sPixmap.toLatin1());
}
ui->pixmapLabel->clear();
m_sPixmap.clear();
@@ -348,33 +366,35 @@ void DlgCustomActionsImp::onButtonReplaceActionClicked()
// check whether the macro is already in use
Action* action = macro->getAction();
if (action)
{
if (action) {
// does all the text related stuff
action->setText(QString::fromUtf8(macro->getMenuText()));
action->setToolTip(QString::fromUtf8(macro->getToolTipText()));
action->setWhatsThis(QString::fromUtf8(macro->getWhatsThis()));
action->setStatusTip(QString::fromUtf8(macro->getStatusTip()));
if (macro->getPixmap())
if (macro->getPixmap()) {
action->setIcon(Gui::BitmapFactory().pixmap(macro->getPixmap()));
action->setShortcut(ShortcutManager::instance()->getShortcut(
actionName.constData(), macro->getAccel()));
}
action->setShortcut(
ShortcutManager::instance()->getShortcut(actionName.constData(), macro->getAccel()));
}
// emit signal to notify the container widget
Q_EMIT modifyMacroAction(actionName);
// call this at the end because it internally invokes the highlight method
if (macro->getPixmap())
if (macro->getPixmap()) {
item->setIcon(0, Gui::BitmapFactory().pixmap(macro->getPixmap()));
}
}
void DlgCustomActionsImp::onButtonRemoveActionClicked()
{
// remove item from list view
QTreeWidgetItem* item = ui->actionListWidget->currentItem();
if (!item)
if (!item) {
return;
}
int current = ui->actionListWidget->indexOfTopLevelItem(item);
ui->actionListWidget->takeTopLevelItem(current);
QByteArray actionName = item->data(1, Qt::UserRole).toByteArray();
@@ -383,10 +403,8 @@ void DlgCustomActionsImp::onButtonRemoveActionClicked()
// if the command is registered in the manager just remove it
CommandManager& rclMan = Application::Instance->commandManager();
std::vector<Command*> aclCurMacros = rclMan.getGroupCommands("Macros");
for (auto & aclCurMacro : aclCurMacros)
{
if (actionName == aclCurMacro->getName())
{
for (auto& aclCurMacro : aclCurMacros) {
if (actionName == aclCurMacro->getName()) {
// emit signal to notify the container widget
Q_EMIT removeMacroAction(actionName);
// remove from manager and delete it immediately
@@ -397,7 +415,8 @@ void DlgCustomActionsImp::onButtonRemoveActionClicked()
}
IconDialog::IconDialog(QWidget* parent)
: QDialog(parent), ui(new Ui_DlgChooseIcon)
: QDialog(parent)
, ui(new Ui_DlgChooseIcon)
{
ui->setupUi(this);
ui->listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@@ -407,7 +426,7 @@ IconDialog::IconDialog(QWidget* parent)
QListWidgetItem* item;
QStringList names = BitmapFactory().findIconFiles();
for (const auto & name : names) {
for (const auto& name : names) {
item = new QListWidgetItem(ui->listWidget);
item->setIcon(QIcon(BitmapFactory().pixmap((const char*)name.toUtf8())));
item->setText(QFileInfo(name).baseName());
@@ -433,12 +452,13 @@ void IconDialog::resizeEvent(QResizeEvent*)
void IconDialog::onAddIconPath()
{
// Add the user defined paths
Base::Reference<ParameterGrp> group = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/Bitmaps");
Base::Reference<ParameterGrp> group =
App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Bitmaps");
std::vector<std::string> paths = group->GetASCIIs("CustomPath");
QStringList pathList;
for (const auto & path : paths)
for (const auto& path : paths) {
pathList << QString::fromUtf8(path.c_str());
}
IconFolders dlg(pathList, this);
dlg.setWindowTitle(tr("Icon folders"));
@@ -447,7 +467,7 @@ void IconDialog::onAddIconPath()
// Write to user config
group->Clear();
int index=0;
int index = 0;
for (QStringList::iterator it = paths.begin(); it != paths.end(); ++it, ++index) {
std::stringstream str;
str << "CustomPath" << index;
@@ -455,19 +475,21 @@ void IconDialog::onAddIconPath()
}
QStringList search = BitmapFactory().getPaths();
for (auto & it : search) {
for (auto& it : search) {
it = QDir::toNativeSeparators(it);
}
for (const auto & path : paths) {
for (const auto& path : paths) {
if (search.indexOf(path) < 0) {
QStringList filters;
QList<QByteArray> formats = QImageReader::supportedImageFormats();
for (const auto & format : formats)
filters << QString::fromLatin1("*.%1").arg(QString::fromLatin1(format).toLower());
for (const auto& format : formats) {
filters << QString::fromLatin1("*.%1").arg(
QString::fromLatin1(format).toLower());
}
QDir d(path);
d.setNameFilters(filters);
QFileInfoList fi = d.entryInfoList();
for (const auto & jt : fi) {
for (const auto& jt : fi) {
QString file = jt.absoluteFilePath();
auto item = new QListWidgetItem(ui->listWidget);
item->setIcon(QIcon(file));
@@ -494,12 +516,12 @@ void DlgCustomActionsImp::onButtonChoosePixmapClicked()
QListWidgetItem* item = dlg.currentItem();
if (item) {
m_sPixmap = item->text();
ui->pixmapLabel->setPixmap(item->icon().pixmap(QSize(32,32)));
ui->pixmapLabel->setPixmap(item->icon().pixmap(QSize(32, 32)));
}
}
}
void DlgCustomActionsImp::changeEvent(QEvent *e)
void DlgCustomActionsImp::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
@@ -511,9 +533,11 @@ void DlgCustomActionsImp::changeEvent(QEvent *e)
}
IconFolders::IconFolders(const QStringList& paths, QWidget* parent)
: QDialog(parent), restart(false), maxLines(10)
: QDialog(parent)
, restart(false)
, maxLines(10)
{
resize(600,400);
resize(600, 400);
auto buttonBox = new QDialogButtonBox(this);
buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, this, &IconFolders::accept);
@@ -530,7 +554,7 @@ IconFolders::IconFolders(const QStringList& paths, QWidget* parent)
// Add the user defined paths
int numPaths = static_cast<int>(paths.size());
int maxRow = this->maxLines;
for (int row=0; row<maxRow; row++) {
for (int row = 0; row < maxRow; row++) {
auto edit = new QLineEdit(this);
edit->setReadOnly(true);
gridLayout->addWidget(edit, row, 0, 1, 1);
@@ -559,8 +583,9 @@ IconFolders::IconFolders(const QStringList& paths, QWidget* parent)
gridLayout->addWidget(addButton, maxRow, 1, 1, 1);
connect(addButton, &QPushButton::clicked, this, &IconFolders::addFolder);
if (numPaths >= this->maxLines)
if (numPaths >= this->maxLines) {
addButton->setDisabled(true);
}
}
IconFolders::~IconFolders() = default;
@@ -569,11 +594,13 @@ void IconFolders::addFolder()
{
int countHidden = -1;
QStringList paths;
for (const auto & it : buttonMap) {
for (const auto& it : buttonMap) {
if (it.first->isHidden()) {
countHidden++;
if (countHidden == 0) {
QString dir = QFileDialog::getExistingDirectory(this, IconDialog::tr("Add icon folder"), QString());
QString dir = QFileDialog::getExistingDirectory(this,
IconDialog::tr("Add icon folder"),
QString());
if (!dir.isEmpty() && paths.indexOf(dir) < 0) {
QLineEdit* edit = it.first;
edit->setVisible(true);
@@ -597,14 +624,16 @@ void IconFolders::removeFolder()
{
if (!restart) {
restart = true;
QMessageBox::information(this, tr("Remove folder"),
QMessageBox::information(
this,
tr("Remove folder"),
tr("Removing a folder only takes effect after an application restart."));
}
addButton->setEnabled(true);
auto remove = static_cast<QPushButton*>(sender());
QLineEdit* edit = nullptr;
for (const auto & it : buttonMap) {
for (const auto& it : buttonMap) {
if (it.second == remove) {
edit = it.first;
}
@@ -628,7 +657,7 @@ void IconFolders::removeFolder()
QStringList IconFolders::getPaths() const
{
QStringList paths;
for (const auto & it : buttonMap) {
for (const auto& it : buttonMap) {
if (!it.first->isHidden()) {
paths << QDir::toNativeSeparators(it.first->text());
}

View File

@@ -30,17 +30,17 @@
using namespace Gui::Dialog;
DlgCustomizeSpNavSettings::DlgCustomizeSpNavSettings(QWidget *parent) :
CustomizeActionPage(parent)
, ui(new Ui_DlgCustomizeSpNavSettings)
, init(false)
DlgCustomizeSpNavSettings::DlgCustomizeSpNavSettings(QWidget* parent)
: CustomizeActionPage(parent)
, ui(new Ui_DlgCustomizeSpNavSettings)
, init(false)
{
auto app = qobject_cast<GUIApplicationNativeEventAware *>(QApplication::instance());
auto app = qobject_cast<GUIApplicationNativeEventAware*>(QApplication::instance());
if (!app)
if (!app) {
return;
if (!app->isSpaceballPresent())
{
}
if (!app->isSpaceballPresent()) {
this->setWindowTitle(tr("Spaceball Motion"));
this->setMessage(tr("No Spaceball Present"));
return;
@@ -55,6 +55,7 @@ DlgCustomizeSpNavSettings::~DlgCustomizeSpNavSettings() = default;
void DlgCustomizeSpNavSettings::setupConnections()
{
// clang-format off
connect(ui->CBDominant, &QCheckBox::clicked,
this, &DlgCustomizeSpNavSettings::on_CBDominant_clicked);
connect(ui->CBFlipYZ, &QCheckBox::clicked,
@@ -105,11 +106,12 @@ void DlgCustomizeSpNavSettings::setupConnections()
this, &DlgCustomizeSpNavSettings::on_ButtonDefaultSpNavMotions_clicked);
connect(ui->ButtonCalibrate, &QPushButton::clicked,
this, &DlgCustomizeSpNavSettings::on_ButtonCalibrate_clicked);
// clang-format on
}
void DlgCustomizeSpNavSettings::setMessage(const QString& message)
{
auto messageLabel = new QLabel(message,this);
auto messageLabel = new QLabel(message, this);
auto layout = new QVBoxLayout();
auto layout2 = new QHBoxLayout();
layout2->addStretch();
@@ -119,7 +121,7 @@ void DlgCustomizeSpNavSettings::setMessage(const QString& message)
this->setLayout(layout);
}
void DlgCustomizeSpNavSettings::changeEvent(QEvent *e)
void DlgCustomizeSpNavSettings::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
if (this->init) {
@@ -127,8 +129,10 @@ void DlgCustomizeSpNavSettings::changeEvent(QEvent *e)
}
else {
this->setWindowTitle(tr("Spaceball Motion"));
QLabel *messageLabel = this->findChild<QLabel*>();
if (messageLabel) messageLabel->setText(tr("No Spaceball Present"));
QLabel* messageLabel = this->findChild<QLabel*>();
if (messageLabel) {
messageLabel->setText(tr("No Spaceball Present"));
}
}
}
QWidget::changeEvent(e);
@@ -136,7 +140,11 @@ void DlgCustomizeSpNavSettings::changeEvent(QEvent *e)
ParameterGrp::handle DlgCustomizeSpNavSettings::spaceballMotionGroup() const
{
static ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Spaceball")->GetGroup("Motion");
static ParameterGrp::handle group = App::GetApplication()
.GetUserParameter()
.GetGroup("BaseApp")
->GetGroup("Spaceball")
->GetGroup("Motion");
return group;
}
@@ -153,49 +161,51 @@ void DlgCustomizeSpNavSettings::initialize()
ui->CBTranslations->setChecked(spaceballMotionGroup()->GetBool("Translations", true));
ui->SliderGlobal->setValue(spaceballMotionGroup()->GetInt("GlobalSensitivity", 0));
ui->CBEnablePanLR ->setChecked(spaceballMotionGroup()->GetBool("PanLREnable", true));
ui->CBEnablePanLR->setChecked(spaceballMotionGroup()->GetBool("PanLREnable", true));
ui->CBReversePanLR->setChecked(spaceballMotionGroup()->GetBool("PanLRReverse", false));
ui->SliderPanLR ->setValue(spaceballMotionGroup()->GetInt("PanLRSensitivity", 0));
ui->SliderPanLR->setValue(spaceballMotionGroup()->GetInt("PanLRSensitivity", 0));
ui->CBEnablePanUD ->setChecked(spaceballMotionGroup()->GetBool("PanUDEnable", true));
ui->CBEnablePanUD->setChecked(spaceballMotionGroup()->GetBool("PanUDEnable", true));
ui->CBReversePanUD->setChecked(spaceballMotionGroup()->GetBool("PanUDReverse", false));
ui->SliderPanUD ->setValue(spaceballMotionGroup()->GetInt("PanUDSensitivity", 0));
ui->SliderPanUD->setValue(spaceballMotionGroup()->GetInt("PanUDSensitivity", 0));
ui->CBEnableZoom ->setChecked(spaceballMotionGroup()->GetBool("ZoomEnable", true));
ui->CBEnableZoom->setChecked(spaceballMotionGroup()->GetBool("ZoomEnable", true));
ui->CBReverseZoom->setChecked(spaceballMotionGroup()->GetBool("ZoomReverse", false));
ui->SliderZoom ->setValue(spaceballMotionGroup()->GetInt("ZoomSensitivity", 0));
ui->SliderZoom->setValue(spaceballMotionGroup()->GetInt("ZoomSensitivity", 0));
ui->CBEnableTilt ->setChecked(spaceballMotionGroup()->GetBool("TiltEnable", true));
ui->CBEnableTilt->setChecked(spaceballMotionGroup()->GetBool("TiltEnable", true));
ui->CBReverseTilt->setChecked(spaceballMotionGroup()->GetBool("TiltReverse", false));
ui->SliderTilt ->setValue(spaceballMotionGroup()->GetInt("TiltSensitivity", 0));
ui->SliderTilt->setValue(spaceballMotionGroup()->GetInt("TiltSensitivity", 0));
ui->CBEnableRoll ->setChecked(spaceballMotionGroup()->GetBool("RollEnable", true));
ui->CBEnableRoll->setChecked(spaceballMotionGroup()->GetBool("RollEnable", true));
ui->CBReverseRoll->setChecked(spaceballMotionGroup()->GetBool("RollReverse", false));
ui->SliderRoll ->setValue(spaceballMotionGroup()->GetInt("RollSensitivity", 0));
ui->SliderRoll->setValue(spaceballMotionGroup()->GetInt("RollSensitivity", 0));
ui->CBEnableSpin ->setChecked(spaceballMotionGroup()->GetBool("SpinEnable", true));
ui->CBEnableSpin->setChecked(spaceballMotionGroup()->GetBool("SpinEnable", true));
ui->CBReverseSpin->setChecked(spaceballMotionGroup()->GetBool("SpinReverse", false));
ui->SliderSpin ->setValue(spaceballMotionGroup()->GetInt("SpinSensitivity", 0));
ui->SliderSpin->setValue(spaceballMotionGroup()->GetInt("SpinSensitivity", 0));
ui->CBEnableTilt ->setEnabled(ui->CBRotations->isChecked());
ui->CBEnableTilt->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->SliderTilt ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->CBEnableRoll ->setEnabled(ui->CBRotations->isChecked());
ui->SliderTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->CBEnableRoll->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->SliderRoll ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->CBEnableSpin ->setEnabled(ui->CBRotations->isChecked());
ui->SliderRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->CBEnableSpin->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
ui->SliderSpin ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
ui->SliderSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
ui->CBEnablePanLR ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->SliderPanLR ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->CBEnablePanUD ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->SliderPanUD ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->CBEnableZoom ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReverseZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->SliderZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked()
&& ui->CBEnablePanLR->isChecked());
ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked()
&& ui->CBEnablePanUD->isChecked());
ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked());
ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->SliderZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
}
void DlgCustomizeSpNavSettings::on_ButtonDefaultSpNavMotions_clicked()
@@ -218,30 +228,32 @@ void DlgCustomizeSpNavSettings::on_CBRotations_clicked()
{
spaceballMotionGroup()->SetBool("Rotations", ui->CBRotations->isChecked());
ui->CBEnableTilt ->setEnabled(ui->CBRotations->isChecked());
ui->CBEnableTilt->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->SliderTilt ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->CBEnableRoll ->setEnabled(ui->CBRotations->isChecked());
ui->SliderTilt->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableTilt->isChecked());
ui->CBEnableRoll->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->SliderRoll ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->CBEnableSpin ->setEnabled(ui->CBRotations->isChecked());
ui->SliderRoll->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableRoll->isChecked());
ui->CBEnableSpin->setEnabled(ui->CBRotations->isChecked());
ui->CBReverseSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
ui->SliderSpin ->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
ui->SliderSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBTranslations_clicked()
{
spaceballMotionGroup()->SetBool("Translations", ui->CBTranslations->isChecked());
ui->CBEnablePanLR ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->SliderPanLR ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->CBEnablePanUD ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->SliderPanUD ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->CBEnableZoom ->setEnabled(ui->CBTranslations->isChecked());
ui->CBReverseZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->SliderZoom ->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked()
&& ui->CBEnablePanLR->isChecked());
ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked());
ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked());
ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked()
&& ui->CBEnablePanUD->isChecked());
ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked());
ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked());
ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
ui->SliderZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked());
}
void DlgCustomizeSpNavSettings::on_SliderGlobal_sliderReleased()
@@ -254,7 +266,7 @@ void DlgCustomizeSpNavSettings::on_CBEnablePanLR_clicked()
spaceballMotionGroup()->SetBool("PanLREnable", ui->CBEnablePanLR->isChecked());
ui->CBReversePanLR->setEnabled(ui->CBEnablePanLR->isChecked());
ui->SliderPanLR ->setEnabled(ui->CBEnablePanLR->isChecked());
ui->SliderPanLR->setEnabled(ui->CBEnablePanLR->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReversePanLR_clicked()
@@ -272,7 +284,7 @@ void DlgCustomizeSpNavSettings::on_CBEnablePanUD_clicked()
spaceballMotionGroup()->SetBool("PanUDEnable", ui->CBEnablePanUD->isChecked());
ui->CBReversePanUD->setEnabled(ui->CBEnablePanUD->isChecked());
ui->SliderPanUD ->setEnabled(ui->CBEnablePanUD->isChecked());
ui->SliderPanUD->setEnabled(ui->CBEnablePanUD->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReversePanUD_clicked()
@@ -289,8 +301,8 @@ void DlgCustomizeSpNavSettings::on_CBEnableZoom_clicked()
{
spaceballMotionGroup()->SetBool("ZoomEnable", ui->CBEnableZoom->isChecked());
ui->CBReverseZoom ->setEnabled(ui->CBEnableZoom->isChecked());
ui->SliderZoom ->setEnabled(ui->CBEnableZoom->isChecked());
ui->CBReverseZoom->setEnabled(ui->CBEnableZoom->isChecked());
ui->SliderZoom->setEnabled(ui->CBEnableZoom->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReverseZoom_clicked()
@@ -308,7 +320,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableTilt_clicked()
spaceballMotionGroup()->SetBool("TiltEnable", ui->CBEnableTilt->isChecked());
ui->CBReverseTilt->setEnabled(ui->CBEnableTilt->isChecked());
ui->SliderTilt ->setEnabled(ui->CBEnableTilt->isChecked());
ui->SliderTilt->setEnabled(ui->CBEnableTilt->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReverseTilt_clicked()
@@ -326,7 +338,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableRoll_clicked()
spaceballMotionGroup()->SetBool("RollEnable", ui->CBEnableRoll->isChecked());
ui->CBReverseRoll->setEnabled(ui->CBEnableRoll->isChecked());
ui->SliderRoll ->setEnabled(ui->CBEnableRoll->isChecked());
ui->SliderRoll->setEnabled(ui->CBEnableRoll->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReverseRoll_clicked()
@@ -344,7 +356,7 @@ void DlgCustomizeSpNavSettings::on_CBEnableSpin_clicked()
spaceballMotionGroup()->SetBool("SpinEnable", ui->CBEnableSpin->isChecked());
ui->CBReverseSpin->setEnabled(ui->CBEnableSpin->isChecked());
ui->SliderSpin ->setEnabled(ui->CBEnableSpin->isChecked());
ui->SliderSpin->setEnabled(ui->CBEnableSpin->isChecked());
}
void DlgCustomizeSpNavSettings::on_CBReverseSpin_clicked()
@@ -357,21 +369,21 @@ void DlgCustomizeSpNavSettings::on_SliderSpin_sliderReleased()
spaceballMotionGroup()->SetInt("SpinSensitivity", ui->SliderSpin->value());
}
void DlgCustomizeSpNavSettings::onAddMacroAction(const QByteArray &macroName)
void DlgCustomizeSpNavSettings::onAddMacroAction(const QByteArray& macroName)
{
//don't need to do anything here.
// don't need to do anything here.
Q_UNUSED(macroName);
}
void DlgCustomizeSpNavSettings::onRemoveMacroAction(const QByteArray &macroName)
void DlgCustomizeSpNavSettings::onRemoveMacroAction(const QByteArray& macroName)
{
//don't need to do anything here.
// don't need to do anything here.
Q_UNUSED(macroName);
}
void DlgCustomizeSpNavSettings::onModifyMacroAction(const QByteArray &macroName)
void DlgCustomizeSpNavSettings::onModifyMacroAction(const QByteArray& macroName)
{
//don't need to do anything here.
// don't need to do anything here.
Q_UNUSED(macroName);
}

View File

@@ -24,10 +24,10 @@
#include "PreCompiled.h"
#include <boost/signals2/connection.hpp>
#ifndef _PreComp_
# include <QAction>
# include <QHeaderView>
# include <QMessageBox>
# include <QTimer>
#include <QAction>
#include <QHeaderView>
#include <QMessageBox>
#include <QTimer>
#endif
#include <Base/Parameter.h>
@@ -48,19 +48,25 @@
using namespace Gui::Dialog;
namespace Gui { namespace Dialog {
using GroupMap = std::vector< std::pair<QLatin1String, QString> >;
namespace Gui
{
namespace Dialog
{
using GroupMap = std::vector<std::pair<QLatin1String, QString>>;
struct GroupMap_find {
struct GroupMap_find
{
const QLatin1String& item;
explicit GroupMap_find(const QLatin1String& item) : item(item) {}
bool operator () (const std::pair<QLatin1String, QString>& elem) const
explicit GroupMap_find(const QLatin1String& item)
: item(item)
{}
bool operator()(const std::pair<QLatin1String, QString>& elem) const
{
return elem.first == item;
}
};
}
}
} // namespace Dialog
} // namespace Gui
/* TRANSLATOR Gui::Dialog::DlgCustomKeyboardImp */
@@ -71,23 +77,28 @@ struct GroupMap_find {
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgCustomKeyboardImp::DlgCustomKeyboardImp( QWidget* parent )
: CustomizeActionPage(parent)
, ui(new Ui_DlgCustomKeyboard)
, firstShow(true)
DlgCustomKeyboardImp::DlgCustomKeyboardImp(QWidget* parent)
: CustomizeActionPage(parent)
, ui(new Ui_DlgCustomKeyboard)
, firstShow(true)
{
ui->setupUi(this);
setupConnections();
// Force create actions for all commands with shortcut to register with ShortcutManager
for (auto cmd : Application::Instance->commandManager().getAllCommands()) {
if (cmd->getShortcut().size())
if (cmd->getShortcut().size()) {
cmd->initAction();
}
}
QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, this,
[](const char *cmdName) {
if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName))
QObject::connect(
ShortcutManager::instance(),
&ShortcutManager::shortcutChanged,
this,
[](const char* cmdName) {
if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) {
cmd->initAction();
}
});
conn = initCommandWidgets(ui->commandTreeWidget,
@@ -101,7 +112,7 @@ DlgCustomKeyboardImp::DlgCustomKeyboardImp( QWidget* parent )
ui->accelLineEditShortcut);
ui->shortcutTimeout->onRestore();
QTimer *timer = new QTimer(this);
QTimer* timer = new QTimer(this);
QObject::connect(ui->shortcutTimeout, qOverload<int>(&QSpinBox::valueChanged), timer, [=](int) {
timer->start(100);
});
@@ -115,6 +126,7 @@ DlgCustomKeyboardImp::~DlgCustomKeyboardImp() = default;
void DlgCustomKeyboardImp::setupConnections()
{
// clang-format off
connect(ui->categoryBox, qOverload<int>(&QComboBox::activated),
this, &DlgCustomKeyboardImp::onCategoryBoxActivated);
connect(ui->commandTreeWidget, &QTreeWidget::currentItemChanged,
@@ -129,49 +141,52 @@ void DlgCustomKeyboardImp::setupConnections()
this, &DlgCustomKeyboardImp::onButtonResetAllClicked);
connect(ui->editShortcut, &AccelLineEdit::textChanged,
this, &DlgCustomKeyboardImp::onEditShortcutTextChanged);
// clang-format on
}
void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit *edit,
QComboBox *combo,
QTreeWidget *commandTreeWidget,
QTreeWidgetItem *separatorItem)
void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit* edit,
QComboBox* combo,
QTreeWidget* commandTreeWidget,
QTreeWidgetItem* separatorItem)
{
edit->setPlaceholderText(tr("Type to search..."));
auto completer = new CommandCompleter(edit, edit);
QObject::connect(completer, &CommandCompleter::commandActivated,
[=](const QByteArray &name) {
CommandManager & cCmdMgr = Application::Instance->commandManager();
Command *cmd = cCmdMgr.getCommandByName(name.constData());
if (!cmd)
return;
QObject::connect(completer, &CommandCompleter::commandActivated, [=](const QByteArray& name) {
CommandManager& cCmdMgr = Application::Instance->commandManager();
Command* cmd = cCmdMgr.getCommandByName(name.constData());
if (!cmd) {
return;
}
QString group = QString::fromLatin1(cmd->getGroupName());
int index = combo->findData(group);
if (index < 0)
QString group = QString::fromLatin1(cmd->getGroupName());
int index = combo->findData(group);
if (index < 0) {
return;
}
if (index != combo->currentIndex()) {
QSignalBlocker blocker(combo);
combo->setCurrentIndex(index);
populateCommandList(commandTreeWidget, separatorItem, combo);
}
for (int i = 0; i < commandTreeWidget->topLevelItemCount(); ++i) {
QTreeWidgetItem* item = commandTreeWidget->topLevelItem(i);
if (item->data(1, Qt::UserRole).toByteArray() == name) {
commandTreeWidget->setCurrentItem(item);
return;
if (index != combo->currentIndex()) {
QSignalBlocker blocker(combo);
combo->setCurrentIndex(index);
populateCommandList(commandTreeWidget, separatorItem, combo);
}
for (int i=0 ; i<commandTreeWidget->topLevelItemCount(); ++i) {
QTreeWidgetItem *item = commandTreeWidget->topLevelItem(i);
if (item->data(1, Qt::UserRole).toByteArray() == name) {
commandTreeWidget->setCurrentItem(item);
return;
}
}
});
}
});
}
void DlgCustomKeyboardImp::populateCommandList(QTreeWidget *commandTreeWidget,
QTreeWidgetItem *separatorItem,
QComboBox *combo)
void DlgCustomKeyboardImp::populateCommandList(QTreeWidget* commandTreeWidget,
QTreeWidgetItem* separatorItem,
QComboBox* combo)
{
QByteArray current;
if (auto item = commandTreeWidget->currentItem())
if (auto item = commandTreeWidget->currentItem()) {
current = item->data(1, Qt::UserRole).toByteArray();
}
if (separatorItem) {
commandTreeWidget->takeTopLevelItem(commandTreeWidget->indexOfTopLevelItem(separatorItem));
@@ -181,36 +196,39 @@ void DlgCustomKeyboardImp::populateCommandList(QTreeWidget *commandTreeWidget,
commandTreeWidget->addTopLevelItem(separatorItem);
}
CommandManager & cCmdMgr = Application::Instance->commandManager();
CommandManager& cCmdMgr = Application::Instance->commandManager();
auto group = combo->itemData(combo->currentIndex(), Qt::UserRole).toByteArray();
auto cmds = group == "All" ? cCmdMgr.getAllCommands()
: cCmdMgr.getGroupCommands(group.constData());
QTreeWidgetItem *currentItem = nullptr;
for (const Command *cmd : cmds) {
auto cmds =
group == "All" ? cCmdMgr.getAllCommands() : cCmdMgr.getGroupCommands(group.constData());
QTreeWidgetItem* currentItem = nullptr;
for (const Command* cmd : cmds) {
QTreeWidgetItem* item = new QTreeWidgetItem(commandTreeWidget);
item->setText(1, Action::commandMenuText(cmd));
item->setToolTip(1, Action::commandToolTip(cmd));
item->setData(1, Qt::UserRole, QByteArray(cmd->getName()));
item->setSizeHint(0, QSize(32, 32));
if (auto pixmap = cmd->getPixmap())
if (auto pixmap = cmd->getPixmap()) {
item->setIcon(0, BitmapFactory().iconFromTheme(pixmap));
}
item->setText(2, cmd->getShortcut());
if (auto accel = cmd->getAccel())
if (auto accel = cmd->getAccel()) {
item->setText(3, QKeySequence(QString::fromLatin1(accel)).toString());
}
if (current == cmd->getName())
if (current == cmd->getName()) {
currentItem = item;
}
}
if (currentItem)
if (currentItem) {
commandTreeWidget->setCurrentItem(currentItem);
}
commandTreeWidget->resizeColumnToContents(2);
commandTreeWidget->resizeColumnToContents(3);
}
boost::signals2::connection
DlgCustomKeyboardImp::initCommandList(QTreeWidget *commandTreeWidget,
QTreeWidgetItem *separatorItem,
QComboBox *combo)
boost::signals2::connection DlgCustomKeyboardImp::initCommandList(QTreeWidget* commandTreeWidget,
QTreeWidgetItem* separatorItem,
QComboBox* combo)
{
QStringList labels;
labels << tr("Icon") << tr("Command") << tr("Shortcut") << tr("Default");
@@ -225,30 +243,33 @@ DlgCustomKeyboardImp::initCommandList(QTreeWidget *commandTreeWidget,
// Using a timer to respond to command change for performance, and also
// because macro command may be added before proper initialization (null
// menu text, etc.)
QTimer *timer = new QTimer(combo);
QTimer* timer = new QTimer(combo);
timer->setSingleShot(true);
QObject::connect(timer, &QTimer::timeout, [=](){
QObject::connect(timer, &QTimer::timeout, [=]() {
populateCommandGroups(combo);
populateCommandList(commandTreeWidget, separatorItem, combo);
});
QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, timer, [timer]() {
timer->start(100);
});
QObject::connect(ShortcutManager::instance(),
&ShortcutManager::shortcutChanged,
timer,
[timer]() {
timer->start(100);
});
QObject::connect(combo, qOverload<int>(&QComboBox::activated), timer, [timer]() {
timer->start(100);
});
return Application::Instance->commandManager().signalChanged.connect([timer](){
return Application::Instance->commandManager().signalChanged.connect([timer]() {
timer->start(100);
});
}
void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList,
QAbstractButton *buttonUp,
QAbstractButton *buttonDown)
void DlgCustomKeyboardImp::initPriorityList(QTreeWidget* priorityList,
QAbstractButton* buttonUp,
QAbstractButton* buttonDown)
{
QStringList labels;
labels << tr("Name") << tr("Title");
@@ -259,18 +280,20 @@ void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList,
auto updatePriorityList = [priorityList](bool up) {
auto item = priorityList->currentItem();
if (!item)
if (!item) {
return;
}
int index = priorityList->indexOfTopLevelItem(item);
if (index < 0)
if (index < 0) {
return;
if ((index == 0 && up)
|| (index == priorityList->topLevelItemCount()-1 && !up))
}
if ((index == 0 && up) || (index == priorityList->topLevelItemCount() - 1 && !up)) {
return;
}
std::vector<QByteArray> actions;
for (int i=0; i<priorityList->topLevelItemCount(); ++i) {
for (int i = 0; i < priorityList->topLevelItemCount(); ++i) {
auto item = priorityList->topLevelItem(i);
actions.push_back(item->data(0, Qt::UserRole).toByteArray());
}
@@ -281,26 +304,28 @@ void DlgCustomKeyboardImp::initPriorityList(QTreeWidget *priorityList,
ShortcutManager::instance()->setPriorities(actions);
};
QObject::connect(buttonUp, &QAbstractButton::clicked, [=](){updatePriorityList(true);});
QObject::connect(buttonDown, &QAbstractButton::clicked, [=](){updatePriorityList(false);});
QObject::connect(priorityList, &QTreeWidget::currentItemChanged,
[=](QTreeWidgetItem *item){
buttonUp->setEnabled(item!=nullptr);
buttonDown->setEnabled(item!=nullptr);
}
);
QObject::connect(buttonUp, &QAbstractButton::clicked, [=]() {
updatePriorityList(true);
});
QObject::connect(buttonDown, &QAbstractButton::clicked, [=]() {
updatePriorityList(false);
});
QObject::connect(priorityList, &QTreeWidget::currentItemChanged, [=](QTreeWidgetItem* item) {
buttonUp->setEnabled(item != nullptr);
buttonDown->setEnabled(item != nullptr);
});
}
boost::signals2::connection
DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget,
QTreeWidgetItem *separatorItem,
QComboBox *comboGroups,
QLineEdit *editCommand,
QTreeWidget *priorityList,
QAbstractButton *buttonUp,
QAbstractButton *buttonDown,
Gui::AccelLineEdit *editShortcut,
Gui::AccelLineEdit *currentShortcut)
DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget* commandTreeWidget,
QTreeWidgetItem* separatorItem,
QComboBox* comboGroups,
QLineEdit* editCommand,
QTreeWidget* priorityList,
QAbstractButton* buttonUp,
QAbstractButton* buttonDown,
Gui::AccelLineEdit* editShortcut,
Gui::AccelLineEdit* currentShortcut)
{
initCommandCompleter(editCommand, comboGroups, commandTreeWidget, separatorItem);
auto conn = initCommandList(commandTreeWidget, separatorItem, comboGroups);
@@ -318,9 +343,12 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget,
QObject::connect(editShortcut, &QLineEdit::textChanged, timer, [timer]() {
timer->start(200);
});
QObject::connect(ShortcutManager::instance(), &ShortcutManager::priorityChanged, timer, [timer](){
timer->start(200);
});
QObject::connect(ShortcutManager::instance(),
&ShortcutManager::priorityChanged,
timer,
[timer]() {
timer->start(200);
});
QObject::connect(timer, &QTimer::timeout, [=]() {
populatePriorityList(priorityList, editShortcut, currentShortcut);
});
@@ -329,45 +357,51 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget *commandTreeWidget,
return conn;
}
void DlgCustomKeyboardImp::populatePriorityList(QTreeWidget *priorityList,
Gui::AccelLineEdit *editor,
Gui::AccelLineEdit *curShortcut)
void DlgCustomKeyboardImp::populatePriorityList(QTreeWidget* priorityList,
Gui::AccelLineEdit* editor,
Gui::AccelLineEdit* curShortcut)
{
QByteArray current;
if (auto currentItem = priorityList->currentItem())
if (auto currentItem = priorityList->currentItem()) {
current = currentItem->data(0, Qt::UserRole).toByteArray();
}
priorityList->clear();
QString sc;
if (!editor->isNone() && editor->text().size())
if (!editor->isNone() && editor->text().size()) {
sc = editor->text();
else if (curShortcut && !curShortcut->isNone())
}
else if (curShortcut && !curShortcut->isNone()) {
sc = curShortcut->text();
}
auto actionList = ShortcutManager::instance()->getActionsByShortcut(sc);
QTreeWidgetItem *currentItem = nullptr;
for (const auto &info : actionList) {
if (!info.second)
QTreeWidgetItem* currentItem = nullptr;
for (const auto& info : actionList) {
if (!info.second) {
continue;
}
QTreeWidgetItem* item = new QTreeWidgetItem(priorityList);
item->setText(0, QString::fromUtf8(info.first));
item->setText(1, Action::cleanTitle(info.second->text()));
item->setToolTip(0, info.second->toolTip());
item->setIcon(0, info.second->icon());
item->setData(0, Qt::UserRole, info.first);
if (current == info.first)
if (current == info.first) {
currentItem = item;
}
}
priorityList->resizeColumnToContents(0);
priorityList->resizeColumnToContents(1);
if (currentItem)
if (currentItem) {
priorityList->setCurrentItem(currentItem);
}
}
void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo)
void DlgCustomKeyboardImp::populateCommandGroups(QComboBox* combo)
{
CommandManager & cCmdMgr = Application::Instance->commandManager();
std::map<std::string,Command*> sCommands = cCmdMgr.getCommands();
CommandManager& cCmdMgr = Application::Instance->commandManager();
std::map<std::string, Command*> sCommands = cCmdMgr.getCommands();
GroupMap groupMap;
groupMap.push_back(std::make_pair(QLatin1String("File"), QString()));
@@ -377,16 +411,18 @@ void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo)
groupMap.push_back(std::make_pair(QLatin1String("Tools"), QString()));
groupMap.push_back(std::make_pair(QLatin1String("Window"), QString()));
groupMap.push_back(std::make_pair(QLatin1String("Help"), QString()));
groupMap.push_back(std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros")));
groupMap.push_back(
std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros")));
for (const auto & sCommand : sCommands) {
for (const auto& sCommand : sCommands) {
QLatin1String group(sCommand.second->getGroupName());
QString text = sCommand.second->translatedGroupName();
GroupMap::iterator jt;
jt = std::find_if(groupMap.begin(), groupMap.end(), GroupMap_find(group));
if (jt != groupMap.end()) {
if (jt->second.isEmpty())
if (jt->second.isEmpty()) {
jt->second = text;
}
}
else {
groupMap.push_back(std::make_pair(group, text));
@@ -394,10 +430,10 @@ void DlgCustomKeyboardImp::populateCommandGroups(QComboBox *combo)
}
groupMap.push_back(std::make_pair(QLatin1String("All"), tr("All")));
for (const auto & it : groupMap) {
for (const auto& it : groupMap) {
if (combo->findData(it.first) < 0) {
combo->addItem(it.second);
combo->setItemData(combo->count()-1, QVariant(it.first), Qt::UserRole);
combo->setItemData(combo->count() - 1, QVariant(it.first), Qt::UserRole);
}
}
}
@@ -416,23 +452,25 @@ void DlgCustomKeyboardImp::showEvent(QShowEvent* e)
/** Shows the description for the corresponding command */
void DlgCustomKeyboardImp::onCommandTreeWidgetCurrentItemChanged(QTreeWidgetItem* item)
{
if (!item)
if (!item) {
return;
}
QVariant data = item->data(1, Qt::UserRole);
QByteArray name = data.toByteArray(); // command name
QByteArray name = data.toByteArray(); // command name
CommandManager & cCmdMgr = Application::Instance->commandManager();
CommandManager& cCmdMgr = Application::Instance->commandManager();
Command* cmd = cCmdMgr.getCommandByName(name.constData());
if (cmd) {
QKeySequence ks = ShortcutManager::instance()->getShortcut(
cmd->getName(), cmd->getAccel());
QKeySequence ks = ShortcutManager::instance()->getShortcut(cmd->getName(), cmd->getAccel());
QKeySequence ks2 = QString::fromLatin1(cmd->getAccel());
QKeySequence ks3 = ui->editShortcut->text();
if (ks.isEmpty())
ui->accelLineEditShortcut->setText( tr("none") );
else
if (ks.isEmpty()) {
ui->accelLineEditShortcut->setText(tr("none"));
}
else {
ui->accelLineEditShortcut->setText(ks.toString(QKeySequence::NativeText));
}
ui->buttonAssign->setEnabled(!ui->editShortcut->text().isEmpty() && (ks != ks3));
ui->buttonReset->setEnabled((ks != ks2));
@@ -451,11 +489,12 @@ void DlgCustomKeyboardImp::onCategoryBoxActivated(int)
void DlgCustomKeyboardImp::setShortcutOfCurrentAction(const QString& accelText)
{
QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
if (!item)
if (!item) {
return;
}
QVariant data = item->data(1, Qt::UserRole);
QByteArray name = data.toByteArray(); // command name
QByteArray name = data.toByteArray(); // command name
QString portableText;
if (!accelText.isEmpty()) {
@@ -490,16 +529,17 @@ void DlgCustomKeyboardImp::onButtonClearClicked()
void DlgCustomKeyboardImp::onButtonResetClicked()
{
QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
if (!item)
if (!item) {
return;
}
QVariant data = item->data(1, Qt::UserRole);
QByteArray name = data.toByteArray(); // command name
QByteArray name = data.toByteArray(); // command name
ShortcutManager::instance()->reset(name);
QString txt = ShortcutManager::instance()->getShortcut(name);
ui->accelLineEditShortcut->setText((txt.isEmpty() ? tr("none") : txt));
ui->buttonReset->setEnabled( false );
ui->buttonReset->setEnabled(false);
}
/** Resets the accelerator of all commands to the default. */
@@ -510,32 +550,32 @@ void DlgCustomKeyboardImp::onButtonResetAllClicked()
}
/** Checks for an already occupied shortcut. */
void DlgCustomKeyboardImp::onEditShortcutTextChanged(const QString& )
void DlgCustomKeyboardImp::onEditShortcutTextChanged(const QString&)
{
QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
if (item) {
QVariant data = item->data(1, Qt::UserRole);
QByteArray name = data.toByteArray(); // command name
QByteArray name = data.toByteArray(); // command name
CommandManager & cCmdMgr = Application::Instance->commandManager();
CommandManager& cCmdMgr = Application::Instance->commandManager();
Command* cmd = cCmdMgr.getCommandByName(name.constData());
if (!ui->editShortcut->isNone())
if (!ui->editShortcut->isNone()) {
ui->buttonAssign->setEnabled(true);
}
else {
if (cmd && cmd->getAction() && cmd->getAction()->shortcut().isEmpty())
ui->buttonAssign->setEnabled(false); // both key sequences are empty
if (cmd && cmd->getAction() && cmd->getAction()->shortcut().isEmpty()) {
ui->buttonAssign->setEnabled(false); // both key sequences are empty
}
}
}
}
void DlgCustomKeyboardImp::onAddMacroAction(const QByteArray&)
{
}
{}
void DlgCustomKeyboardImp::onRemoveMacroAction(const QByteArray&)
{
}
{}
void DlgCustomKeyboardImp::onModifyMacroAction(const QByteArray&)
{
@@ -546,14 +586,14 @@ void DlgCustomKeyboardImp::onModifyMacroAction(const QByteArray&)
}
}
void DlgCustomKeyboardImp::changeEvent(QEvent *e)
void DlgCustomKeyboardImp::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
int count = ui->categoryBox->count();
CommandManager & cCmdMgr = Application::Instance->commandManager();
for (int i=0; i<count; i++) {
CommandManager& cCmdMgr = Application::Instance->commandManager();
for (int i = 0; i < count; i++) {
QVariant data = ui->categoryBox->itemData(i, Qt::UserRole);
std::vector<Command*> aCmds = cCmdMgr.getGroupCommands(data.toByteArray());
if (!aCmds.empty()) {

File diff suppressed because it is too large Load Diff

View File

@@ -22,10 +22,10 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QDir>
# include <QFile>
# include <QFileInfo>
# include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#endif
#include "DlgMacroRecordImp.h"
@@ -47,7 +47,7 @@ using namespace Gui::Dialog;
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl )
DlgMacroRecordImp::DlgMacroRecordImp(QWidget* parent, Qt::WindowFlags fl)
: QDialog(parent, fl)
, WindowParameter("Macro")
, ui(new Ui_DlgMacroRecord)
@@ -56,8 +56,10 @@ DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl )
setupConnections();
// get the macro home path
this->macroPath = QString::fromUtf8(getWindowParameter()->GetASCII("MacroPath",
App::Application::getUserMacroDir().c_str()).c_str());
this->macroPath =
QString::fromUtf8(getWindowParameter()
->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str())
.c_str());
this->macroPath = QDir::toNativeSeparators(QDir(this->macroPath).path() + QDir::separator());
// set the edit fields
@@ -67,7 +69,8 @@ DlgMacroRecordImp::DlgMacroRecordImp( QWidget* parent, Qt::WindowFlags fl )
this->macroManager = Application::Instance->macroManager();
// check if a macro recording is in progress
this->macroManager->isOpen() ? ui->buttonStart->setEnabled(false) : ui->buttonStop->setEnabled(false);
this->macroManager->isOpen() ? ui->buttonStart->setEnabled(false)
: ui->buttonStop->setEnabled(false);
}
/**
@@ -77,6 +80,7 @@ DlgMacroRecordImp::~DlgMacroRecordImp() = default;
void DlgMacroRecordImp::setupConnections()
{
// clang-format off
connect(ui->buttonStart, &QPushButton::clicked,
this, &DlgMacroRecordImp::onButtonStartClicked);
connect(ui->buttonStop, &QPushButton::clicked,
@@ -87,6 +91,7 @@ void DlgMacroRecordImp::setupConnections()
this, &DlgMacroRecordImp::onButtonChooseDirClicked);
connect(ui->lineEditMacroPath, &QLineEdit::textChanged,
this, &DlgMacroRecordImp::onMacroPathTextChanged);
// clang-format on
}
/**
@@ -96,14 +101,17 @@ void DlgMacroRecordImp::onButtonStartClicked()
{
// test if the path already set
if (ui->lineEditPath->text().isEmpty()) {
QMessageBox::information(getMainWindow(), tr("Macro recorder"),
tr("Specify first a place to save."));
QMessageBox::information(getMainWindow(),
tr("Macro recorder"),
tr("Specify first a place to save."));
return;
}
QDir dir(macroPath);
if (!dir.exists()) {
QMessageBox::information(getMainWindow(), tr("Macro recorder"),
QMessageBox::information(
getMainWindow(),
tr("Macro recorder"),
tr("The macro directory doesn't exist. Please, choose another one."));
return;
}
@@ -116,16 +124,22 @@ void DlgMacroRecordImp::onButtonStartClicked()
QFileInfo fi(fn);
if (fi.isFile() && fi.exists()) {
if (QMessageBox::question(this, tr("Existing macro"),
if (QMessageBox::question(
this,
tr("Existing macro"),
tr("The macro '%1' already exists. Do you want to overwrite?").arg(fn),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::No)
return;
QMessageBox::No)
== QMessageBox::No) {
return;
}
}
QFile file(fn);
if (!file.open(QFile::WriteOnly)) {
QMessageBox::information(getMainWindow(), tr("Macro recorder"),
QMessageBox::information(
getMainWindow(),
tr("Macro recorder"),
tr("You have no write permission for the directory. Please, choose another one."));
return;
}
@@ -170,19 +184,19 @@ void DlgMacroRecordImp::onButtonStopClicked()
void DlgMacroRecordImp::onButtonChooseDirClicked()
{
QString newDir = QFileDialog::getExistingDirectory(nullptr,tr("Choose macro directory"),macroPath);
QString newDir =
QFileDialog::getExistingDirectory(nullptr, tr("Choose macro directory"), macroPath);
if (!newDir.isEmpty()) {
macroPath = QDir::toNativeSeparators(newDir + QDir::separator());
ui->lineEditMacroPath->setText(macroPath);
getWindowParameter()->SetASCII("MacroPath",macroPath.toUtf8());
getWindowParameter()->SetASCII("MacroPath", macroPath.toUtf8());
}
}
void DlgMacroRecordImp::onMacroPathTextChanged (const QString & newDir)
void DlgMacroRecordImp::onMacroPathTextChanged(const QString& newDir)
{
macroPath = newDir;
}
#include "moc_DlgMacroRecordImp.cpp"

View File

@@ -35,8 +35,8 @@ using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::DlgMaterialPropertiesImp */
DlgMaterialPropertiesImp::DlgMaterialPropertiesImp(QWidget* parent, Qt::WindowFlags fl)
: QDialog(parent, fl)
, ui(new Ui_DlgMaterialProperties)
: QDialog(parent, fl)
, ui(new Ui_DlgMaterialProperties)
{
ui->setupUi(this);
setupConnections();
@@ -51,6 +51,7 @@ DlgMaterialPropertiesImp::~DlgMaterialPropertiesImp() = default;
void DlgMaterialPropertiesImp::setupConnections()
{
// clang-format off
connect(ui->ambientColor, &ColorButton::changed,
this, &DlgMaterialPropertiesImp::onAmbientColorChanged);
connect(ui->diffuseColor, &ColorButton::changed,
@@ -65,6 +66,7 @@ void DlgMaterialPropertiesImp::setupConnections()
this, &DlgMaterialPropertiesImp::onButtonReset);
connect(ui->buttonDefault, &QPushButton::clicked,
this, &DlgMaterialPropertiesImp::onButtonDefault);
// clang-format on
}
void DlgMaterialPropertiesImp::setCustomMaterial(const App::Material& mat)

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
# include <QPushButton>
#include <QMessageBox>
#include <QPushButton>
#endif
#include "DlgParameterFind.h"
@@ -36,9 +36,9 @@ using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::DlgParameterFind */
DlgParameterFind::DlgParameterFind(DlgParameterImp* parent)
: QDialog(parent)
, ui(new Ui_DlgParameterFind)
, dialog(parent)
: QDialog(parent)
, ui(new Ui_DlgParameterFind)
, dialog(parent)
{
ui->setupUi(this);
setupConnections();
@@ -61,6 +61,7 @@ DlgParameterFind::~DlgParameterFind()
void DlgParameterFind::setupConnections()
{
// clang-format off
connect(ui->lineEdit, &QLineEdit::textChanged,
this, &DlgParameterFind::onLineEditTextChanged);
connect(ui->checkGroups, &QCheckBox::toggled,
@@ -69,15 +70,15 @@ void DlgParameterFind::setupConnections()
this, &DlgParameterFind::onCheckNamesToggled);
connect(ui->checkValues, &QCheckBox::toggled,
this, &DlgParameterFind::onCheckValuesToggled);
// clang-format on
}
void DlgParameterFind::onLineEditTextChanged(const QString& text)
{
QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok);
if (btn) {
bool ok = ui->checkGroups->isChecked() ||
ui->checkNames->isChecked() ||
ui->checkValues->isChecked();
bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked()
|| ui->checkValues->isChecked();
btn->setDisabled(!ok || text.isEmpty());
}
}
@@ -86,9 +87,8 @@ void DlgParameterFind::onCheckGroupsToggled(bool)
{
QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok);
if (btn) {
bool ok = ui->checkGroups->isChecked() ||
ui->checkNames->isChecked() ||
ui->checkValues->isChecked();
bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked()
|| ui->checkValues->isChecked();
QString text = ui->lineEdit->text();
btn->setDisabled(!ok || text.isEmpty());
}
@@ -98,9 +98,8 @@ void DlgParameterFind::onCheckNamesToggled(bool)
{
QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok);
if (btn) {
bool ok = ui->checkGroups->isChecked() ||
ui->checkNames->isChecked() ||
ui->checkValues->isChecked();
bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked()
|| ui->checkValues->isChecked();
QString text = ui->lineEdit->text();
btn->setDisabled(!ok || text.isEmpty());
}
@@ -110,9 +109,8 @@ void DlgParameterFind::onCheckValuesToggled(bool)
{
QPushButton* btn = ui->buttonBox->button(QDialogButtonBox::Ok);
if (btn) {
bool ok = ui->checkGroups->isChecked() ||
ui->checkNames->isChecked() ||
ui->checkValues->isChecked();
bool ok = ui->checkGroups->isChecked() || ui->checkNames->isChecked()
|| ui->checkValues->isChecked();
QString text = ui->lineEdit->text();
btn->setDisabled(!ok || text.isEmpty());
}
@@ -124,12 +122,14 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const
if (opt.group) {
// whole word matches
if (opt.match) {
if (item->text(0).compare(opt.text, Qt::CaseInsensitive) == 0)
if (item->text(0).compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
else {
if (item->text(0).indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (item->text(0).indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
}
@@ -148,55 +148,65 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const
if (opt.match) {
for (const auto& it : boolMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
for (const auto& it : intMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
for (const auto& it : uintMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
for (const auto& it : floatMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
for (const auto& it : asciiMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
}
else {
for (const auto& it : boolMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
for (const auto& it : intMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
for (const auto& it : uintMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
for (const auto& it : floatMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
for (const auto& it : asciiMap) {
QString text = QString::fromUtf8(it.first.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
}
}
@@ -206,15 +216,17 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const
if (opt.match) {
for (const auto& it : asciiMap) {
QString text = QString::fromUtf8(it.second.c_str());
if (text.compare(opt.text, Qt::CaseInsensitive) == 0)
if (text.compare(opt.text, Qt::CaseInsensitive) == 0) {
return true;
}
}
}
else {
for (const auto& it : asciiMap) {
QString text = QString::fromUtf8(it.second.c_str());
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0)
if (text.indexOf(opt.text, 0, Qt::CaseInsensitive) >= 0) {
return true;
}
}
}
}
@@ -225,23 +237,27 @@ bool DlgParameterFind::matches(QTreeWidgetItem* item, const Options& opt) const
QTreeWidgetItem* DlgParameterFind::findItem(QTreeWidgetItem* root, const Options& opt) const
{
if (!root)
if (!root) {
return nullptr;
}
if (matches(root, opt)) {
// if the root matches then only return if it's not the current element
// as otherwise it would never move forward
if (root->treeWidget()->currentItem() != root)
if (root->treeWidget()->currentItem() != root) {
return root;
}
}
for (int i=0; i<root->childCount(); i++) {
for (int i = 0; i < root->childCount(); i++) {
QTreeWidgetItem* item = root->child(i);
if (matches(item, opt))
if (matches(item, opt)) {
return item;
}
item = findItem(item, opt);
if (item)
if (item) {
return item;
}
}
return nullptr;
@@ -272,10 +288,11 @@ void DlgParameterFind::accept()
}
if (parent) {
int index = parent->indexOfChild(current);
for (int i=index+1; i<parent->childCount(); i++) {
for (int i = index + 1; i < parent->childCount(); i++) {
next = findItem(parent->child(i), opt);
if (next)
if (next) {
break;
}
}
}
@@ -285,10 +302,14 @@ void DlgParameterFind::accept()
}
// if search was successful then make it the current item
if (next)
if (next) {
groupTree->setCurrentItem(next);
else
QMessageBox::warning(this, tr("Not found"), tr("Can't find the text: %1").arg(opt.text));
}
else {
QMessageBox::warning(this,
tr("Not found"),
tr("Can't find the text: %1").arg(opt.text));
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -22,7 +22,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QFileDialog>
#include <QFileDialog>
#endif
#include "DlgRunExternal.h"
@@ -41,12 +41,13 @@ using namespace Gui::Dialog;
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgRunExternal::DlgRunExternal( QWidget* parent, Qt::WindowFlags fl )
DlgRunExternal::DlgRunExternal(QWidget* parent, Qt::WindowFlags fl)
: QDialog(parent, fl)
, process(this)
, advancedHidden(true)
, ui(new Ui_DlgRunExternal)
{
// clang-format off
ui->setupUi(this);
connect(ui->chooseProgram, &QPushButton::clicked, this, &DlgRunExternal::onChooseProgramClicked);
connect(&process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished),
@@ -55,6 +56,7 @@ DlgRunExternal::DlgRunExternal( QWidget* parent, Qt::WindowFlags fl )
connect(ui->buttonDiscard, &QPushButton::clicked, this, &DlgRunExternal::reject);
connect(ui->buttonAbort, &QPushButton::clicked, this, &DlgRunExternal::abort);
connect(ui->buttonAdvanced, &QPushButton::clicked, this, &DlgRunExternal::advanced);
// clang-format on
ui->gridLayout->setSizeConstraint(QLayout::SetFixedSize);
ui->extensionWidget->hide();
@@ -72,36 +74,36 @@ void DlgRunExternal::addArgument(const QString& arg)
int DlgRunExternal::runProcess()
{
QFileInfo ifo (ProcName);
QFileInfo ifo(ProcName);
ui->programName->setText(ifo.baseName());
ui->programPath->setText(ProcName);
process.start(ProcName,arguments);
process.start(ProcName, arguments);
ui->buttonAccept->setEnabled(false);
ui->buttonDiscard->setEnabled(false);
return exec();
}
void DlgRunExternal::reject ()
void DlgRunExternal::reject()
{
QDialog::reject();
}
void DlgRunExternal::accept ()
void DlgRunExternal::accept()
{
QDialog::accept();
}
void DlgRunExternal::abort ()
void DlgRunExternal::abort()
{
process.terminate();
DlgRunExternal::reject();
}
void DlgRunExternal::advanced ()
void DlgRunExternal::advanced()
{
if (advancedHidden){
if (advancedHidden) {
ui->extensionWidget->show();
advancedHidden = false;
}
@@ -111,7 +113,7 @@ void DlgRunExternal::advanced ()
}
}
void DlgRunExternal::finished (int exitCode, QProcess::ExitStatus exitStatus)
void DlgRunExternal::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED(exitCode);
Q_UNUSED(exitStatus);
@@ -130,4 +132,3 @@ void DlgRunExternal::onChooseProgramClicked()
}
#include "moc_DlgRunExternal.cpp"

View File

@@ -22,13 +22,13 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cmath>
# include <limits>
# include <QButtonGroup>
# include <QDoubleValidator>
# include <QFontMetrics>
# include <QLocale>
# include <QMessageBox>
#include <cmath>
#include <limits>
#include <QButtonGroup>
#include <QDoubleValidator>
#include <QFontMetrics>
#include <QLocale>
#include <QMessageBox>
#endif
#include "DlgSettingsColorGradientImp.h"
@@ -46,10 +46,11 @@ using namespace Gui::Dialog;
* name 'name' and widget flags set to 'f'.
*/
DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradient& cg,
QWidget* parent, Qt::WindowFlags fl)
: QDialog( parent, fl )
, validator(nullptr)
, ui(new Ui_DlgSettingsColorGradient)
QWidget* parent,
Qt::WindowFlags fl)
: QDialog(parent, fl)
, validator(nullptr)
, ui(new Ui_DlgSettingsColorGradient)
{
ui->setupUi(this);
ui->spinBoxLabel->setRange(5, 30);
@@ -67,7 +68,8 @@ DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradien
// assure that the LineEdit is as wide to contain numbers with 4 digits and 6 decimals
QFontMetrics fm(ui->floatLineEditMax->font());
ui->floatLineEditMax->setMinimumWidth(QtTools::horizontalAdvance(fm, QString::fromLatin1("-8000.000000")));
ui->floatLineEditMax->setMinimumWidth(
QtTools::horizontalAdvance(fm, QString::fromLatin1("-8000.000000")));
setColorModelNames(cg.getColorModelNames());
setProfile(cg.getProfile());
@@ -81,6 +83,7 @@ DlgSettingsColorGradientImp::~DlgSettingsColorGradientImp() = default;
void DlgSettingsColorGradientImp::setupConnections()
{
// clang-format off
auto group = new QButtonGroup(this);
group->setExclusive(true);
group->addButton(ui->radioButtonFlow);
@@ -112,6 +115,7 @@ void DlgSettingsColorGradientImp::setupConnections()
connect(ui->spinBoxDecimals, qOverload<int>(&QSpinBox::valueChanged),
this, &DlgSettingsColorGradientImp::colorModelChanged);
// clang-format on
}
App::ColorGradientProfile DlgSettingsColorGradientImp::getProfile() const
@@ -154,16 +158,15 @@ void DlgSettingsColorGradientImp::setColorModelNames(const std::vector<std::stri
}
}
void DlgSettingsColorGradientImp::setColorStyle( App::ColorBarStyle tStyle )
void DlgSettingsColorGradientImp::setColorStyle(App::ColorBarStyle tStyle)
{
switch ( tStyle )
{
case App::ColorBarStyle::FLOW:
ui->radioButtonFlow->setChecked(true);
break;
case App::ColorBarStyle::ZERO_BASED:
ui->radioButtonZero->setChecked(true);
break;
switch (tStyle) {
case App::ColorBarStyle::FLOW:
ui->radioButtonFlow->setChecked(true);
break;
case App::ColorBarStyle::ZERO_BASED:
ui->radioButtonZero->setChecked(true);
break;
}
}
@@ -173,9 +176,9 @@ App::ColorBarStyle DlgSettingsColorGradientImp::colorStyle() const
: App::ColorBarStyle::FLOW;
}
void DlgSettingsColorGradientImp::setOutGrayed( bool grayed )
void DlgSettingsColorGradientImp::setOutGrayed(bool grayed)
{
ui->checkBoxGrayed->setChecked( grayed );
ui->checkBoxGrayed->setChecked(grayed);
}
bool DlgSettingsColorGradientImp::isOutGrayed() const
@@ -183,9 +186,9 @@ bool DlgSettingsColorGradientImp::isOutGrayed() const
return ui->checkBoxGrayed->isChecked();
}
void DlgSettingsColorGradientImp::setOutInvisible( bool invisible )
void DlgSettingsColorGradientImp::setOutInvisible(bool invisible)
{
ui->checkBoxInvisible->setChecked( invisible );
ui->checkBoxInvisible->setChecked(invisible);
}
bool DlgSettingsColorGradientImp::isOutInvisible() const
@@ -224,7 +227,7 @@ void DlgSettingsColorGradientImp::getRange(float& fMin, float& fMax) const
void DlgSettingsColorGradientImp::setNumberOfLabels(int val)
{
ui->spinBoxLabel->setValue( val );
ui->spinBoxLabel->setValue(val);
}
int DlgSettingsColorGradientImp::numberOfLabels() const
@@ -249,8 +252,9 @@ void DlgSettingsColorGradientImp::accept()
double fMin = QLocale().toDouble(ui->floatLineEditMin->text());
if (fMax <= fMin) {
QMessageBox::warning(this, tr("Wrong parameter"),
tr("The maximum value must be higher than the minimum value."));
QMessageBox::warning(this,
tr("Wrong parameter"),
tr("The maximum value must be higher than the minimum value."));
}
else {
QDialog::accept();
@@ -258,4 +262,3 @@ void DlgSettingsColorGradientImp::accept()
}
#include "moc_DlgSettingsColorGradientImp.cpp"

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QRegularExpression>
# include <QRegularExpressionMatch>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#endif
#include "DlgSettingsImageImp.h"
@@ -39,9 +39,9 @@ using namespace std;
* Constructs a DlgSettingsImageImp as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
DlgSettingsImageImp::DlgSettingsImageImp( QWidget* parent )
: QWidget( parent )
, ui(new Ui_DlgSettingsImage)
DlgSettingsImageImp::DlgSettingsImageImp(QWidget* parent)
: QWidget(parent)
, ui(new Ui_DlgSettingsImage)
{
ui->setupUi(this);
setupConnections();
@@ -52,7 +52,7 @@ DlgSettingsImageImp::DlgSettingsImageImp( QWidget* parent )
_width = width();
_height = height();
_fRatio = (float)_width/(float)_height;
_fRatio = (float)_width / (float)_height;
ui->comboMethod->addItem(tr("Offscreen (New)"), QByteArray("QtOffscreenRenderer"));
ui->comboMethod->addItem(tr("Offscreen (Old)"), QByteArray("CoinOffscreenRenderer"));
@@ -67,6 +67,7 @@ DlgSettingsImageImp::~DlgSettingsImageImp() = default;
void DlgSettingsImageImp::setupConnections()
{
// clang-format off
connect(ui->buttonRatioScreen, &QToolButton::clicked,
this, &DlgSettingsImageImp::onButtonRatioScreenClicked);
connect(ui->buttonRatio4x3, &QToolButton::clicked,
@@ -79,9 +80,10 @@ void DlgSettingsImageImp::setupConnections()
this, &DlgSettingsImageImp::onStandardSizeBoxActivated);
connect(ui->comboMethod, qOverload<int>(&QComboBox::activated),
this, &DlgSettingsImageImp::onComboMethodActivated);
// clang-format on
}
void DlgSettingsImageImp::changeEvent(QEvent *e)
void DlgSettingsImageImp::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
@@ -95,32 +97,32 @@ void DlgSettingsImageImp::changeEvent(QEvent *e)
void DlgSettingsImageImp::setImageSize(int w, int h)
{
// set current screen size
ui->standardSizeBox->setItemData(0, QSize(w,h));
ui->standardSizeBox->setItemData(0, QSize(w, h));
ui->spinWidth->setValue(w);
ui->spinHeight->setValue(h);
// As the image size is in pixel why shouldn't _width and _height be integers?
_width = w;
_width = w;
_height = h;
_fRatio = (float)_width/(float)_height;
_fRatio = (float)_width / (float)_height;
}
/**
* Sets the image size to \a s.
*/
void DlgSettingsImageImp::setImageSize( const QSize& s )
void DlgSettingsImageImp::setImageSize(const QSize& s)
{
// set current screen size
ui->standardSizeBox->setItemData(0, s);
ui->spinWidth->setValue( s.width() );
ui->spinHeight->setValue( s.height() );
ui->spinWidth->setValue(s.width());
ui->spinHeight->setValue(s.height());
// As the image size is in pixel why shouldn't _width and _height be integers?
_width = s.width();
_width = s.width();
_height = s.height();
_fRatio = (float)_width/(float)_height;
_fRatio = (float)_width / (float)_height;
}
/**
@@ -128,7 +130,7 @@ void DlgSettingsImageImp::setImageSize( const QSize& s )
*/
QSize DlgSettingsImageImp::imageSize() const
{
return { ui->spinWidth->value(), ui->spinHeight->value() };
return {ui->spinWidth->value(), ui->spinHeight->value()};
}
/**
@@ -148,15 +150,17 @@ int DlgSettingsImageImp::imageHeight() const
}
/**
* Returns the comment of the picture. If for the currently selected image format no comments are supported
* QString() is returned.
* Returns the comment of the picture. If for the currently selected image format no comments are
* supported QString() is returned.
*/
QString DlgSettingsImageImp::comment() const
{
if ( !ui->textEditComment->isEnabled() )
if (!ui->textEditComment->isEnabled()) {
return {};
else
}
else {
return ui->textEditComment->toPlainText();
}
}
int DlgSettingsImageImp::backgroundType() const
@@ -169,8 +173,9 @@ int DlgSettingsImageImp::backgroundType() const
*/
void DlgSettingsImageImp::setBackgroundType(int t)
{
if ( t < ui->comboBackground->count() )
if (t < ui->comboBackground->count()) {
ui->comboBackground->setCurrentIndex(t);
}
}
bool DlgSettingsImageImp::addWatermark() const
@@ -180,26 +185,24 @@ bool DlgSettingsImageImp::addWatermark() const
void DlgSettingsImageImp::onSelectedFilter(const QString& filter)
{
bool ok = (filter.startsWith(QLatin1String("JPG")) ||
filter.startsWith(QLatin1String("JPEG")) ||
filter.startsWith(QLatin1String("PNG")));
ui->buttonGroupComment->setEnabled( ok );
bool ok = (filter.startsWith(QLatin1String("JPG")) || filter.startsWith(QLatin1String("JPEG"))
|| filter.startsWith(QLatin1String("PNG")));
ui->buttonGroupComment->setEnabled(ok);
}
void DlgSettingsImageImp::adjustImageSize(float fRatio)
{
// if width has changed then adjust height and vice versa, if both has changed then adjust width
if (_height != ui->spinHeight->value())
{
if (_height != ui->spinHeight->value()) {
_height = ui->spinHeight->value();
_width = (int)((float)_height*fRatio);
ui->spinWidth->setValue( (int)_width );
_width = (int)((float)_height * fRatio);
ui->spinWidth->setValue((int)_width);
}
else // if( _width != spinWidth->value() )
else // if( _width != spinWidth->value() )
{
_width = ui->spinWidth->value();
_height = (int)((float)_width/fRatio);
ui->spinHeight->setValue( (int)_height );
_height = (int)((float)_width / fRatio);
ui->spinHeight->setValue((int)_height);
}
}
@@ -210,12 +213,12 @@ void DlgSettingsImageImp::onButtonRatioScreenClicked()
void DlgSettingsImageImp::onButtonRatio4x3Clicked()
{
adjustImageSize(4.0f/3.0f);
adjustImageSize(4.0f / 3.0f);
}
void DlgSettingsImageImp::onButtonRatio16x9Clicked()
{
adjustImageSize(16.0f/9.0f);
adjustImageSize(16.0f / 9.0f);
}
void DlgSettingsImageImp::onButtonRatio1x1Clicked()
@@ -256,8 +259,9 @@ void DlgSettingsImageImp::onStandardSizeBoxActivated(int index)
void DlgSettingsImageImp::setMethod(const QByteArray& m)
{
int index = ui->comboMethod->findData(m);
if (index >= 0)
if (index >= 0) {
ui->comboMethod->setCurrentIndex(index);
}
}
QByteArray DlgSettingsImageImp::method() const

View File

@@ -22,12 +22,12 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QHeaderView>
# include <QInputDialog>
# include <QMenu>
# include <QMessageBox>
# include <QToolBar>
# include <QToolButton>
#include <QHeaderView>
#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
#include <QToolBar>
#include <QToolButton>
#endif
#include "DlgToolbarsImp.h"
@@ -85,14 +85,16 @@ DlgCustomToolbars::DlgCustomToolbars(DlgCustomToolbars::Type t, QWidget* parent)
int index = 1;
ui->workbenchBox->addItem(QApplication::windowIcon(), tr("Global"));
ui->workbenchBox->setItemData(0, QVariant(QString::fromLatin1("Global")), Qt::UserRole);
for (const auto & workbench : workbenches) {
for (const auto& workbench : workbenches) {
QPixmap px = Application::Instance->workbenchIcon(workbench);
QString mt = Application::Instance->workbenchMenuText(workbench);
if (mt != QLatin1String("<none>")) {
if (px.isNull())
if (px.isNull()) {
ui->workbenchBox->addItem(mt);
else
}
else {
ui->workbenchBox->addItem(px, mt);
}
ui->workbenchBox->setItemData(index, QVariant(workbench), Qt::UserRole);
index++;
}
@@ -117,6 +119,7 @@ DlgCustomToolbars::~DlgCustomToolbars() = default;
void DlgCustomToolbars::setupConnections()
{
// clang-format off
connect(ui->workbenchBox, qOverload<int>(&QComboBox::activated),
this, &DlgCustomToolbars::onWorkbenchBoxActivated);
connect(ui->moveActionRightButton, &QPushButton::clicked,
@@ -133,37 +136,31 @@ void DlgCustomToolbars::setupConnections()
this, &DlgCustomToolbars::onRenameButtonClicked);
connect(ui->deleteButton, &QPushButton::clicked,
this, &DlgCustomToolbars::onDeleteButtonClicked);
// clang-format on
}
void DlgCustomToolbars::addCustomToolbar(const QString&)
{
}
{}
void DlgCustomToolbars::removeCustomToolbar(const QString&)
{
}
{}
void DlgCustomToolbars::renameCustomToolbar(const QString&, const QString&)
{
}
{}
void DlgCustomToolbars::addCustomCommand(const QString&, const QByteArray&)
{
}
{}
void DlgCustomToolbars::removeCustomCommand(const QString&, const QByteArray&)
{
}
{}
void DlgCustomToolbars::moveUpCustomCommand(const QString&, const QByteArray&)
{
}
{}
void DlgCustomToolbars::moveDownCustomCommand(const QString&, const QByteArray&)
{
}
{}
void DlgCustomToolbars::hideEvent(QHideEvent * event)
void DlgCustomToolbars::hideEvent(QHideEvent* event)
{
QVariant data = ui->workbenchBox->itemData(ui->workbenchBox->currentIndex(), Qt::UserRole);
QString workbench = data.toString();
@@ -173,8 +170,7 @@ void DlgCustomToolbars::hideEvent(QHideEvent * event)
}
void DlgCustomToolbars::onActivateCategoryBox()
{
}
{}
void DlgCustomToolbars::onWorkbenchBoxActivated(int index)
{
@@ -188,27 +184,30 @@ void DlgCustomToolbars::onWorkbenchBoxActivated(int index)
void DlgCustomToolbars::importCustomToolbars(const QByteArray& name)
{
ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench");
ParameterGrp::handle hGrp =
App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench");
const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar");
if (!hGrp->HasGroup(name.constData()))
if (!hGrp->HasGroup(name.constData())) {
return;
}
hGrp = hGrp->GetGroup(name.constData());
if (!hGrp->HasGroup(subgroup))
if (!hGrp->HasGroup(subgroup)) {
return;
}
hGrp = hGrp->GetGroup(subgroup);
std::string separator = "Separator";
std::vector<Base::Reference<ParameterGrp> > hGrps = hGrp->GetGroups();
std::vector<Base::Reference<ParameterGrp>> hGrps = hGrp->GetGroups();
CommandManager& rMgr = Application::Instance->commandManager();
for (const auto & hGrp : hGrps) {
for (const auto& hGrp : hGrps) {
// create a toplevel item
auto toplevel = new QTreeWidgetItem(ui->toolbarTreeWidget);
bool active = hGrp->GetBool("Active", true);
toplevel->setCheckState(0, (active ? Qt::Checked : Qt::Unchecked));
// get the elements of the subgroups
std::vector<std::pair<std::string,std::string> > items = hGrp->GetASCIIMap();
for (const auto & it2 : items) {
std::vector<std::pair<std::string, std::string>> items = hGrp->GetASCIIMap();
for (const auto& it2 : items) {
// since we have stored the separators to the user parameters as (key, pair) we had to
// make sure to use a unique key because otherwise we cannot store more than
// one.
@@ -230,14 +229,17 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name)
item->setText(0, Action::commandMenuText(pCmd));
item->setToolTip(0, Action::commandToolTip(pCmd));
item->setData(0, Qt::UserRole, QByteArray(it2.first.c_str()));
if (pCmd->getPixmap())
if (pCmd->getPixmap()) {
item->setIcon(0, BitmapFactory().iconFromTheme(pCmd->getPixmap()));
}
item->setSizeHint(0, QSize(32, 32));
}
else {
// If corresponding module is not yet loaded do not lose the entry
auto item = new QTreeWidgetItem(toplevel);
item->setText(0, tr("%1 module not loaded").arg(QString::fromStdString(it2.second)));
item->setText(
0,
tr("%1 module not loaded").arg(QString::fromStdString(it2.second)));
item->setData(0, Qt::UserRole, QByteArray(it2.first.c_str()));
item->setData(0, Qt::WhatsThisPropertyRole, QByteArray(it2.second.c_str()));
item->setSizeHint(0, QSize(32, 32));
@@ -249,15 +251,16 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name)
void DlgCustomToolbars::exportCustomToolbars(const QByteArray& workbench)
{
ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench");
ParameterGrp::handle hGrp =
App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench");
const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar");
hGrp = hGrp->GetGroup(workbench.constData())->GetGroup(subgroup);
hGrp->Clear();
CommandManager& rMgr = Application::Instance->commandManager();
for (int i=0; i<ui->toolbarTreeWidget->topLevelItemCount(); i++) {
for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i);
QString groupName = QString::fromLatin1("Custom_%1").arg(i+1);
QString groupName = QString::fromLatin1("Custom_%1").arg(i + 1);
QByteArray toolbarName = toplevel->text(0).toUtf8();
ParameterGrp::handle hToolGrp = hGrp->GetGroup(groupName.toLatin1());
hToolGrp->SetASCII("Name", toolbarName.constData());
@@ -267,7 +270,7 @@ void DlgCustomToolbars::exportCustomToolbars(const QByteArray& workbench)
// make sure to use a unique key because otherwise we cannot store more than
// one.
int suffixSeparator = 1;
for (int j=0; j<toplevel->childCount(); j++) {
for (int j = 0; j < toplevel->childCount(); j++) {
QTreeWidgetItem* child = toplevel->child(j);
QByteArray commandName = child->data(0, Qt::UserRole).toByteArray();
if (commandName == "Separator") {
@@ -295,10 +298,12 @@ void DlgCustomToolbars::onMoveActionRightButtonClicked()
QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
if (item) {
QTreeWidgetItem* current = ui->toolbarTreeWidget->currentItem();
if (!current)
if (!current) {
current = ui->toolbarTreeWidget->topLevelItem(0);
else if (current->parent())
}
else if (current->parent()) {
current = current->parent();
}
if (current && !current->parent()) {
auto copy = new QTreeWidgetItem(current);
copy->setText(0, item->text(1));
@@ -331,7 +336,7 @@ void DlgCustomToolbars::onMoveActionLeftButtonClicked()
QByteArray data = item->data(0, Qt::UserRole).toByteArray();
if (data == "Separator") {
int countSep = 1;
for (int i=0; i<index-1; i++) {
for (int i = 0; i < index - 1; i++) {
QByteArray d = parent->child(i)->data(0, Qt::UserRole).toByteArray();
if (d == "Separator") {
countSep++;
@@ -364,7 +369,7 @@ void DlgCustomToolbars::onMoveActionUpButtonClicked()
QByteArray data = item->data(0, Qt::UserRole).toByteArray();
if (data == "Separator") {
int countSep = 1;
for (int i=0; i<index; i++) {
for (int i = 0; i < index; i++) {
QByteArray d = parent->child(i)->data(0, Qt::UserRole).toByteArray();
if (d == "Separator") {
countSep++;
@@ -375,7 +380,7 @@ void DlgCustomToolbars::onMoveActionUpButtonClicked()
}
parent->takeChild(index);
parent->insertChild(index-1, item);
parent->insertChild(index - 1, item);
ui->toolbarTreeWidget->setCurrentItem(item);
moveUpCustomCommand(parent->text(0), data);
@@ -394,7 +399,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked()
if (item && item->parent() && item->isSelected()) {
QTreeWidgetItem* parent = item->parent();
int index = parent->indexOfChild(item);
if (index < parent->childCount()-1) {
if (index < parent->childCount() - 1) {
// In case a separator should be moved we have to count the separators
// which come before this one.
// This is needed so that we can distinguish in moveDownCustomCommand
@@ -402,7 +407,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked()
QByteArray data = item->data(0, Qt::UserRole).toByteArray();
if (data == "Separator") {
int countSep = 1;
for (int i=0; i<index; i++) {
for (int i = 0; i < index; i++) {
QByteArray d = parent->child(i)->data(0, Qt::UserRole).toByteArray();
if (d == "Separator") {
countSep++;
@@ -413,7 +418,7 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked()
}
parent->takeChild(index);
parent->insertChild(index+1, item);
parent->insertChild(index + 1, item);
ui->toolbarTreeWidget->setCurrentItem(item);
moveDownCustomCommand(parent->text(0), data);
@@ -428,15 +433,24 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked()
void DlgCustomToolbars::onNewButtonClicked()
{
bool ok;
QString text = QString::fromLatin1("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount()+1);
text = QInputDialog::getText(this, tr("New toolbar"), tr("Toolbar name:"), QLineEdit::Normal, text, &ok, Qt::MSWindowsFixedSizeDialogHint);
QString text =
QString::fromLatin1("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount() + 1);
text = QInputDialog::getText(this,
tr("New toolbar"),
tr("Toolbar name:"),
QLineEdit::Normal,
text,
&ok,
Qt::MSWindowsFixedSizeDialogHint);
if (ok) {
// Check for duplicated name
for (int i=0; i<ui->toolbarTreeWidget->topLevelItemCount(); i++) {
for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i);
QString groupName = toplevel->text(0);
if (groupName == text) {
QMessageBox::warning(this, tr("Duplicated name"), tr("The toolbar name '%1' is already used").arg(text));
QMessageBox::warning(this,
tr("Duplicated name"),
tr("The toolbar name '%1' is already used").arg(text));
return;
}
}
@@ -475,15 +489,22 @@ void DlgCustomToolbars::onRenameButtonClicked()
if (item && !item->parent() && item->isSelected()) {
bool ok;
QString old_text = item->text(0);
QString text = QInputDialog::getText(this, tr("Rename toolbar"), tr("Toolbar name:"),
QLineEdit::Normal, old_text, &ok, Qt::MSWindowsFixedSizeDialogHint);
QString text = QInputDialog::getText(this,
tr("Rename toolbar"),
tr("Toolbar name:"),
QLineEdit::Normal,
old_text,
&ok,
Qt::MSWindowsFixedSizeDialogHint);
if (ok && text != old_text) {
// Check for duplicated name
for (int i=0; i<ui->toolbarTreeWidget->topLevelItemCount(); i++) {
for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i);
QString groupName = toplevel->text(0);
if (groupName == text && toplevel != item) {
QMessageBox::warning(this, tr("Duplicated name"), tr("The toolbar name '%1' is already used").arg(text));
QMessageBox::warning(this,
tr("Duplicated name"),
tr("The toolbar name '%1' is already used").arg(text));
return;
}
}
@@ -502,32 +523,30 @@ void DlgCustomToolbars::onRenameButtonClicked()
}
void DlgCustomToolbars::onAddMacroAction(const QByteArray&)
{
}
{}
void DlgCustomToolbars::onRemoveMacroAction(const QByteArray&)
{
}
{}
void DlgCustomToolbars::onModifyMacroAction(const QByteArray& macro)
{
QVariant data = ui->categoryBox->itemData(ui->categoryBox->currentIndex(), Qt::UserRole);
QString group = data.toString();
if (group == QLatin1String("Macros"))
{
CommandManager & cCmdMgr = Application::Instance->commandManager();
if (group == QLatin1String("Macros")) {
CommandManager& cCmdMgr = Application::Instance->commandManager();
Command* pCmd = cCmdMgr.getCommandByName(macro);
// the right side
for (int i=0; i<ui->toolbarTreeWidget->topLevelItemCount(); i++) {
for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) {
QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i);
for (int j=0; j<toplevel->childCount(); j++) {
for (int j = 0; j < toplevel->childCount(); j++) {
QTreeWidgetItem* item = toplevel->child(j);
QByteArray command = item->data(0, Qt::UserRole).toByteArray();
if (command == macro) {
item->setText(0, Action::commandMenuText(pCmd));
item->setToolTip(0, Action::commandToolTip(pCmd));
if (pCmd->getPixmap())
if (pCmd->getPixmap()) {
item->setIcon(0, BitmapFactory().iconFromTheme(pCmd->getPixmap()));
}
}
}
}
@@ -535,14 +554,14 @@ void DlgCustomToolbars::onModifyMacroAction(const QByteArray& macro)
}
}
void DlgCustomToolbars::changeEvent(QEvent *e)
void DlgCustomToolbars::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
int count = ui->categoryBox->count();
CommandManager & cCmdMgr = Application::Instance->commandManager();
for (int i=0; i<count; i++) {
CommandManager& cCmdMgr = Application::Instance->commandManager();
for (int i = 0; i < count; i++) {
QVariant data = ui->categoryBox->itemData(i, Qt::UserRole);
std::vector<Command*> aCmds = cCmdMgr.getGroupCommands(data.toByteArray());
if (!aCmds.empty()) {
@@ -570,10 +589,9 @@ void DlgCustomToolbars::changeEvent(QEvent *e)
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgCustomToolbarsImp::DlgCustomToolbarsImp( QWidget* parent )
DlgCustomToolbarsImp::DlgCustomToolbarsImp(QWidget* parent)
: DlgCustomToolbars(DlgCustomToolbars::Toolbar, parent)
{
}
{}
/** Destroys the object and frees any allocated resources */
DlgCustomToolbarsImp::~DlgCustomToolbarsImp() = default;
@@ -594,8 +612,9 @@ void DlgCustomToolbarsImp::removeCustomToolbar(const QString& name)
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
QToolBar* tb = bars.front();
getMainWindow()->removeToolBar(tb);
@@ -609,8 +628,9 @@ void DlgCustomToolbarsImp::renameCustomToolbar(const QString& old_name, const QS
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(old_name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
QToolBar* tb = bars.front();
tb->setObjectName(new_name);
@@ -621,12 +641,12 @@ void DlgCustomToolbarsImp::renameCustomToolbar(const QString& old_name, const QS
QList<QAction*> DlgCustomToolbarsImp::getActionGroup(QAction* action)
{
QList<QAction*> group;
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QList<QWidget*> widgets = action->associatedWidgets();
#else
QList<QObject*> widgets = action->associatedObjects();
#endif
for (const auto & widget : widgets) {
for (const auto& widget : widgets) {
auto tb = qobject_cast<QToolButton*>(widget);
if (tb) {
QMenu* menu = tb->menu();
@@ -642,12 +662,12 @@ QList<QAction*> DlgCustomToolbarsImp::getActionGroup(QAction* action)
void DlgCustomToolbarsImp::setActionGroup(QAction* action, const QList<QAction*>& group)
{
// See also ActionGroup::addTo()
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QList<QWidget*> widgets = action->associatedWidgets();
#else
QList<QObject*> widgets = action->associatedObjects();
#endif
for (const auto & widget : widgets) {
for (const auto& widget : widgets) {
auto tb = qobject_cast<QToolButton*>(widget);
if (tb) {
QMenu* menu = tb->menu();
@@ -668,8 +688,9 @@ void DlgCustomToolbarsImp::addCustomCommand(const QString& name, const QByteArra
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
if (cmd == "Separator") {
QAction* action = bars.front()->addSeparator();
@@ -682,8 +703,9 @@ void DlgCustomToolbarsImp::addCustomCommand(const QString& name, const QByteArra
// See ToolBarManager::setup(ToolBarItem* , QToolBar* )
// We have to add the user data in order to identify the command in
// removeCustomCommand(), moveUpCustomCommand() or moveDownCustomCommand()
if (action && action->data().isNull())
if (action && action->data().isNull()) {
action->setData(cmd);
}
}
}
}
@@ -695,8 +717,9 @@ void DlgCustomToolbarsImp::removeCustomCommand(const QString& name, const QByteA
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
QByteArray cmd = userdata;
int numSep = 0, indexSep = 0;
@@ -705,12 +728,13 @@ void DlgCustomToolbarsImp::removeCustomCommand(const QString& name, const QByteA
cmd = "Separator";
}
QList<QAction*> actions = bars.front()->actions();
for (const auto & action : actions) {
for (const auto& action : actions) {
if (action->data().toByteArray() == cmd) {
// if we move a separator then make sure to pick up the right one
if (numSep > 0) {
if (++indexSep < numSep)
if (++indexSep < numSep) {
continue;
}
}
bars.front()->removeAction(action);
break;
@@ -725,8 +749,9 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
QByteArray cmd = userdata;
int numSep = 0, indexSep = 0;
@@ -735,8 +760,8 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA
cmd = "Separator";
}
QList<QAction*> actions = bars.front()->actions();
QAction* before=nullptr;
for (const auto & action : actions) {
QAction* before = nullptr;
for (const auto& action : actions) {
if (action->data().toByteArray() == cmd) {
// if we move a separator then make sure to pick up the right one
if (numSep > 0) {
@@ -749,8 +774,9 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA
QList<QAction*> group = getActionGroup(action);
bars.front()->removeAction(action);
bars.front()->insertAction(before, action);
if (!group.isEmpty())
if (!group.isEmpty()) {
setActionGroup(action, group);
}
break;
}
}
@@ -766,8 +792,9 @@ void DlgCustomToolbarsImp::moveDownCustomCommand(const QString& name, const QByt
Workbench* w = WorkbenchManager::instance()->active();
if (w && w->name() == std::string((const char*)data.toByteArray())) {
QList<QToolBar*> bars = getMainWindow()->findChildren<QToolBar*>(name);
if (bars.size() != 1)
if (bars.size() != 1) {
return;
}
QByteArray cmd = userdata;
int numSep = 0, indexSep = 0;
@@ -780,28 +807,32 @@ void DlgCustomToolbarsImp::moveDownCustomCommand(const QString& name, const QByt
if ((*it)->data().toByteArray() == cmd) {
// if we move a separator then make sure to pick up the right one
if (numSep > 0) {
if (++indexSep < numSep)
if (++indexSep < numSep) {
continue;
}
}
QAction* act = *it;
if (*it == actions.back())
break; // we're already on the last element
if (*it == actions.back()) {
break; // we're already on the last element
}
++it;
// second last item
if (*it == actions.back()) {
QList<QAction*> group = getActionGroup(act);
bars.front()->removeAction(act);
bars.front()->addAction(act);
if (!group.isEmpty())
if (!group.isEmpty()) {
setActionGroup(act, group);
}
break;
}
++it;
QList<QAction*> group = getActionGroup(act);
bars.front()->removeAction(act);
bars.front()->insertAction(*it, act);
if (!group.isEmpty())
if (!group.isEmpty()) {
setActionGroup(act, group);
}
break;
}
}
@@ -819,7 +850,7 @@ void DlgCustomToolbarsImp::showEvent(QShowEvent* event)
}
}
void DlgCustomToolbarsImp::changeEvent(QEvent *e)
void DlgCustomToolbarsImp::changeEvent(QEvent* e)
{
DlgCustomToolbars::changeEvent(e);
}
@@ -834,19 +865,19 @@ void DlgCustomToolbarsImp::changeEvent(QEvent *e)
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgCustomToolBoxbarsImp::DlgCustomToolBoxbarsImp( QWidget* parent )
DlgCustomToolBoxbarsImp::DlgCustomToolBoxbarsImp(QWidget* parent)
: DlgCustomToolbars(DlgCustomToolbars::Toolboxbar, parent)
{
setWindowTitle( tr( "Toolbox bars" ) );
setWindowTitle(tr("Toolbox bars"));
}
/** Destroys the object and frees any allocated resources */
DlgCustomToolBoxbarsImp::~DlgCustomToolBoxbarsImp() = default;
void DlgCustomToolBoxbarsImp::changeEvent(QEvent *e)
void DlgCustomToolBoxbarsImp::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
setWindowTitle( tr( "Toolbox bars" ) );
setWindowTitle(tr("Toolbox bars"));
}
DlgCustomToolbars::changeEvent(e);
}

View File

@@ -23,9 +23,9 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QClipboard>
# include <QLocale>
#include <QApplication>
#include <QClipboard>
#include <QLocale>
#endif
#include "DlgUnitsCalculatorImp.h"
@@ -43,8 +43,9 @@ using namespace Gui::Dialog;
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl )
: QDialog(parent, fl), ui(new Ui_DlgUnitCalculator)
DlgUnitsCalculator::DlgUnitsCalculator(QWidget* parent, Qt::WindowFlags fl)
: QDialog(parent, fl)
, ui(new Ui_DlgUnitCalculator)
{
// create widgets
ui->setupUi(this);
@@ -52,11 +53,12 @@ DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl )
ui->comboBoxScheme->addItem(QString::fromLatin1("Preference system"), static_cast<int>(-1));
int num = static_cast<int>(Base::UnitSystem::NumUnitSystemTypes);
for (int i=0; i<num; i++) {
for (int i = 0; i < num; i++) {
QString item = Base::UnitsApi::getDescription(static_cast<Base::UnitSystem>(i));
ui->comboBoxScheme->addItem(item, i);
}
// clang-format off
connect(ui->unitsBox, qOverload<int>(&QComboBox::activated),
this, &DlgUnitsCalculator::onUnitsBoxActivated);
connect(ui->comboBoxScheme, qOverload<int>(&QComboBox::activated),
@@ -67,63 +69,41 @@ DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WindowFlags fl )
this, &DlgUnitsCalculator::valueChanged);
connect(ui->ValueInput, &InputField::returnPressed,
this, &DlgUnitsCalculator::returnPressed);
connect(ui->ValueInput, &InputField::parseError, this, &DlgUnitsCalculator::parseError);
connect(ui->UnitInput, &QLineEdit::textChanged, this, &DlgUnitsCalculator::textChanged);
connect(ui->UnitInput, &QLineEdit::returnPressed, this, &DlgUnitsCalculator::returnPressed);
connect(ui->pushButton_Close, &QPushButton::clicked, this, &DlgUnitsCalculator::accept);
connect(ui->pushButton_Copy, &QPushButton::clicked, this, &DlgUnitsCalculator::copy);
connect(ui->ValueInput, &InputField::parseError,
this, &DlgUnitsCalculator::parseError);
connect(ui->UnitInput, &QLineEdit::textChanged,
this, &DlgUnitsCalculator::textChanged);
connect(ui->UnitInput, &QLineEdit::returnPressed,
this, &DlgUnitsCalculator::returnPressed);
connect(ui->pushButton_Close, &QPushButton::clicked,
this, &DlgUnitsCalculator::accept);
connect(ui->pushButton_Copy, &QPushButton::clicked,
this, &DlgUnitsCalculator::copy);
// clang-format on
ui->ValueInput->setParamGrpPath(QByteArray("User parameter:BaseApp/History/UnitsCalculator"));
// set a default that also illustrates how the dialog works
ui->ValueInput->setText(QString::fromLatin1("1 cm"));
ui->UnitInput->setText(QString::fromLatin1("in"));
units << Base::Unit::Acceleration
<< Base::Unit::AmountOfSubstance
<< Base::Unit::Angle
<< Base::Unit::Area
<< Base::Unit::Density
<< Base::Unit::CurrentDensity
<< Base::Unit::DissipationRate
<< Base::Unit::DynamicViscosity
<< Base::Unit::ElectricalCapacitance
<< Base::Unit::ElectricalInductance
<< Base::Unit::ElectricalConductance
<< Base::Unit::ElectricalResistance
<< Base::Unit::ElectricalConductivity
<< Base::Unit::ElectricCharge
<< Base::Unit::ElectricCurrent
<< Base::Unit::ElectricPotential
<< Base::Unit::Force
<< Base::Unit::Frequency
<< Base::Unit::HeatFlux
<< Base::Unit::InverseArea
<< Base::Unit::InverseLength
<< Base::Unit::InverseVolume
<< Base::Unit::KinematicViscosity
<< Base::Unit::Length
<< Base::Unit::LuminousIntensity
<< Base::Unit::Mass
<< Base::Unit::MagneticFieldStrength
<< Base::Unit::MagneticFlux
<< Base::Unit::MagneticFluxDensity
<< Base::Unit::Magnetization
<< Base::Unit::Power
<< Base::Unit::Pressure
<< Base::Unit::SpecificEnergy
<< Base::Unit::SpecificHeat
<< Base::Unit::Stiffness
<< Base::Unit::Temperature
<< Base::Unit::ThermalConductivity
<< Base::Unit::ThermalExpansionCoefficient
<< Base::Unit::ThermalTransferCoefficient
<< Base::Unit::TimeSpan
<< Base::Unit::VacuumPermittivity
<< Base::Unit::Velocity
<< Base::Unit::Volume
<< Base::Unit::VolumeFlowRate
<< Base::Unit::VolumetricThermalExpansionCoefficient
<< Base::Unit::Work;
units << Base::Unit::Acceleration << Base::Unit::AmountOfSubstance << Base::Unit::Angle
<< Base::Unit::Area << Base::Unit::Density << Base::Unit::CurrentDensity
<< Base::Unit::DissipationRate << Base::Unit::DynamicViscosity
<< Base::Unit::ElectricalCapacitance << Base::Unit::ElectricalInductance
<< Base::Unit::ElectricalConductance << Base::Unit::ElectricalResistance
<< Base::Unit::ElectricalConductivity << Base::Unit::ElectricCharge
<< Base::Unit::ElectricCurrent << Base::Unit::ElectricPotential << Base::Unit::Force
<< Base::Unit::Frequency << Base::Unit::HeatFlux << Base::Unit::InverseArea
<< Base::Unit::InverseLength << Base::Unit::InverseVolume
<< Base::Unit::KinematicViscosity << Base::Unit::Length << Base::Unit::LuminousIntensity
<< Base::Unit::Mass << Base::Unit::MagneticFieldStrength << Base::Unit::MagneticFlux
<< Base::Unit::MagneticFluxDensity << Base::Unit::Magnetization << Base::Unit::Power
<< Base::Unit::Pressure << Base::Unit::SpecificEnergy << Base::Unit::SpecificHeat
<< Base::Unit::Stiffness << Base::Unit::Temperature << Base::Unit::ThermalConductivity
<< Base::Unit::ThermalExpansionCoefficient << Base::Unit::ThermalTransferCoefficient
<< Base::Unit::TimeSpan << Base::Unit::VacuumPermittivity << Base::Unit::Velocity
<< Base::Unit::Volume << Base::Unit::VolumeFlowRate
<< Base::Unit::VolumetricThermalExpansionCoefficient << Base::Unit::Work;
for (const Base::Unit& it : units) {
ui->unitsBox->addItem(it.getTypeString());
}
@@ -157,28 +137,34 @@ void DlgUnitsCalculator::valueChanged(const Base::Quantity& quant)
// first check the unit, if it is invalid, getTypeString() outputs an empty string
// explicitly check for "ee" like in "eeV" because this would trigger an exception in Base::Unit
// since it expects then a scientific notation number like "1e3"
if ( (ui->UnitInput->text().mid(0, 2) == QString::fromLatin1("ee")) ||
Base::Unit(ui->UnitInput->text()).getTypeString().isEmpty()) {
ui->ValueOutput->setText(QString::fromLatin1("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text()));
if ((ui->UnitInput->text().mid(0, 2) == QString::fromLatin1("ee"))
|| Base::Unit(ui->UnitInput->text()).getTypeString().isEmpty()) {
ui->ValueOutput->setText(
QString::fromLatin1("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text()));
ui->pushButton_Copy->setEnabled(false);
} else { // the unit is valid
}
else { // the unit is valid
// we can only convert units of the same type, thus check
if (Base::Unit(ui->UnitInput->text()).getTypeString() != quant.getUnit().getTypeString()) {
ui->ValueOutput->setText(tr("unit mismatch"));
ui->pushButton_Copy->setEnabled(false);
} else { // the unit is valid and has the same type
double convertValue = Base::Quantity::parse(QString::fromLatin1("1") + ui->UnitInput->text()).getValue();
}
else { // the unit is valid and has the same type
double convertValue =
Base::Quantity::parse(QString::fromLatin1("1") + ui->UnitInput->text()).getValue();
// we got now e.g. for "1 in" the value '25.4' because 1 in = 25.4 mm
// the result is now just quant / convertValue because the input is always in a base unit
// (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField of the dialog)
// the result is now just quant / convertValue because the input is always in a base
// unit (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField
// of the dialog)
double value = quant.getValue() / convertValue;
// determine how many decimals we will need to avoid an output like "0.00"
// at first use scientific notation, if there is no "e", we can round it to the user-defined decimals,
// but the user-defined decimals might be too low for cases like "10 um" in "in",
// thus only if value > 0.005 because FC's default are 2 decimals
// at first use scientific notation, if there is no "e", we can round it to the
// user-defined decimals, but the user-defined decimals might be too low for cases like
// "10 um" in "in", thus only if value > 0.005 because FC's default are 2 decimals
QString val = QLocale().toString(value, 'g');
if (!val.contains(QChar::fromLatin1('e')) && (value > 0.005))
if (!val.contains(QChar::fromLatin1('e')) && (value > 0.005)) {
val = QLocale().toString(value, 'f', Base::UnitsApi::getDecimals());
}
// create the output string
QString out = QString::fromLatin1("%1 %2").arg(val, ui->UnitInput->text());
ui->ValueOutput->setText(out);
@@ -197,14 +183,15 @@ void DlgUnitsCalculator::parseError(const QString& errorText)
void DlgUnitsCalculator::copy()
{
QClipboard *cb = QApplication::clipboard();
QClipboard* cb = QApplication::clipboard();
cb->setText(ui->ValueOutput->text());
}
void DlgUnitsCalculator::returnPressed()
{
if (ui->pushButton_Copy->isEnabled()) {
ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ") + ui->ValueOutput->text());
ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ")
+ ui->ValueOutput->text());
ui->ValueInput->pushToHistory();
}
}
@@ -219,16 +206,18 @@ void DlgUnitsCalculator::onUnitsBoxActivated(int index)
Base::Unit unit = units[index];
int32_t len = unit.getSignature().Length;
ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3*(len-old)), unit));
ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3 * (len - old)), unit));
}
void DlgUnitsCalculator::onComboBoxSchemeActivated(int index)
{
int item = ui->comboBoxScheme->itemData(index).toInt();
if (item > 0)
if (item > 0) {
ui->quantitySpinBox->setSchema(static_cast<Base::UnitSystem>(item));
else
}
else {
ui->quantitySpinBox->clearSchema();
}
}
void DlgUnitsCalculator::onSpinBoxDecimalsValueChanged(int value)

View File

@@ -53,47 +53,49 @@
using namespace Gui::Dialog;
EditTableView::EditTableView(QWidget *parent)
EditTableView::EditTableView(QWidget* parent)
: QTableView(parent)
{
}
{}
void EditTableView::keyPressEvent(QKeyEvent *event)
void EditTableView::keyPressEvent(QKeyEvent* event)
{
if ((event->matches(QKeySequence::Delete)
|| event->matches(QKeySequence::Backspace))
if ((event->matches(QKeySequence::Delete) || event->matches(QKeySequence::Backspace))
&& model()) {
removeOne();
} else {
}
else {
QAbstractItemView::keyPressEvent(event);
}
}
void EditTableView::removeOne()
{
if (!model() || !selectionModel())
if (!model() || !selectionModel()) {
return;
}
int row = currentIndex().row();
model()->removeRow(row, rootIndex());
QModelIndex idx = model()->index(row, 0, rootIndex());
if (!idx.isValid())
if (!idx.isValid()) {
idx = model()->index(row - 1, 0, rootIndex());
}
selectionModel()->select(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
void EditTableView::removeAll()
{
if (model())
if (model()) {
model()->removeRows(0, model()->rowCount(rootIndex()), rootIndex());
}
}
// ----------------------------------------------------------------------------
SqueezeLabel::SqueezeLabel(QWidget *parent) : QLabel(parent)
{
}
SqueezeLabel::SqueezeLabel(QWidget* parent)
: QLabel(parent)
{}
void SqueezeLabel::paintEvent(QPaintEvent *event)
void SqueezeLabel::paintEvent(QPaintEvent* event)
{
QFontMetrics fm = fontMetrics();
if (Gui::QtTools::horizontalAdvance(fm, text()) > contentsRect().width()) {
@@ -102,52 +104,59 @@ void SqueezeLabel::paintEvent(QPaintEvent *event)
setText(elided);
QLabel::paintEvent(event);
setText(oldText);
} else {
}
else {
QLabel::paintEvent(event);
}
}
// ----------------------------------------------------------------------------
#define AUTOSAVE_IN 1000 * 3 // seconds
#define MAXWAIT 1000 * 15 // seconds
#define AUTOSAVE_IN 1000 * 3 // seconds
#define MAXWAIT 1000 * 15 // seconds
AutoSaver::AutoSaver(QObject *parent) : QObject(parent)
AutoSaver::AutoSaver(QObject* parent)
: QObject(parent)
{
Q_ASSERT(parent);
}
AutoSaver::~AutoSaver()
{
if (m_timer.isActive())
if (m_timer.isActive()) {
qWarning() << "AutoSaver: still active when destroyed, changes not saved.";
}
}
void AutoSaver::changeOccurred()
{
if (!m_firstChange.isValid())
if (!m_firstChange.isValid()) {
m_firstChange.start();
}
if (m_firstChange.elapsed() > MAXWAIT) {
saveIfNecessary();
} else {
}
else {
m_timer.start(AUTOSAVE_IN, this);
}
}
void AutoSaver::timerEvent(QTimerEvent *event)
void AutoSaver::timerEvent(QTimerEvent* event)
{
if (event->timerId() == m_timer.timerId()) {
saveIfNecessary();
} else {
}
else {
QObject::timerEvent(event);
}
}
void AutoSaver::saveIfNecessary()
{
if (!m_timer.isActive())
if (!m_timer.isActive()) {
return;
}
m_timer.stop();
m_firstChange = QElapsedTimer();
if (!QMetaObject::invokeMethod(parent(), "save", Qt::DirectConnection)) {
@@ -157,13 +166,17 @@ void AutoSaver::saveIfNecessary()
// ----------------------------------------------------------------------------
NetworkAccessManager::NetworkAccessManager(QObject *parent)
NetworkAccessManager::NetworkAccessManager(QObject* parent)
: QNetworkAccessManager(parent)
{
connect(this, &QNetworkAccessManager::authenticationRequired,
this, &NetworkAccessManager::authenticationRequired);
connect(this, &QNetworkAccessManager::proxyAuthenticationRequired,
this, &NetworkAccessManager::proxyAuthenticationRequired);
connect(this,
&QNetworkAccessManager::authenticationRequired,
this,
&NetworkAccessManager::authenticationRequired);
connect(this,
&QNetworkAccessManager::proxyAuthenticationRequired,
this,
&NetworkAccessManager::proxyAuthenticationRequired);
auto diskCache = new QNetworkDiskCache(this);
QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
@@ -171,9 +184,9 @@ NetworkAccessManager::NetworkAccessManager(QObject *parent)
setCache(diskCache);
}
void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthenticator *auth)
void NetworkAccessManager::authenticationRequired(QNetworkReply* reply, QAuthenticator* auth)
{
QWidget *mainWindow = Gui::getMainWindow();
QWidget* mainWindow = Gui::getMainWindow();
QDialog dialog(mainWindow);
dialog.setWindowFlags(Qt::Sheet);
@@ -183,7 +196,8 @@ void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthent
dialog.adjustSize();
QString introMessage = tr("<qt>Enter username and password for \"%1\" at %2</qt>");
introMessage = introMessage.arg(QString(reply->url().toString()).toHtmlEscaped(), QString(reply->url().toString()).toHtmlEscaped());
introMessage = introMessage.arg(QString(reply->url().toString()).toHtmlEscaped(),
QString(reply->url().toString()).toHtmlEscaped());
passwordDialog.siteDescription->setText(introMessage);
passwordDialog.siteDescription->setWordWrap(true);
@@ -193,9 +207,10 @@ void NetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthent
}
}
void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *auth)
void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy& proxy,
QAuthenticator* auth)
{
QWidget *mainWindow = Gui::getMainWindow();
QWidget* mainWindow = Gui::getMainWindow();
QDialog dialog(mainWindow);
dialog.setWindowFlags(Qt::Sheet);
@@ -217,7 +232,7 @@ void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &prox
// ----------------------------------------------------------------------------
DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget *parent)
DownloadItem::DownloadItem(QNetworkReply* reply, bool requestFileName, QWidget* parent)
: QWidget(parent)
, m_reply(reply)
, m_requestFileName(requestFileName)
@@ -238,6 +253,7 @@ DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget *
void DownloadItem::init()
{
// clang-format off
if (!m_reply)
return;
@@ -266,6 +282,7 @@ void DownloadItem::init()
error(m_reply->error());
finished();
}
// clang-format on
}
QString DownloadItem::getDownloadDirectory() const
@@ -273,8 +290,11 @@ QString DownloadItem::getDownloadDirectory() const
QString exe = QString::fromStdString(App::Application::getExecutableName());
QString path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QString dirPath = QDir(path).filePath(exe);
Base::Reference<ParameterGrp> hPath = App::GetApplication().GetUserParameter().GetGroup("BaseApp")
->GetGroup("Preferences")->GetGroup("General");
Base::Reference<ParameterGrp> hPath = App::GetApplication()
.GetUserParameter()
.GetGroup("BaseApp")
->GetGroup("Preferences")
->GetGroup("General");
std::string dir = hPath->GetASCII("DownloadPath", "");
if (!dir.empty()) {
dirPath = QString::fromUtf8(dir.c_str());
@@ -292,11 +312,14 @@ void DownloadItem::getFileName()
{
QSettings settings;
settings.beginGroup(QLatin1String("downloadmanager"));
//QString defaultLocation = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
// QString defaultLocation =
// QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
QString defaultLocation = getDownloadDirectory();
QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString();
if (!downloadDirectory.isEmpty())
QString downloadDirectory =
settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString();
if (!downloadDirectory.isEmpty()) {
downloadDirectory += QLatin1Char('/');
}
QString defaultFileName = saveFileName(downloadDirectory);
QString fileName = defaultFileName;
@@ -304,23 +327,26 @@ void DownloadItem::getFileName()
fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) {
m_reply->close();
fileNameLabel->setText(tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName()));
fileNameLabel->setText(
tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName()));
return;
}
}
m_output.setFileName(fileName);
fileNameLabel->setText(QFileInfo(m_output.fileName()).fileName());
fileNameLabel->setToolTip(m_output.fileName());
if (m_requestFileName)
if (m_requestFileName) {
downloadReadyRead();
}
}
QString DownloadItem::saveFileName(const QString &directory) const
QString DownloadItem::saveFileName(const QString& directory) const
{
// Move this function into QNetworkReply to also get file name sent from the server
QString path = m_url.path();
if (!m_fileName.isEmpty())
if (!m_fileName.isEmpty()) {
path = m_fileName;
}
QFileInfo info(path);
QString baseName = info.completeBaseName();
QString endName = info.suffix();
@@ -334,7 +360,8 @@ QString DownloadItem::saveFileName(const QString &directory) const
// already exists, don't overwrite
int i = 1;
do {
name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.') + endName;
name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.')
+ endName;
} while (QFile::exists(name));
}
return name;
@@ -366,7 +393,8 @@ void DownloadItem::open()
if (doc) {
for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
Gui::Application::Instance->importFrom(it.key().toUtf8(),
doc->getDocument()->getName(), it.value().toLatin1());
doc->getDocument()->getName(),
it.value().toLatin1());
}
}
else {
@@ -390,8 +418,9 @@ void DownloadItem::openFolder()
void DownloadItem::tryAgain()
{
if (!tryAgainButton->isEnabled())
if (!tryAgainButton->isEnabled()) {
return;
}
tryAgainButton->setEnabled(false);
tryAgainButton->setVisible(false);
@@ -399,17 +428,20 @@ void DownloadItem::tryAgain()
stopButton->setVisible(true);
progressBar->setVisible(true);
QNetworkReply *r = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(m_url));
if (m_reply)
QNetworkReply* r =
DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(m_url));
if (m_reply) {
m_reply->deleteLater();
if (m_output.exists())
}
if (m_output.exists()) {
m_output.remove();
}
m_reply = r;
init();
Q_EMIT statusChanged();
}
void DownloadItem::contextMenuEvent (QContextMenuEvent * e)
void DownloadItem::contextMenuEvent(QContextMenuEvent* e)
{
QMenu menu;
QAction* a = menu.addAction(tr("Open containing folder"), this, &DownloadItem::openFolder);
@@ -419,15 +451,17 @@ void DownloadItem::contextMenuEvent (QContextMenuEvent * e)
void DownloadItem::downloadReadyRead()
{
if (m_requestFileName && m_output.fileName().isEmpty())
if (m_requestFileName && m_output.fileName().isEmpty()) {
return;
}
if (!m_output.isOpen()) {
// in case someone else has already put a file there
if (!m_requestFileName)
if (!m_requestFileName) {
getFileName();
}
if (!m_output.open(QIODevice::WriteOnly)) {
downloadInfoLabel->setText(tr("Error opening saved file: %1")
.arg(m_output.errorString()));
downloadInfoLabel->setText(
tr("Error opening saved file: %1").arg(m_output.errorString()));
stopButton->click();
Q_EMIT statusChanged();
return;
@@ -436,8 +470,7 @@ void DownloadItem::downloadReadyRead()
Q_EMIT statusChanged();
}
if (-1 == m_output.write(m_reply->readAll())) {
downloadInfoLabel->setText(tr("Error saving: %1")
.arg(m_output.errorString()));
downloadInfoLabel->setText(tr("Error saving: %1").arg(m_output.errorString()));
stopButton->click();
}
}
@@ -457,26 +490,32 @@ void DownloadItem::metaDataChanged()
QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition"));
int index = header.indexOf("filename=");
if (index >= 0) {
header = header.mid(index+9);
if (header.startsWith("\"") || header.startsWith("'"))
header = header.mid(index + 9);
if (header.startsWith("\"") || header.startsWith("'")) {
header = header.mid(1);
if ((index = header.lastIndexOf("\"")) > 0)
}
if ((index = header.lastIndexOf("\"")) > 0) {
header = header.left(index);
else if ((index = header.lastIndexOf("'")) > 0)
}
else if ((index = header.lastIndexOf("'")) > 0) {
header = header.left(index);
}
m_fileName = QUrl::fromPercentEncoding(header);
}
// Sometimes "filename=" and "filename*=UTF-8''" is set.
// So, search for this too.
index = header.indexOf("filename*=UTF-8''");
if (index >= 0) {
header = header.mid(index+17);
if (header.startsWith("\"") || header.startsWith("'"))
header = header.mid(index + 17);
if (header.startsWith("\"") || header.startsWith("'")) {
header = header.mid(1);
if ((index = header.lastIndexOf("\"")) > 0)
}
if ((index = header.lastIndexOf("\"")) > 0) {
header = header.left(index);
else if ((index = header.lastIndexOf("'")) > 0)
}
else if ((index = header.lastIndexOf("'")) > 0) {
header = header.left(index);
}
m_fileName = QUrl::fromPercentEncoding(header);
}
}
@@ -497,18 +536,28 @@ void DownloadItem::metaDataChanged()
url = redirectUrl;
disconnect(m_reply, &QNetworkReply::readyRead, this, &DownloadItem::downloadReadyRead);
#if QT_VERSION < QT_VERSION_CHECK(5,15,0)
disconnect(m_reply, qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error), this, &DownloadItem::error);
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
disconnect(m_reply,
qOverload<QNetworkReply::NetworkError>(&QNetworkReply::error),
this,
&DownloadItem::error);
#else
disconnect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error);
#endif
disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress);
disconnect(m_reply, &QNetworkReply::metaDataChanged, this, &DownloadItem::metaDataChanged);
disconnect(m_reply,
&QNetworkReply::downloadProgress,
this,
&DownloadItem::downloadProgress);
disconnect(m_reply,
&QNetworkReply::metaDataChanged,
this,
&DownloadItem::metaDataChanged);
disconnect(m_reply, &QNetworkReply::finished, this, &DownloadItem::finished);
m_reply->close();
m_reply->deleteLater();
m_reply = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url));
m_reply =
DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url));
init();
}
}
@@ -520,7 +569,8 @@ void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
if (bytesTotal == -1) {
progressBar->setValue(0);
progressBar->setMaximum(0);
} else {
}
else {
progressBar->setValue(bytesReceived);
progressBar->setMaximum(bytesTotal);
}
@@ -543,28 +593,30 @@ void DownloadItem::updateInfoLabel()
timeRemaining = floor(timeRemaining);
// When downloading the eta should never be 0
if (timeRemaining == 0)
if (timeRemaining == 0) {
timeRemaining = 1;
}
QString info;
if (running) {
QString remaining;
if (bytesTotal != 0)
remaining = tr("- %4 %5 remaining")
.arg(timeRemaining)
.arg(timeRemainingString);
if (bytesTotal != 0) {
remaining = tr("- %4 %5 remaining").arg(timeRemaining).arg(timeRemainingString);
}
info = QString(tr("%1 of %2 (%3/sec) %4"))
.arg(dataString(m_bytesReceived),
bytesTotal == 0 ? tr("?") : dataString(bytesTotal),
dataString((int)speed),
remaining);
} else {
if (m_bytesReceived == bytesTotal)
.arg(dataString(m_bytesReceived),
bytesTotal == 0 ? tr("?") : dataString(bytesTotal),
dataString((int)speed),
remaining);
}
else {
if (m_bytesReceived == bytesTotal) {
info = dataString(m_output.size());
else
info = tr("%1 of %2 - Stopped")
.arg(dataString(m_bytesReceived),
dataString(bytesTotal));
}
else {
info =
tr("%1 of %2 - Stopped").arg(dataString(m_bytesReceived), dataString(bytesTotal));
}
}
downloadInfoLabel->setText(info);
}
@@ -574,11 +626,13 @@ QString DownloadItem::dataString(int size) const
QString unit;
if (size < 1024) {
unit = tr("bytes");
} else if (size < 1024*1024) {
}
else if (size < 1024 * 1024) {
size /= 1024;
unit = tr("kB");
} else {
size /= 1024*1024;
}
else {
size /= 1024 * 1024;
unit = tr("MB");
}
return QString(QLatin1String("%1 %2")).arg(size).arg(unit);

View File

@@ -23,25 +23,25 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QCheckBox>
# include <QClipboard>
# include <QDateTime>
# include <QHBoxLayout>
# include <QVBoxLayout>
# include <QLineEdit>
# include <QMessageBox>
# include <QPrinter>
# include <QPrintDialog>
# include <QPlainTextEdit>
# include <QPrintPreviewDialog>
# include <QSpacerItem>
# include <QStyle>
# include <QTextCursor>
# include <QTextDocument>
# include <QTextStream>
# include <QTimer>
# include <QToolButton>
#include <QApplication>
#include <QCheckBox>
#include <QClipboard>
#include <QDateTime>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QPrinter>
#include <QPrintDialog>
#include <QPlainTextEdit>
#include <QPrintPreviewDialog>
#include <QSpacerItem>
#include <QStyle>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextStream>
#include <QTimer>
#include <QToolButton>
#endif
#include "EditorView.h"
@@ -59,21 +59,23 @@
using namespace Gui;
namespace Gui {
class EditorViewP {
namespace Gui
{
class EditorViewP
{
public:
TextEdit* textEdit;
SearchBar* searchBar;
QString fileName;
EditorView::DisplayName displayName;
QTimer* activityTimer;
QTimer* activityTimer;
qint64 timeStamp;
bool lock;
bool aboutToClose;
QStringList undos;
QStringList redos;
};
}
} // namespace Gui
// -------------------------------------------------------
@@ -87,7 +89,7 @@ TYPESYSTEM_SOURCE_ABSTRACT(Gui::EditorView, Gui::MDIView)
*/
EditorView::EditorView(TextEdit* editor, QWidget* parent)
: MDIView(nullptr, parent, Qt::WindowFlags())
, WindowParameter( "Editor" )
, WindowParameter("Editor")
{
d = new EditorViewP;
d->lock = false;
@@ -101,6 +103,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent)
d->searchBar = new SearchBar();
d->searchBar->setEditor(editor);
// clang-format off
// update editor actions on request
Gui::MainWindow* mw = Gui::getMainWindow();
connect(editor, &QPlainTextEdit::undoAvailable, mw, &MainWindow::updateEditorActions);
@@ -110,6 +113,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent)
connect(editor, &TextEdit::showSearchBar, d->searchBar, &SearchBar::activate);
connect(editor, &TextEdit::findNext, d->searchBar, &SearchBar::findNext);
connect(editor, &TextEdit::findPrevious, d->searchBar, &SearchBar::findPrevious);
// clang-format on
// Create the layout containing the workspace and a tab bar
auto hbox = new QFrame(this);
@@ -130,10 +134,11 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent)
setWindowIcon(d->textEdit->windowIcon());
ParameterGrp::handle hPrefGrp = getWindowParameter();
hPrefGrp->Attach( this );
hPrefGrp->Attach(this);
hPrefGrp->NotifyAll();
d->activityTimer = new QTimer(this);
// clang-format off
connect(d->activityTimer, &QTimer::timeout,
this, &EditorView::checkTimestamp);
connect(d->textEdit->document(), &QTextDocument::modificationChanged,
@@ -144,6 +149,7 @@ EditorView::EditorView(TextEdit* editor, QWidget* parent)
this, &EditorView::redoAvailable);
connect(d->textEdit->document(), &QTextDocument::contentsChange,
this, &EditorView::contentsChange);
// clang-format on
}
/** Destroys the object and frees any allocated resources */
@@ -152,7 +158,7 @@ EditorView::~EditorView()
d->activityTimer->stop();
delete d->activityTimer;
delete d;
getWindowParameter()->Detach( this );
getWindowParameter()->Detach(this);
}
QPlainTextEdit* EditorView::getEditor() const
@@ -182,27 +188,30 @@ void EditorView::closeEvent(QCloseEvent* event)
}
}
void EditorView::OnChange(Base::Subject<const char*> &rCaller,const char* rcReason)
void EditorView::OnChange(Base::Subject<const char*>& rCaller, const char* rcReason)
{
Q_UNUSED(rCaller);
ParameterGrp::handle hPrefGrp = getWindowParameter();
if (strcmp(rcReason, "EnableLineNumber") == 0) {
//bool show = hPrefGrp->GetBool( "EnableLineNumber", true );
// bool show = hPrefGrp->GetBool( "EnableLineNumber", true );
}
}
void EditorView::checkTimestamp()
{
QFileInfo fi(d->fileName);
qint64 timeStamp = fi.lastModified().toSecsSinceEpoch();
qint64 timeStamp = fi.lastModified().toSecsSinceEpoch();
if (timeStamp != d->timeStamp) {
switch( QMessageBox::question( this, tr("Modified file"),
tr("%1.\n\nThis has been modified outside of the source editor. Do you want to reload it?").arg(d->fileName),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) )
{
switch (QMessageBox::question(this,
tr("Modified file"),
tr("%1.\n\nThis has been modified outside of the source "
"editor. Do you want to reload it?")
.arg(d->fileName),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes)) {
case QMessageBox::Yes:
// updates time stamp and timer
open( d->fileName );
open(d->fileName);
return;
case QMessageBox::No:
d->timeStamp = timeStamp;
@@ -219,11 +228,12 @@ void EditorView::checkTimestamp()
/**
* Runs the action specified by \a pMsg.
*/
bool EditorView::onMsg(const char* pMsg,const char** /*ppReturn*/)
bool EditorView::onMsg(const char* pMsg, const char** /*ppReturn*/)
{
// don't allow any actions if the editor is being closed
if (d->aboutToClose)
if (d->aboutToClose) {
return false;
}
if (strcmp(pMsg, "Save") == 0) {
saveFile();
@@ -268,22 +278,30 @@ bool EditorView::onMsg(const char* pMsg,const char** /*ppReturn*/)
bool EditorView::onHasMsg(const char* pMsg) const
{
// don't allow any actions if the editor is being closed
if (d->aboutToClose)
if (d->aboutToClose) {
return false;
if (strcmp(pMsg, "Run") == 0)
}
if (strcmp(pMsg, "Run") == 0) {
return true;
if (strcmp(pMsg, "DebugStart") == 0)
}
if (strcmp(pMsg, "DebugStart") == 0) {
return true;
if (strcmp(pMsg, "DebugStop") == 0)
}
if (strcmp(pMsg, "DebugStop") == 0) {
return true;
if (strcmp(pMsg, "SaveAs") == 0)
}
if (strcmp(pMsg, "SaveAs") == 0) {
return true;
if (strcmp(pMsg, "Print") == 0)
}
if (strcmp(pMsg, "Print") == 0) {
return true;
if (strcmp(pMsg, "PrintPreview") == 0)
}
if (strcmp(pMsg, "PrintPreview") == 0) {
return true;
if (strcmp(pMsg, "PrintPdf") == 0)
}
if (strcmp(pMsg, "PrintPdf") == 0) {
return true;
}
if (strcmp(pMsg, "Save") == 0) {
return d->textEdit->document()->isModified();
}
@@ -292,23 +310,23 @@ bool EditorView::onHasMsg(const char* pMsg) const
return (canWrite && (d->textEdit->textCursor().hasSelection()));
}
else if (strcmp(pMsg, "Copy") == 0) {
return ( d->textEdit->textCursor().hasSelection() );
return (d->textEdit->textCursor().hasSelection());
}
else if (strcmp(pMsg, "Paste") == 0) {
QClipboard *cb = QApplication::clipboard();
QClipboard* cb = QApplication::clipboard();
QString text;
// Copy text from the clipboard (paste)
text = cb->text();
bool canWrite = !d->textEdit->isReadOnly();
return ( !text.isEmpty() && canWrite );
return (!text.isEmpty() && canWrite);
}
else if (strcmp(pMsg, "Undo") == 0) {
return d->textEdit->document()->isUndoAvailable ();
return d->textEdit->document()->isUndoAvailable();
}
else if (strcmp(pMsg, "Redo") == 0) {
return d->textEdit->document()->isRedoAvailable ();
return d->textEdit->document()->isRedoAvailable();
}
return false;
@@ -317,14 +335,16 @@ bool EditorView::onHasMsg(const char* pMsg) const
/** Checking on close state. */
bool EditorView::canClose()
{
if ( !d->textEdit->document()->isModified() )
if (!d->textEdit->document()->isModified()) {
return true;
this->setFocus(); // raises the view to front
switch( QMessageBox::question(this, tr("Unsaved document"),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel))
{
}
this->setFocus(); // raises the view to front
switch (QMessageBox::question(this,
tr("Unsaved document"),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
QMessageBox::Cancel)) {
case QMessageBox::Yes:
return saveFile();
case QMessageBox::No:
@@ -346,10 +366,14 @@ void EditorView::setDisplayName(EditorView::DisplayName type)
*/
bool EditorView::saveAs()
{
QString fn = FileDialog::getSaveFileName(this, QObject::tr("Save Macro"),
QString(), QString::fromLatin1("%1 (*.FCMacro);;Python (*.py)").arg(tr("FreeCAD macro")));
if (fn.isEmpty())
QString fn = FileDialog::getSaveFileName(
this,
QObject::tr("Save Macro"),
QString(),
QString::fromLatin1("%1 (*.FCMacro);;Python (*.py)").arg(tr("FreeCAD macro")));
if (fn.isEmpty()) {
return false;
}
setCurrentFileName(fn);
return saveFile();
}
@@ -359,11 +383,13 @@ bool EditorView::saveAs()
*/
bool EditorView::open(const QString& fileName)
{
if (!QFile::exists(fileName))
if (!QFile::exists(fileName)) {
return false;
}
QFile file(fileName);
if (!file.open(QFile::ReadOnly))
if (!file.open(QFile::ReadOnly)) {
return false;
}
d->lock = true;
d->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
@@ -373,7 +399,7 @@ bool EditorView::open(const QString& fileName)
file.close();
QFileInfo fi(fileName);
d->timeStamp = fi.lastModified().toSecsSinceEpoch();
d->timeStamp = fi.lastModified().toSecsSinceEpoch();
d->activityTimer->setSingleShot(true);
d->activityTimer->start(3000);
@@ -409,7 +435,8 @@ void EditorView::paste()
/**
* Undoes the last operation.
* If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens.
* If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing
* happens.
*/
void EditorView::undo()
{
@@ -424,7 +451,8 @@ void EditorView::undo()
/**
* Redoes the last operation.
* If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens.
* If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing
* happens.
*/
void EditorView::redo()
{
@@ -454,8 +482,10 @@ void EditorView::printPreview()
{
QPrinter printer(QPrinter::ScreenResolution);
QPrintPreviewDialog dlg(&printer, this);
connect(&dlg, &QPrintPreviewDialog::paintRequested,
this, qOverload<QPrinter *>(&EditorView::print));
connect(&dlg,
&QPrintPreviewDialog::paintRequested,
this,
qOverload<QPrinter*>(&EditorView::print));
dlg.exec();
}
@@ -469,11 +499,15 @@ void EditorView::print(QPrinter* printer)
*/
void EditorView::printPdf()
{
QString filename = FileDialog::getSaveFileName(this, tr("Export PDF"), QString(),
QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file")));
QString filename =
FileDialog::getSaveFileName(this,
tr("Export PDF"),
QString(),
QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file")));
if (!filename.isEmpty()) {
QPrinter printer(QPrinter::ScreenResolution);
// setPdfVersion sets the printied PDF Version to comply with PDF/A-1b, more details under: https://www.kdab.com/creating-pdfa-documents-qt/
// setPdfVersion sets the printied PDF Version to comply with PDF/A-1b, more details under:
// https://www.kdab.com/creating-pdfa-documents-qt/
printer.setPdfVersion(QPagedPaintDevice::PdfVersion_A1b);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filename);
@@ -481,7 +515,7 @@ void EditorView::printPdf()
}
}
void EditorView::setCurrentFileName(const QString &fileName)
void EditorView::setCurrentFileName(const QString& fileName)
{
d->fileName = fileName;
Q_EMIT changeFileName(d->fileName);
@@ -490,22 +524,24 @@ void EditorView::setCurrentFileName(const QString &fileName)
QString name;
QFileInfo fi(fileName);
switch (d->displayName) {
case FullName:
name = fileName;
break;
case FileName:
name = fi.fileName();
break;
case BaseName:
name = fi.baseName();
break;
case FullName:
name = fileName;
break;
case FileName:
name = fi.fileName();
break;
case BaseName:
name = fi.baseName();
break;
}
QString shownName;
if (fileName.isEmpty())
if (fileName.isEmpty()) {
shownName = tr("untitled[*]");
else
}
else {
shownName = QString::fromLatin1("%1[*]").arg(name);
}
shownName += tr(" - Editor");
setWindowTitle(shownName);
setWindowModified(false);
@@ -521,12 +557,14 @@ QString EditorView::fileName() const
*/
bool EditorView::saveFile()
{
if (d->fileName.isEmpty())
if (d->fileName.isEmpty()) {
return saveAs();
}
QFile file(d->fileName);
if (!file.open(QFile::WriteOnly))
if (!file.open(QFile::WriteOnly)) {
return false;
}
QTextStream ts(&file);
#if QT_VERSION < 0x060000
ts.setCodec("UTF-8");
@@ -536,35 +574,42 @@ bool EditorView::saveFile()
d->textEdit->document()->setModified(false);
QFileInfo fi(d->fileName);
d->timeStamp = fi.lastModified().toSecsSinceEpoch();
d->timeStamp = fi.lastModified().toSecsSinceEpoch();
return true;
}
void EditorView::undoAvailable(bool undo)
{
if (!undo)
if (!undo) {
d->undos.clear();
}
}
void EditorView::redoAvailable(bool redo)
{
if (!redo)
if (!redo) {
d->redos.clear();
}
}
void EditorView::contentsChange(int position, int charsRemoved, int charsAdded)
{
Q_UNUSED(position);
if (d->lock)
if (d->lock) {
return;
if (charsRemoved > 0 && charsAdded > 0)
return; // syntax highlighting
else if (charsRemoved > 0)
}
if (charsRemoved > 0 && charsAdded > 0) {
return; // syntax highlighting
}
else if (charsRemoved > 0) {
d->undos << tr("%1 chars removed").arg(charsRemoved);
else if (charsAdded > 0)
}
else if (charsAdded > 0) {
d->undos << tr("%1 chars added").arg(charsAdded);
else
}
else {
d->undos << tr("Formatted");
}
d->redos.clear();
}
@@ -581,10 +626,11 @@ QStringList EditorView::undoActions() const
*/
QStringList EditorView::redoActions() const
{
return d->redos;;
return d->redos;
;
}
void EditorView::focusInEvent (QFocusEvent *)
void EditorView::focusInEvent(QFocusEvent*)
{
d->textEdit->setFocus();
}
@@ -594,10 +640,10 @@ void EditorView::focusInEvent (QFocusEvent *)
TYPESYSTEM_SOURCE_ABSTRACT(Gui::PythonEditorView, Gui::EditorView)
PythonEditorView::PythonEditorView(PythonEditor* editor, QWidget* parent)
: EditorView(editor, parent), _pye(editor)
: EditorView(editor, parent)
, _pye(editor)
{
connect(this, &PythonEditorView::changeFileName,
editor, &PythonEditor::setFileName);
connect(this, &PythonEditorView::changeFileName, editor, &PythonEditor::setFileName);
watcher = new PythonTracingWatcher(this);
}
@@ -609,17 +655,17 @@ PythonEditorView::~PythonEditorView()
/**
* Runs the action specified by \a pMsg.
*/
bool PythonEditorView::onMsg(const char* pMsg,const char** ppReturn)
bool PythonEditorView::onMsg(const char* pMsg, const char** ppReturn)
{
if (strcmp(pMsg,"Run")==0) {
if (strcmp(pMsg, "Run") == 0) {
executeScript();
return true;
}
else if (strcmp(pMsg,"StartDebug")==0) {
else if (strcmp(pMsg, "StartDebug") == 0) {
QTimer::singleShot(300, this, &PythonEditorView::startDebug);
return true;
}
else if (strcmp(pMsg,"ToggleBreakpoint")==0) {
else if (strcmp(pMsg, "ToggleBreakpoint") == 0) {
toggleBreakpoint();
return true;
}
@@ -632,12 +678,15 @@ bool PythonEditorView::onMsg(const char* pMsg,const char** ppReturn)
*/
bool PythonEditorView::onHasMsg(const char* pMsg) const
{
if (strcmp(pMsg,"Run")==0)
if (strcmp(pMsg, "Run") == 0) {
return true;
if (strcmp(pMsg,"StartDebug")==0)
}
if (strcmp(pMsg, "StartDebug") == 0) {
return true;
if (strcmp(pMsg,"ToggleBreakpoint")==0)
}
if (strcmp(pMsg, "ToggleBreakpoint") == 0) {
return true;
}
return EditorView::onHasMsg(pMsg);
}
@@ -647,12 +696,13 @@ bool PythonEditorView::onHasMsg(const char* pMsg) const
void PythonEditorView::executeScript()
{
// always save the macro when it is modified
if (EditorView::onHasMsg("Save"))
if (EditorView::onHasMsg("Save")) {
EditorView::onMsg("Save", nullptr);
}
try {
getMainWindow()->setCursor(Qt::WaitCursor);
PythonTracingLocker tracelock(watcher->getTrace());
Application::Instance->macroManager()->run(Gui::MacroManager::File,fileName().toUtf8());
Application::Instance->macroManager()->run(Gui::MacroManager::File, fileName().toUtf8());
getMainWindow()->unsetCursor();
}
catch (const Base::SystemExitException&) {
@@ -771,8 +821,9 @@ void SearchBar::activate()
void SearchBar::deactivate()
{
if (textEditor)
if (textEditor) {
textEditor->setFocus();
}
hide();
}
@@ -793,32 +844,39 @@ void SearchBar::findCurrent()
void SearchBar::findText(bool skip, bool next, const QString& str)
{
if (!textEditor)
if (!textEditor) {
return;
}
QTextCursor cursor = textEditor->textCursor();
QTextDocument *doc = textEditor->document();
if (!doc || cursor.isNull())
QTextDocument* doc = textEditor->document();
if (!doc || cursor.isNull()) {
return;
}
if (cursor.hasSelection())
if (cursor.hasSelection()) {
cursor.setPosition((skip && next) ? cursor.position() : cursor.anchor());
}
bool found = true;
QTextCursor newCursor = cursor;
if (!str.isEmpty()) {
QTextDocument::FindFlags options;
if (!next)
if (!next) {
options |= QTextDocument::FindBackward;
if (matchCase->isChecked())
}
if (matchCase->isChecked()) {
options |= QTextDocument::FindCaseSensitively;
if (matchWord->isChecked())
}
if (matchWord->isChecked()) {
options |= QTextDocument::FindWholeWords;
}
newCursor = doc->find(str, cursor, options);
if (newCursor.isNull()) {
QTextCursor ac(doc);
ac.movePosition(options & QTextDocument::FindBackward ? QTextCursor::End : QTextCursor::Start);
ac.movePosition(options & QTextDocument::FindBackward ? QTextCursor::End
: QTextCursor::Start);
newCursor = doc->find(str, ac, options);
if (newCursor.isNull()) {
found = false;
@@ -827,18 +885,17 @@ void SearchBar::findText(bool skip, bool next, const QString& str)
}
}
if (!isVisible())
if (!isVisible()) {
show();
}
textEditor->setTextCursor(newCursor);
QString styleSheet;
if (!found) {
styleSheet = QString::fromLatin1(
" QLineEdit {\n"
" background-color: rgb(221,144,161);\n"
" }\n"
);
styleSheet = QString::fromLatin1(" QLineEdit {\n"
" background-color: rgb(221,144,161);\n"
" }\n");
}
searchText->setStyleSheet(styleSheet);

View File

@@ -23,12 +23,12 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string/predicate.hpp>
# include <QAbstractItemView>
# include <QContextMenuEvent>
# include <QLineEdit>
# include <QMenu>
# include <QTextBlock>
#include <boost/algorithm/string/predicate.hpp>
#include <QAbstractItemView>
#include <QContextMenuEvent>
#include <QLineEdit>
#include <QMenu>
#include <QTextBlock>
#endif
#include <App/Application.h>
@@ -53,11 +53,12 @@ class ExpressionCompleterModel: public QAbstractItemModel
{
public:
ExpressionCompleterModel(QObject* parent, bool noProperty)
:QAbstractItemModel(parent), noProperty(noProperty)
{
}
: QAbstractItemModel(parent)
, noProperty(noProperty)
{}
void setNoProperty(bool enabled) {
void setNoProperty(bool enabled)
{
noProperty = enabled;
}
@@ -79,6 +80,7 @@ public:
endResetModel();
}
// clang-format off
// This ExpressionCompleter model works without any physical items.
// Everything item related is stored inside QModelIndex.InternalPointer/InternalId(),
// using the following Info structure.
@@ -154,6 +156,7 @@ public:
// |-- prop2.path1 (contextual) - (row 0, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM
// |-- prop2.path2 (contextual) - (row 1, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM
//
// clang-format on
struct Info
{
@@ -165,20 +168,21 @@ public:
static const Info root;
};
static const quint64 k_numBitsProp = 16ULL; // 0 .. 15
static const quint64 k_numBitsObj = 24ULL; // 16.. 39
static const quint64 k_numBitsContextualHierarchy = 1; // 40
static const quint64 k_numBitsDocuments = 23ULL; // 41.. 63
static const quint64 k_numBitsProp = 16ULL; // 0 .. 15
static const quint64 k_numBitsObj = 24ULL; // 16.. 39
static const quint64 k_numBitsContextualHierarchy = 1; // 40
static const quint64 k_numBitsDocuments = 23ULL; // 41.. 63
static const quint64 k_offsetProp = 0;
static const quint64 k_offsetObj = k_offsetProp + k_numBitsProp;
static const quint64 k_offsetContextualHierarchy = k_offsetObj + k_numBitsObj;
static const quint64 k_offsetDocuments = k_offsetContextualHierarchy + k_numBitsContextualHierarchy;
static const quint64 k_offsetProp = 0;
static const quint64 k_offsetObj = k_offsetProp + k_numBitsProp;
static const quint64 k_offsetContextualHierarchy = k_offsetObj + k_numBitsObj;
static const quint64 k_offsetDocuments =
k_offsetContextualHierarchy + k_numBitsContextualHierarchy;
static const quint64 k_maskProp = ((1ULL << k_numBitsProp) - 1);
static const quint64 k_maskObj = ((1ULL << k_numBitsObj) - 1);
static const quint64 k_maskContextualHierarchy = ((1ULL << k_numBitsContextualHierarchy) - 1);
static const quint64 k_maskDocuments = ((1ULL << k_numBitsDocuments) - 1);
static const quint64 k_maskProp = ((1ULL << k_numBitsProp) - 1);
static const quint64 k_maskObj = ((1ULL << k_numBitsObj) - 1);
static const quint64 k_maskContextualHierarchy = ((1ULL << k_numBitsContextualHierarchy) - 1);
static const quint64 k_maskDocuments = ((1ULL << k_numBitsDocuments) - 1);
union InfoPtrEncoding
{
@@ -249,8 +253,9 @@ public:
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (role != Qt::EditRole && role != Qt::DisplayRole && role != Qt::UserRole)
if (role != Qt::EditRole && role != Qt::DisplayRole && role != Qt::UserRole) {
return {};
}
QVariant variant;
Info info = getInfo(index);
_data(info, index.row(), &variant, nullptr, role == Qt::UserRole);
@@ -265,10 +270,11 @@ public:
if (prop) {
prop->getPaths(result);
// need to filter out irrelevant paths (len 1, aka just this object identifier)
auto res = std::remove_if(
result.begin(), result.end(), [](const App::ObjectIdentifier& path) -> bool {
return path.getComponents().empty();
});
auto res = std::remove_if(result.begin(),
result.end(),
[](const App::ObjectIdentifier& path) -> bool {
return path.getComponents().empty();
});
result.erase(res, result.end());
}
return result;
@@ -295,11 +301,11 @@ public:
// identify the document index. For any children of the root, it is given by traversing
// the flat list and identified by [row]
idx = info.doc < 0 ? row : info.doc;
const auto &docs = App::GetApplication().getDocuments();
const auto& docs = App::GetApplication().getDocuments();
int docSize = (int)docs.size() * 2;
int objSize = 0;
int propSize = 0;
std::vector<std::pair<const char*, App::Property*> > props;
std::vector<std::pair<const char*, App::Property*>> props;
App::Document* doc = nullptr;
App::DocumentObject* obj = nullptr;
const char* propName = nullptr;
@@ -311,28 +317,33 @@ public:
}
else {
// if we're looking at the ROOT, or the row identifies one of the other ROOT elements
// |----- current documents' objects, rows: docs.size ... docs.size + objs.size
// |----- current objects' props, rows: docs.size + objs.size ... docs.size + objs.size+ props.size
// |----- current documents' objects, rows: docs.size ... docs.size +
// objs.size
// |----- current objects' props, rows: docs.size + objs.size ... docs.size +
// objs.size+ props.size
//
// We need to process the ROOT so we get the correct count for its children
doc = App::GetApplication().getDocument(currentDoc.c_str());
if (!doc)// no current, there are no additional objects
if (!doc) { // no current, there are no additional objects
return;
}
// move to the current documents' objects' range
idx -= docSize;
if (info.doc < 0)
if (info.doc < 0) {
row = idx;
}
const auto &objs = doc->getObjects();
const auto& objs = doc->getObjects();
objSize = (int)objs.size() * 2;
// if this is a valid object, we found our object and break.
// if not, this may be the root or one of current object's properties
if (idx >= 0 && idx < objSize) {
obj = objs[idx / 2];
// if they are in the ignore list skip
if (inList.count(obj))
if (inList.count(obj)) {
return;
}
}
else if (!noProperty) {
// need to check the current object's props range, or we're parsing the ROOT
@@ -340,18 +351,21 @@ public:
if (cobj) {
// move to the props range of the current object
idx -= objSize;
if (info.doc < 0)
if (info.doc < 0) {
row = idx;
}
// get the properties
cobj->getPropertyNamedList(props);
propSize = (int)props.size();
// if this is an invalid index, bail out
// if it's the ROOT break!
if (idx >= propSize)
if (idx >= propSize) {
return;
}
if (idx >= 0) {
obj = cobj; // we only set the active object if we're not processing the root.
obj = cobj; // we only set the active object if we're not processing the
// root.
propName = props[idx].first;
prop = props[idx].second;
}
@@ -373,26 +387,35 @@ public:
if (propName) {
res = QString::fromLatin1(propName);
// resolve the property
if (sep && !noProperty && !retrieveSubPaths(prop).empty())
if (sep && !noProperty && !retrieveSubPaths(prop).empty()) {
res += QLatin1Char('.');
}
}
else if (obj) {
// the object has been resolved, use the saved idx to figure out quotation or not.
if (idx & 1)
// the object has been resolved, use the saved idx to figure out quotation or
// not.
if (idx & 1) {
res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str());
else
}
else {
res = QString::fromLatin1(obj->getNameInDocument());
if (sep && !noProperty)
}
if (sep && !noProperty) {
res += QLatin1Char('.');
}
}
else {
// the document has been resolved, use the saved idx to figure out quotation or not.
if (idx & 1)
// the document has been resolved, use the saved idx to figure out quotation or
// not.
if (idx & 1) {
res = QString::fromUtf8(quote(doc->Label.getStrValue()).c_str());
else
}
else {
res = QString::fromLatin1(doc->getName());
if (sep)
}
if (sep) {
res += QLatin1Char('#');
}
}
v->setValue(res);
}
@@ -404,34 +427,40 @@ public:
if (!obj) {
// are we pointing to an object item, or our father (info) is an object
idx = info.obj < 0 ? row : info.obj;
const auto &objs = doc->getObjects();
const auto& objs = doc->getObjects();
objSize = (int)objs.size() * 2;
// if invalid index, or in the ignore list bail out
if (idx < 0 || idx >= objSize || inList.count(obj))
if (idx < 0 || idx >= objSize || inList.count(obj)) {
return;
}
obj = objs[idx / 2];
if (info.obj < 0) {
// if this is AN actual Object item and not a root
if (count)
*count = objSize; // set the correct count if requested
if (count) {
*count = objSize; // set the correct count if requested
}
if (v) {
// resolve the name
QString res;
if (idx & 1)
if (idx & 1) {
res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str());
else
}
else {
res = QString::fromLatin1(obj->getNameInDocument());
if (sep && !noProperty)
}
if (sep && !noProperty) {
res += QLatin1Char('.');
}
v->setValue(res);
}
return;
}
}
if (noProperty)
if (noProperty) {
return;
}
if (!propName) {
idx = info.prop < 0 ? row : info.prop;
obj->getPropertyNamedList(props);
@@ -452,8 +481,9 @@ public:
QString res = QString::fromLatin1(propName);
// check to see if we have accessible paths from this prop name?
if (sep && !retrieveSubPaths(prop).empty())
if (sep && !retrieveSubPaths(prop).empty()) {
res += QLatin1Char('.');
}
*v = res;
}
return;
@@ -489,9 +519,11 @@ public:
return;
}
QModelIndex parent(const QModelIndex & index) const override {
if (!index.isValid())
QModelIndex parent(const QModelIndex& index) const override
{
if (!index.isValid()) {
return {};
}
Info parentInfo = getInfo(index);
Info grandParentInfo = parentInfo;
@@ -505,7 +537,8 @@ public:
grandParentInfo.prop = -1;
return createIndex(parentInfo.prop, 0, infoId(grandParentInfo));
}
// if the parent is the object or a prop attached to the root, we just need the below line
// if the parent is the object or a prop attached to the root, we just need the below
// line
return createIndex(parentInfo.doc, 0, infoId(Info::root));
}
else {
@@ -528,7 +561,7 @@ public:
}
// returns true if successful, false if 'element' identifies a Leaf
bool modelIndexToParentInfo(QModelIndex element, Info & info) const
bool modelIndexToParentInfo(QModelIndex element, Info& info) const
{
Info parentInfo;
info = Info::root;
@@ -545,8 +578,8 @@ public:
info.doc = element.row();
// if my element is a contextual descendant of root (current doc object list, current object prop list)
// mark it as such
// if my element is a contextual descendant of root (current doc object list,
// current object prop list) mark it as such
if (element.row() >= docsSize) {
info.contextualHierarchy = 1;
}
@@ -559,18 +592,21 @@ public:
int objsSize = static_cast<int>(cdoc->getObjects().size() * 2);
int idx = parentInfo.doc - static_cast<int>(docs.size());
if (idx < objsSize) {
// |-- Parent (OBJECT) - (row 4, [-1,-1,-1,0]) = encode as element => [parent.row,-1,-1,1]
// |- element (PROP) - (row 0, [parent.row,-1,-1,1]) = encode as element => [parent.row,-1,parent.row,1]
// |-- Parent (OBJECT) - (row 4, [-1,-1,-1,0]) = encode as element =>
// [parent.row,-1,-1,1]
// |- element (PROP) - (row 0, [parent.row,-1,-1,1]) = encode as
// element => [parent.row,-1,parent.row,1]
info.doc = parentInfo.doc;
info.obj = -1;// object information is determined by the DOC index actually
info.obj =
-1; // object information is determined by the DOC index actually
info.prop = element.row();
info.contextualHierarchy = 1;
}
else {
// if my parent (parentInfo) is a prop, it means that our element is a prop path
// and that is a leaf item (we don't split prop paths further)
// we can't encode leaf items into an "Info"
// if my parent (parentInfo) is a prop, it means that our element is a prop
// path and that is a leaf item (we don't split prop paths further) we can't
// encode leaf items into an "Info"
return false;
}
}
@@ -578,7 +614,6 @@ public:
// no contextual document
return false;
}
}
// regular hierarchy
else if (parentInfo.obj <= 0) {
@@ -594,10 +629,11 @@ public:
return true;
}
QModelIndex index(int row, int column,
const QModelIndex & parent = QModelIndex()) const override {
if (row < 0)
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override
{
if (row < 0) {
return {};
}
Info myParentInfoEncoded = Info::root;
// encode the parent's QModelIndex into an 'Info' structure
@@ -655,47 +691,59 @@ const ExpressionCompleterModel::Info ExpressionCompleterModel::Info::root = {-1,
*/
ExpressionCompleter::ExpressionCompleter(const App::DocumentObject* currentDocObj,
QObject* parent, bool noProperty, bool checkInList)
: QCompleter(parent), currentObj(currentDocObj)
, noProperty(noProperty), checkInList(checkInList)
QObject* parent,
bool noProperty,
bool checkInList)
: QCompleter(parent)
, currentObj(currentDocObj)
, noProperty(noProperty)
, checkInList(checkInList)
{
setCaseSensitivity(Qt::CaseInsensitive);
}
void ExpressionCompleter::init() {
if (model())
void ExpressionCompleter::init()
{
if (model()) {
return;
}
auto m = new ExpressionCompleterModel(this,noProperty);
m->setDocumentObject(currentObj.getObject(),checkInList);
auto m = new ExpressionCompleterModel(this, noProperty);
m->setDocumentObject(currentObj.getObject(), checkInList);
setModel(m);
}
void ExpressionCompleter::setDocumentObject(const App::DocumentObject* obj, bool _checkInList)
{
if (!obj || !obj->isAttachedToDocument())
if (!obj || !obj->isAttachedToDocument()) {
currentObj = App::DocumentObjectT();
else
}
else {
currentObj = obj;
}
setCompletionPrefix(QString());
checkInList = _checkInList;
auto m = model();
if (m)
if (m) {
static_cast<ExpressionCompleterModel*>(m)->setDocumentObject(obj, checkInList);
}
}
void ExpressionCompleter::setNoProperty(bool enabled) {
void ExpressionCompleter::setNoProperty(bool enabled)
{
noProperty = enabled;
auto m = model();
if (m)
if (m) {
static_cast<ExpressionCompleterModel*>(m)->setNoProperty(enabled);
}
}
QString ExpressionCompleter::pathFromIndex(const QModelIndex& index) const
{
auto m = model();
if (!m || !index.isValid())
if (!m || !index.isValid()) {
return {};
}
QString res;
auto parent = index;
@@ -706,8 +754,8 @@ QString ExpressionCompleter::pathFromIndex(const QModelIndex& index) const
auto info = ExpressionCompleterModel::getInfo(index);
FC_TRACE("join path " << info.doc << "," << info.obj << "," << info.prop << ","
<< info.contextualHierarchy << "," << index.row()
<< ": " << res.toUtf8().constData());
<< info.contextualHierarchy << "," << index.row() << ": "
<< res.toUtf8().constData());
return res;
}
@@ -715,8 +763,9 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const
{
QStringList resultList;
std::string path = input.toUtf8().constData();
if (path.empty())
if (path.empty()) {
return resultList;
}
int retry = 0;
std::string lastElem; // used to recover in case of parse failure after ".".
@@ -726,17 +775,18 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const
// this will not work for incomplete Tokens at the end
// "Sketch." will fail to parse and complete.
App::ObjectIdentifier ident = ObjectIdentifier::parse(
currentObj.getObject(), path);
App::ObjectIdentifier ident = ObjectIdentifier::parse(currentObj.getObject(), path);
std::vector<std::string> stringList = ident.getStringList();
auto stringListIter = stringList.begin();
if (retry > 1 && !stringList.empty())
if (retry > 1 && !stringList.empty()) {
stringList.pop_back();
}
if (!stringList.empty()) {
if (!trim.empty() && boost::ends_with(stringList.back(), trim))
if (!trim.empty() && boost::ends_with(stringList.back(), trim)) {
stringList.back().resize(stringList.back().size() - trim.size());
}
while (stringListIter != stringList.end()) {
resultList << Base::Tools::fromStdString(*stringListIter);
++stringListIter;
@@ -748,7 +798,8 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const
// erase the separator
lastElem.erase(lastElem.begin());
resultList << Base::Tools::fromStdString(lastElem);
} else {
}
else {
// add empty string to allow completion after "." or "#"
resultList << QString();
}
@@ -778,7 +829,8 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const
path = path + lastElem;
lastElem = "";
}
// else... we don't reset lastElem if it's a '.' or '#' to allow chaining completions
// else... we don't reset lastElem if it's a '.' or '#' to allow chaining
// completions
if (!path.empty()) {
char last = path[path.size() - 1];
if (last != '#' && last != '.' && path.find('#') != std::string::npos) {
@@ -810,7 +862,7 @@ QStringList ExpressionCompleter::splitPath(const QString& input) const
// Code below inspired by blog entry:
// https://john.nachtimwald.com/2009/07/04/qcompleter-and-comma-separated-tags/
void ExpressionCompleter::slotUpdate(const QString & prefix, int pos)
void ExpressionCompleter::slotUpdate(const QString& prefix, int pos)
{
FC_TRACE("SlotUpdate:" << prefix.toUtf8().constData());
@@ -818,8 +870,9 @@ void ExpressionCompleter::slotUpdate(const QString & prefix, int pos)
QString completionPrefix = tokenizer.perform(prefix, pos);
if (completionPrefix.isEmpty()) {
if (auto itemView = popup())
if (auto itemView = popup()) {
itemView->setVisible(false);
}
return;
}
@@ -831,15 +884,16 @@ void ExpressionCompleter::slotUpdate(const QString & prefix, int pos)
FC_TRACE("Complete on Prefix" << completionPrefix.toUtf8().constData());
complete();
FC_TRACE("Complete Done");
}
else if (auto itemView = popup()) {
itemView->setVisible(false);
}
}
ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, bool noProperty,
char checkPrefix, bool checkInList)
ExpressionLineEdit::ExpressionLineEdit(QWidget* parent,
bool noProperty,
char checkPrefix,
bool checkInList)
: QLineEdit(parent)
, completer(nullptr)
, block(true)
@@ -851,12 +905,13 @@ ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, bool noProperty,
connect(this, &QLineEdit::textEdited, this, &ExpressionLineEdit::slotTextChanged);
}
void ExpressionLineEdit::setPrefix(char prefix) {
void ExpressionLineEdit::setPrefix(char prefix)
{
checkPrefix = prefix;
}
void ExpressionLineEdit::setDocumentObject(const App::DocumentObject* currentDocObj,
bool _checkInList)
bool _checkInList)
{
checkInList = _checkInList;
if (completer) {
@@ -867,29 +922,38 @@ void ExpressionLineEdit::setDocumentObject(const App::DocumentObject* currentDoc
completer = new ExpressionCompleter(currentDocObj, this, noProperty, checkInList);
completer->setWidget(this);
completer->setCaseSensitivity(Qt::CaseInsensitive);
if (!exactMatch)
if (!exactMatch) {
completer->setFilterMode(Qt::MatchContains);
connect(completer, qOverload<const QString&>(&QCompleter::activated),
this, &ExpressionLineEdit::slotCompleteTextSelected);
}
connect(completer,
qOverload<const QString&>(&QCompleter::activated),
this,
&ExpressionLineEdit::slotCompleteTextSelected);
connect(completer,
qOverload<const QString&>(&QCompleter::highlighted),
this, &ExpressionLineEdit::slotCompleteTextHighlighted);
connect(this, &ExpressionLineEdit::textChanged2,
completer, &ExpressionCompleter::slotUpdate);
this,
&ExpressionLineEdit::slotCompleteTextHighlighted);
connect(this,
&ExpressionLineEdit::textChanged2,
completer,
&ExpressionCompleter::slotUpdate);
}
}
void ExpressionLineEdit::setNoProperty(bool enabled) {
void ExpressionLineEdit::setNoProperty(bool enabled)
{
noProperty = enabled;
if (completer)
if (completer) {
completer->setNoProperty(enabled);
}
}
void ExpressionLineEdit::setExactMatch(bool enabled) {
void ExpressionLineEdit::setExactMatch(bool enabled)
{
exactMatch = enabled;
if (completer)
if (completer) {
completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains);
}
}
bool ExpressionLineEdit::completerActive() const
@@ -899,23 +963,25 @@ bool ExpressionLineEdit::completerActive() const
void ExpressionLineEdit::hideCompleter()
{
if (completer && completer->popup())
if (completer && completer->popup()) {
completer->popup()->setVisible(false);
}
void ExpressionLineEdit::slotTextChanged(const QString & text)
{
if (!block) {
if (!text.size() || (checkPrefix && text[0] != QLatin1Char(checkPrefix)))
return;
Q_EMIT textChanged2(text,cursorPosition());
}
}
void ExpressionLineEdit::slotCompleteText(const QString & completionPrefix, bool isActivated)
void ExpressionLineEdit::slotTextChanged(const QString& text)
{
int start,end;
completer->getPrefixRange(start,end);
if (!block) {
if (!text.size() || (checkPrefix && text[0] != QLatin1Char(checkPrefix))) {
return;
}
Q_EMIT textChanged2(text, cursorPosition());
}
}
void ExpressionLineEdit::slotCompleteText(const QString& completionPrefix, bool isActivated)
{
int start, end;
completer->getPrefixRange(start, end);
QString before(text().left(start));
QString after(text().mid(end));
@@ -952,7 +1018,7 @@ void ExpressionLineEdit::slotCompleteTextSelected(const QString& completionPrefi
void ExpressionLineEdit::keyPressEvent(QKeyEvent* e)
{
Base::FlagToggler<bool> flag(block,true);
Base::FlagToggler<bool> flag(block, true);
QLineEdit::keyPressEvent(e);
}
@@ -962,11 +1028,10 @@ void ExpressionLineEdit::contextMenuEvent(QContextMenuEvent* event)
if (completer) {
menu->addSeparator();
QAction *match = menu->addAction(tr("Exact match"));
QAction* match = menu->addAction(tr("Exact match"));
match->setCheckable(true);
match->setChecked(completer->filterMode() == Qt::MatchStartsWith);
QObject::connect(match, &QAction::toggled,
this, &Gui::ExpressionLineEdit::setExactMatch);
QObject::connect(match, &QAction::toggled, this, &Gui::ExpressionLineEdit::setExactMatch);
}
menu->setAttribute(Qt::WA_DeleteOnClose);
@@ -988,8 +1053,9 @@ ExpressionTextEdit::ExpressionTextEdit(QWidget* parent)
void ExpressionTextEdit::setExactMatch(bool enabled)
{
exactMatch = enabled;
if (completer)
if (completer) {
completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains);
}
}
void ExpressionTextEdit::setDocumentObject(const App::DocumentObject* currentDocObj)
@@ -1001,16 +1067,23 @@ void ExpressionTextEdit::setDocumentObject(const App::DocumentObject* currentDoc
if (currentDocObj) {
completer = new ExpressionCompleter(currentDocObj, this);
if (!exactMatch)
if (!exactMatch) {
completer->setFilterMode(Qt::MatchContains);
}
completer->setWidget(this);
completer->setCaseSensitivity(Qt::CaseInsensitive);
connect(completer, qOverload<const QString&>(&QCompleter::activated), this,
&ExpressionTextEdit::slotCompleteText);
connect(completer, qOverload<const QString&>(&QCompleter::highlighted), this,
&ExpressionTextEdit::slotCompleteText);
connect(this, &ExpressionTextEdit::textChanged2, completer,
&ExpressionCompleter::slotUpdate);
connect(completer,
qOverload<const QString&>(&QCompleter::activated),
this,
&ExpressionTextEdit::slotCompleteText);
connect(completer,
qOverload<const QString&>(&QCompleter::highlighted),
this,
&ExpressionTextEdit::slotCompleteText);
connect(this,
&ExpressionTextEdit::textChanged2,
completer,
&ExpressionCompleter::slotUpdate);
}
}
@@ -1021,36 +1094,37 @@ bool ExpressionTextEdit::completerActive() const
void ExpressionTextEdit::hideCompleter()
{
if (completer && completer->popup())
if (completer && completer->popup()) {
completer->popup()->setVisible(false);
}
}
void ExpressionTextEdit::slotTextChanged()
{
if (!block) {
QTextCursor cursor = textCursor();
Q_EMIT textChanged2(cursor.block().text(),cursor.positionInBlock());
Q_EMIT textChanged2(cursor.block().text(), cursor.positionInBlock());
}
}
void ExpressionTextEdit::slotCompleteText(const QString& completionPrefix)
{
QTextCursor cursor = textCursor();
int start,end;
completer->getPrefixRange(start,end);
int start, end;
completer->getPrefixRange(start, end);
int pos = cursor.positionInBlock();
if (pos < end) {
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, end - pos);
}
cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,end-start);
Base::FlagToggler<bool> flag(block,false);
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, end - start);
Base::FlagToggler<bool> flag(block, false);
cursor.insertText(completionPrefix);
completer->updatePrefixEnd(cursor.positionInBlock());
}
void ExpressionTextEdit::keyPressEvent(QKeyEvent* e)
{
Base::FlagToggler<bool> flag(block,true);
Base::FlagToggler<bool> flag(block, true);
QPlainTextEdit::keyPressEvent(e);
}
@@ -1071,8 +1145,9 @@ void ExpressionTextEdit::contextMenuEvent(QContextMenuEvent* event)
QAction* action = menu->exec(event->globalPos());
if (completer) {
if (action == match)
if (action == match) {
setExactMatch(match->isChecked());
}
}
delete menu;
@@ -1088,15 +1163,15 @@ ExpressionParameter* ExpressionParameter::instance()
bool ExpressionParameter::isCaseSensitive() const
{
auto handle = GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Expression");
auto handle =
GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Expression");
return handle->GetBool("CompleterCaseSensitive", false);
}
bool ExpressionParameter::isExactMatch() const
{
auto handle = GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Expression");
auto handle =
GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Expression");
return handle->GetBool("CompleterMatchExact", false);
}

View File

@@ -23,13 +23,13 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QPixmap>
# include <QMenu>
# include <Inventor/SbBox.h>
# include <Inventor/events/SoEvent.h>
# include <Inventor/events/SoKeyboardEvent.h>
# include <Inventor/events/SoLocation2Event.h>
# include <Inventor/events/SoMouseButtonEvent.h>
#include <QPixmap>
#include <QMenu>
#include <Inventor/SbBox.h>
#include <Inventor/events/SoEvent.h>
#include <Inventor/events/SoKeyboardEvent.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#endif
#include "MouseSelection.h"
@@ -70,38 +70,39 @@ void AbstractMouseSelection::releaseMouseModel(bool abort)
int AbstractMouseSelection::handleEvent(const SoEvent* const ev, const SbViewportRegion& vp)
{
int ret=Continue;
int ret = Continue;
const SbVec2s& sz = vp.getWindowSize();
short w,h;
sz.getValue(w,h);
short w, h;
sz.getValue(w, h);
SbVec2s loc = ev->getPosition();
short x,y;
loc.getValue(x,y);
y = h-y; // the origin is at the left bottom corner (instead of left top corner)
short x, y;
loc.getValue(x, y);
y = h - y; // the origin is at the left bottom corner (instead of left top corner)
if (ev->getTypeId().isDerivedFrom(SoMouseButtonEvent::getClassTypeId())) {
const auto event = (const SoMouseButtonEvent*) ev;
const auto event = (const SoMouseButtonEvent*)ev;
const SbBool press = event->getState() == SoButtonEvent::DOWN ? true : false;
if (press) {
_clPoly.push_back(ev->getPosition());
ret = mouseButtonEvent(static_cast<const SoMouseButtonEvent*>(ev), QPoint(x,y));
ret = mouseButtonEvent(static_cast<const SoMouseButtonEvent*>(ev), QPoint(x, y));
}
else {
ret = mouseButtonEvent(static_cast<const SoMouseButtonEvent*>(ev), QPoint(x,y));
ret = mouseButtonEvent(static_cast<const SoMouseButtonEvent*>(ev), QPoint(x, y));
}
}
else if (ev->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId())) {
ret = locationEvent(static_cast<const SoLocation2Event*>(ev), QPoint(x,y));
ret = locationEvent(static_cast<const SoLocation2Event*>(ev), QPoint(x, y));
}
else if (ev->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId())) {
ret = keyboardEvent(static_cast<const SoKeyboardEvent*>(ev));
}
if (ret == Restart)
if (ret == Restart) {
_clPoly.clear();
}
return ret;
}
@@ -110,9 +111,9 @@ int AbstractMouseSelection::handleEvent(const SoEvent* const ev, const SbViewpor
BaseMouseSelection::BaseMouseSelection()
: AbstractMouseSelection()
{
}
{}
// clang-format off
static const char* cursor_cut_scissors[]= {
"32 32 6 1",
"a c #800000",
@@ -154,6 +155,7 @@ static const char* cursor_cut_scissors[]= {
"................................",
"................................"
};
// clang-format on
PolyPickerSelection::PolyPickerSelection()
{
@@ -162,7 +164,7 @@ PolyPickerSelection::PolyPickerSelection()
void PolyPickerSelection::setColor(float r, float g, float b, float a)
{
polyline.setColor(r,g,b,a);
polyline.setColor(r, g, b, a);
}
void PolyPickerSelection::setLineWidth(float l)
@@ -179,7 +181,7 @@ void PolyPickerSelection::initialize()
polyline.setViewer(_pcView3D);
_pcView3D->addGraphicsItem(&polyline);
_pcView3D->redraw(); // needed to get an up-to-date image
_pcView3D->redraw(); // needed to get an up-to-date image
_pcView3D->setRenderType(View3DInventorViewer::Image);
_pcView3D->redraw();
@@ -209,17 +211,21 @@ int PolyPickerSelection::popupMenu()
menu.addAction(QObject::tr("Clear"));
QAction* ca = menu.addAction(QObject::tr("Cancel"));
if(getPositions().size() < 3)
if (getPositions().size() < 3) {
fi->setEnabled(false);
}
QAction* id = menu.exec(QCursor::pos());
if (id == fi)
if (id == fi) {
return Finish;
else if (id == ca)
}
else if (id == ca) {
return Cancel;
else
}
else {
return Restart;
}
}
int PolyPickerSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos)
@@ -228,63 +234,57 @@ int PolyPickerSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, con
const SbBool press = e->getState() == SoButtonEvent::DOWN ? true : false;
if (press) {
switch(button)
{
case SoMouseButtonEvent::BUTTON1:
{
if (!polyline.isWorking()) {
polyline.setWorking(true);
polyline.clear();
};
polyline.addNode(pos);
lastConfirmed = true;
m_iXnew = pos.x(); m_iYnew = pos.y();
m_iXold = pos.x(); m_iYold = pos.y();
}
break;
switch (button) {
case SoMouseButtonEvent::BUTTON1: {
if (!polyline.isWorking()) {
polyline.setWorking(true);
polyline.clear();
};
polyline.addNode(pos);
lastConfirmed = true;
m_iXnew = pos.x();
m_iYnew = pos.y();
m_iXold = pos.x();
m_iYold = pos.y();
} break;
case SoMouseButtonEvent::BUTTON2:
{
polyline.addNode(pos);
m_iXnew = pos.x(); m_iYnew = pos.y();
m_iXold = pos.x(); m_iYold = pos.y();
}
break;
case SoMouseButtonEvent::BUTTON2: {
polyline.addNode(pos);
m_iXnew = pos.x();
m_iYnew = pos.y();
m_iXold = pos.x();
m_iYold = pos.y();
} break;
default:
{
} break;
default: {
} break;
}
}
// release
else {
switch(button)
{
case SoMouseButtonEvent::BUTTON2:
{
QCursor cur = _pcView3D->getWidget()->cursor();
_pcView3D->getWidget()->setCursor(m_cPrevCursor);
switch (button) {
case SoMouseButtonEvent::BUTTON2: {
QCursor cur = _pcView3D->getWidget()->cursor();
_pcView3D->getWidget()->setCursor(m_cPrevCursor);
// The pop-up menu should be shown when releasing mouse button because
// otherwise the navigation style doesn't get the UP event and gets into
// an inconsistent state.
int id = popupMenu();
// The pop-up menu should be shown when releasing mouse button because
// otherwise the navigation style doesn't get the UP event and gets into
// an inconsistent state.
int id = popupMenu();
if (id == Finish || id == Cancel) {
releaseMouseModel();
}
else if (id == Restart) {
_pcView3D->getWidget()->setCursor(cur);
}
if (id == Finish || id == Cancel) {
releaseMouseModel();
}
else if (id == Restart) {
_pcView3D->getWidget()->setCursor(cur);
}
polyline.setWorking(false);
return id;
}
break;
polyline.setWorking(false);
return id;
} break;
default:
{
} break;
default: {
} break;
}
}
@@ -301,22 +301,26 @@ int PolyPickerSelection::locationEvent(const SoLocation2Event* const, const QPoi
qreal dpr = _pcView3D->getGLWidget()->devicePixelRatioF();
QRect r = _pcView3D->getGLWidget()->rect();
if (dpr != 1.0) {
r.setHeight(r.height()*dpr);
r.setWidth(r.width()*dpr);
r.setHeight(r.height() * dpr);
r.setWidth(r.width() * dpr);
}
if (!r.contains(clPoint)) {
if (clPoint.x() < r.left())
if (clPoint.x() < r.left()) {
clPoint.setX(r.left());
}
if (clPoint.x() > r.right())
if (clPoint.x() > r.right()) {
clPoint.setX(r.right());
}
if (clPoint.y() < r.top())
if (clPoint.y() < r.top()) {
clPoint.setY(r.top());
}
if (clPoint.y() > r.bottom())
if (clPoint.y() > r.bottom()) {
clPoint.setY(r.bottom());
}
#ifdef FC_OS_WINDOWS
QPoint newPos = _pcView3D->getGLWidget()->mapToGlobal(clPoint);
@@ -324,8 +328,9 @@ int PolyPickerSelection::locationEvent(const SoLocation2Event* const, const QPoi
#endif
}
if (!lastConfirmed)
if (!lastConfirmed) {
polyline.popNode();
}
polyline.addNode(clPoint);
lastConfirmed = false;
@@ -413,16 +418,20 @@ int FreehandSelection::popupMenu()
menu.addAction(QObject::tr("Clear"));
QAction* ca = menu.addAction(QObject::tr("Cancel"));
if (getPositions().size() < 3)
if (getPositions().size() < 3) {
fi->setEnabled(false);
}
QAction* id = menu.exec(QCursor::pos());
if (id == fi)
if (id == fi) {
return Finish;
else if (id == ca)
}
else if (id == ca) {
return Cancel;
else
}
else {
return Restart;
}
}
int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos)
@@ -431,9 +440,8 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const
const SbBool press = e->getState() == SoButtonEvent::DOWN ? true : false;
if (press) {
switch(button) {
case SoMouseButtonEvent::BUTTON1:
{
switch (button) {
case SoMouseButtonEvent::BUTTON1: {
if (!polyline.isWorking()) {
polyline.setWorking(true);
polyline.clear();
@@ -441,35 +449,34 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const
polyline.addNode(pos);
polyline.setCoords(pos.x(), pos.y());
m_iXnew = pos.x(); m_iYnew = pos.y();
m_iXold = pos.x(); m_iYold = pos.y();
}
break;
m_iXnew = pos.x();
m_iYnew = pos.y();
m_iXold = pos.x();
m_iYold = pos.y();
} break;
case SoMouseButtonEvent::BUTTON2:
{
polyline.addNode(pos);
m_iXnew = pos.x(); m_iYnew = pos.y();
m_iXold = pos.x(); m_iYold = pos.y();
}
break;
case SoMouseButtonEvent::BUTTON2: {
polyline.addNode(pos);
m_iXnew = pos.x();
m_iYnew = pos.y();
m_iXold = pos.x();
m_iYold = pos.y();
} break;
default:
break;
default:
break;
}
}
// release
else {
switch(button)
{
case SoMouseButtonEvent::BUTTON1:
if (polyline.isWorking()) {
releaseMouseModel();
return Finish;
}
break;
case SoMouseButtonEvent::BUTTON2:
{
switch (button) {
case SoMouseButtonEvent::BUTTON1:
if (polyline.isWorking()) {
releaseMouseModel();
return Finish;
}
break;
case SoMouseButtonEvent::BUTTON2: {
QCursor cur = _pcView3D->getWidget()->cursor();
_pcView3D->getWidget()->setCursor(m_cPrevCursor);
@@ -487,11 +494,10 @@ int FreehandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, const
polyline.setWorking(false);
return id;
}
break;
} break;
default:
break;
default:
break;
}
}
@@ -508,29 +514,34 @@ int FreehandSelection::locationEvent(const SoLocation2Event* const e, const QPoi
qreal dpr = _pcView3D->getGLWidget()->devicePixelRatioF();
QRect r = _pcView3D->getGLWidget()->rect();
if (dpr != 1.0) {
r.setHeight(r.height()*dpr);
r.setWidth(r.width()*dpr);
r.setHeight(r.height() * dpr);
r.setWidth(r.width() * dpr);
}
if (!r.contains(clPoint)) {
if (clPoint.x() < r.left())
if (clPoint.x() < r.left()) {
clPoint.setX(r.left());
}
if (clPoint.x() > r.right())
if (clPoint.x() > r.right()) {
clPoint.setX(r.right());
}
if (clPoint.y() < r.top())
if (clPoint.y() < r.top()) {
clPoint.setY(r.top());
}
if (clPoint.y() > r.bottom())
if (clPoint.y() > r.bottom()) {
clPoint.setY(r.bottom());
}
}
SbVec2s last = _clPoly.back();
SbVec2s curr = e->getPosition();
if (abs(last[0]-curr[0]) > 20 || abs(last[1]-curr[1]) > 20)
if (abs(last[0] - curr[0]) > 20 || abs(last[1] - curr[1]) > 20) {
_clPoly.push_back(curr);
}
polyline.addNode(clPoint);
polyline.setCoords(clPoint.x(), clPoint.y());
@@ -556,7 +567,7 @@ RubberbandSelection::~RubberbandSelection() = default;
void RubberbandSelection::setColor(float r, float g, float b, float a)
{
rubberband.setColor(r,g,b,a);
rubberband.setColor(r, g, b, a);
}
void RubberbandSelection::initialize()
@@ -594,35 +605,28 @@ int RubberbandSelection::mouseButtonEvent(const SoMouseButtonEvent* const e, con
int ret = Continue;
if (press) {
switch(button)
{
case SoMouseButtonEvent::BUTTON1:
{
rubberband.setWorking(true);
m_iXold = m_iXnew = pos.x();
m_iYold = m_iYnew = pos.y();
}
break;
switch (button) {
case SoMouseButtonEvent::BUTTON1: {
rubberband.setWorking(true);
m_iXold = m_iXnew = pos.x();
m_iYold = m_iYnew = pos.y();
} break;
default:
{
} break;
default: {
} break;
}
}
else {
switch(button) {
case SoMouseButtonEvent::BUTTON1:
{
rubberband.setWorking(false);
releaseMouseModel();
_clPoly.push_back(e->getPosition());
ret = Finish;
}
break;
switch (button) {
case SoMouseButtonEvent::BUTTON1: {
rubberband.setWorking(false);
releaseMouseModel();
_clPoly.push_back(e->getPosition());
ret = Finish;
} break;
default:
{
} break;
default: {
} break;
}
}
@@ -645,9 +649,10 @@ int RubberbandSelection::keyboardEvent(const SoKeyboardEvent* const)
// -----------------------------------------------------------------------------------
RectangleSelection::RectangleSelection() : RubberbandSelection()
RectangleSelection::RectangleSelection()
: RubberbandSelection()
{
rubberband.setColor(0.0,0.0,1.0,1.0);
rubberband.setColor(0.0, 0.0, 1.0, 1.0);
}
RectangleSelection::~RectangleSelection() = default;

View File

@@ -22,11 +22,11 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QBuffer>
# include <QImageWriter>
# include <QMessageBox>
# include <QTcpSocket>
#include <QApplication>
#include <QBuffer>
#include <QImageWriter>
#include <QMessageBox>
#include <QTcpSocket>
#endif
#include <Base/Interpreter.h>
@@ -39,6 +39,7 @@
using namespace Gui;
// the favicon
// clang-format off
// NOLINTBEGIN
static const unsigned int navicon_data_len = 318;
static const unsigned char navicon_data[] = {
@@ -66,6 +67,7 @@ static const unsigned char navicon_data[] = {
0x9c,0x3d,0x00,0x00,0x9f,0xfd,0x00,0x00,0x80,0xfd,0x00,0x00,0xff,0x7d,
0x00,0x00,0xfe,0x01,0x00,0x00,0xff,0x7f,0x00,0x00};
// NOLINTEND
// clang-format on
PythonOnlineHelp::PythonOnlineHelp() = default;
@@ -103,7 +105,7 @@ QByteArray PythonOnlineHelp::loadFavicon() const
else {
// fallback
res.reserve(navicon_data_len);
for (int i=0; i<(int)navicon_data_len;i++) {
for (int i = 0; i < (int)navicon_data_len; i++) {
res[i] = navicon_data[i];
}
}
@@ -175,7 +177,8 @@ QByteArray PythonOnlineHelp::fileNotFound() const
"<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">"
"<tr bgcolor=\"#7799ee\">"
"<td valign=bottom>&nbsp;<br>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>FreeCAD Documentation</strong></big></big></font></td>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>FreeCAD "
"Documentation</strong></big></big></font></td>"
"<td align=right valign=bottom>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;</font></td></tr></table>"
"<p><p>"
@@ -184,13 +187,13 @@ QByteArray PythonOnlineHelp::fileNotFound() const
"</strong></p>"
"</div></body>"
"</html>"
"\r\n"
);
"\r\n");
QString header = QString::fromLatin1("content-type: %1\r\n").arg(contentType);
QString http(QLatin1String("HTTP/1.1 %1 %2\r\n%3\r\n"));
QString httpResponseHeader = http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header);
QString httpResponseHeader =
http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header);
QByteArray res = httpResponseHeader.toLatin1();
return res;
@@ -199,37 +202,40 @@ QByteArray PythonOnlineHelp::fileNotFound() const
QByteArray PythonOnlineHelp::loadFailed(const QString& error) const
{
const int pageNotFound = 404;
QString contentType = QString::fromLatin1(
"text/html\r\n"
"\r\n"
"<html><head><title>Error</title></head>"
"<body bgcolor=\"#f0f0f8\">"
"<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">"
"<tr bgcolor=\"#7799ee\">"
"<td valign=bottom>&nbsp;<br>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>FreeCAD Documentation</strong></big></big></font></td>"
"<td align=right valign=bottom>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;</font></td></tr></table>"
"<p><p>"
"<h1>%1</h1>"
"</body>"
"</html>"
"\r\n"
).arg(error);
QString contentType =
QString::fromLatin1(
"text/html\r\n"
"\r\n"
"<html><head><title>Error</title></head>"
"<body bgcolor=\"#f0f0f8\">"
"<table width=\"100%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">"
"<tr bgcolor=\"#7799ee\">"
"<td valign=bottom>&nbsp;<br>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;<br><big><big><strong>FreeCAD "
"Documentation</strong></big></big></font></td>"
"<td align=right valign=bottom>"
"<font color=\"#ffffff\" face=\"helvetica, arial\">&nbsp;</font></td></tr></table>"
"<p><p>"
"<h1>%1</h1>"
"</body>"
"</html>"
"\r\n")
.arg(error);
QString header = QString::fromLatin1("content-type: %1\r\n").arg(contentType);
QString http(QLatin1String("HTTP/1.1 %1 %2\r\n%3\r\n"));
QString httpResponseHeader = http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header);
QString httpResponseHeader =
http.arg(pageNotFound).arg(QString::fromLatin1("File not found"), header);
QByteArray res = httpResponseHeader.toLatin1();
return res;
}
HttpServer::HttpServer(QObject* parent)
: QTcpServer(parent), disabled(false)
{
}
: QTcpServer(parent)
, disabled(false)
{}
void HttpServer::incomingConnection(qintptr socket)
{
@@ -279,8 +285,8 @@ void HttpServer::readClient()
QString p = lst[1];
if (lst.count() > 2) {
QString v = lst[2];
if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") &&
v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit()) {
if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") && v[5].isDigit()
&& v[6] == QLatin1Char('.') && v[7].isDigit()) {
method = m;
path = p;
}
@@ -293,7 +299,7 @@ void HttpServer::readClient()
socket->write(help.loadResource(path));
socket->close();
if (socket->state() == QTcpSocket::UnconnectedState) {
//mark the socket for deletion but do not destroy immediately
// mark the socket for deletion but do not destroy immediately
socket->deleteLater();
}
}
@@ -312,14 +318,15 @@ void HttpServer::discardClient()
/* TRANSLATOR Gui::StdCmdPythonHelp */
StdCmdPythonHelp::StdCmdPythonHelp()
: Command("Std_PythonHelp"), server(nullptr)
: Command("Std_PythonHelp")
, server(nullptr)
{
sGroup = "Tools";
sMenuText = QT_TR_NOOP("Automatic Python modules documentation");
sToolTipText = QT_TR_NOOP("Opens a browser to show the Python modules documentation");
sWhatsThis = "Std_PythonHelp";
sStatusTip = QT_TR_NOOP("Opens a browser to show the Python modules documentation");
sPixmap = "applications-python";
sGroup = "Tools";
sMenuText = QT_TR_NOOP("Automatic Python modules documentation");
sToolTipText = QT_TR_NOOP("Opens a browser to show the Python modules documentation");
sWhatsThis = "Std_PythonHelp";
sStatusTip = QT_TR_NOOP("Opens a browser to show the Python modules documentation");
sPixmap = "applications-python";
}
StdCmdPythonHelp::~StdCmdPythonHelp()
@@ -340,19 +347,22 @@ void StdCmdPythonHelp::activated(int iMsg)
}
// if server is not yet running try to open one
if (this->server->isListening() ||
this->server->listen(QHostAddress(QHostAddress::LocalHost), port)) {
if (this->server->isListening()
|| this->server->listen(QHostAddress(QHostAddress::LocalHost), port)) {
std::string url = "http://localhost:";
url += std::to_string(port);
OpenURLInBrowser(url.c_str());
}
else {
QMessageBox::critical(Gui::getMainWindow(), QObject::tr("No Server"),
QObject::tr("Unable to start the server to port %1: %2.").arg(port).arg(server->errorString()));
QMessageBox::critical(Gui::getMainWindow(),
QObject::tr("No Server"),
QObject::tr("Unable to start the server to port %1: %2.")
.arg(port)
.arg(server->errorString()));
}
}
bool Gui::OpenURLInBrowser(const char * URL)
bool Gui::OpenURLInBrowser(const char* URL)
{
// The webbrowser Python module allows to start the system browser in an OS-independent way
Base::PyGILStateLocker lock;
@@ -368,12 +378,12 @@ bool Gui::OpenURLInBrowser(const char * URL)
}
catch (Py::Exception& e) {
e.clear();
QMessageBox::critical(Gui::getMainWindow(), QObject::tr("No Browser"),
QObject::tr("Unable to open your system browser."));
QMessageBox::critical(Gui::getMainWindow(),
QObject::tr("No Browser"),
QObject::tr("Unable to open your system browser."));
return false;
}
}
#include "moc_OnlineDocumentation.cpp"

View File

@@ -23,7 +23,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QFontDatabase>
#include <QFontDatabase>
#endif
#include <App/Color.h>
@@ -37,14 +37,16 @@
using namespace Gui;
using namespace Gui::Dialog;
namespace Gui {
namespace Dialog {
namespace Gui
{
namespace Dialog
{
struct DlgSettingsEditorP
{
QVector<QPair<QString, unsigned int> > colormap; // Color map
QVector<QPair<QString, unsigned int>> colormap; // Color map
};
} // namespace Dialog
} // namespace Gui
} // namespace Dialog
} // namespace Gui
namespace
{
@@ -58,20 +60,24 @@ namespace
QFont getMonospaceFont()
{
QFont font(QString::fromLatin1("monospace"));
if (font.fixedPitch())
if (font.fixedPitch()) {
return font;
}
font.setStyleHint(QFont::Monospace);
if (font.fixedPitch())
if (font.fixedPitch()) {
return font;
}
font.setStyleHint(QFont::TypeWriter);
if (font.fixedPitch())
if (font.fixedPitch()) {
return font;
}
font.setFamily(QString::fromLatin1("courier"));
if (font.fixedPitch())
if (font.fixedPitch()) {
return font;
return font; // We failed, but return whatever we have anyway
}
}
return font; // We failed, but return whatever we have anyway
}
} // namespace
/* TRANSLATOR Gui::Dialog::DlgSettingsEditor */
@@ -82,12 +88,12 @@ QFont getMonospaceFont()
* The dialog will by default be modeless, unless you set 'modal' to
* true to construct a modal dialog.
*/
DlgSettingsEditor::DlgSettingsEditor( QWidget* parent )
: PreferencePage( parent )
, ui(new Ui_DlgSettingsEditor)
DlgSettingsEditor::DlgSettingsEditor(QWidget* parent)
: PreferencePage(parent)
, ui(new Ui_DlgSettingsEditor)
{
ui->setupUi(this);
ui->EnableFolding->hide(); // Switch off until we have an editor with folding
ui->EnableFolding->hide(); // Switch off until we have an editor with folding
setupConnections();
@@ -101,70 +107,71 @@ DlgSettingsEditor::DlgSettingsEditor( QWidget* parent )
QColor col;
col = qApp->palette().windowText().color();
unsigned int lText = App::Color::asPackedRGB<QColor>(col);
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Text")), lText));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Text")), lText));
unsigned int lBookmarks = App::Color::asPackedRGB<QColor>(QColor(Qt::cyan));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Bookmark")), lBookmarks));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Bookmark")), lBookmarks));
unsigned int lBreakpnts = App::Color::asPackedRGB<QColor>(QColor(Qt::red));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Breakpoint")), lBreakpnts));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Breakpoint")), lBreakpnts));
unsigned int lKeywords = App::Color::asPackedRGB<QColor>(QColor(Qt::blue));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Keyword")), lKeywords));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Keyword")), lKeywords));
unsigned int lComments = App::Color::asPackedRGB<QColor>(QColor(0, 170, 0));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Comment")), lComments));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Comment")), lComments));
unsigned int lBlockCom = App::Color::asPackedRGB<QColor>(QColor(160, 160, 164));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Block comment")), lBlockCom));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Block comment")), lBlockCom));
unsigned int lNumbers = App::Color::asPackedRGB<QColor>(QColor(Qt::blue));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Number")), lNumbers));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Number")), lNumbers));
unsigned int lStrings = App::Color::asPackedRGB<QColor>(QColor(Qt::red));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("String")), lStrings));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("String")), lStrings));
unsigned int lCharacter = App::Color::asPackedRGB<QColor>(QColor(Qt::red));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Character")), lCharacter));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Character")), lCharacter));
unsigned int lClass = App::Color::asPackedRGB<QColor>(QColor(255, 170, 0));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Class name")), lClass));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Class name")), lClass));
unsigned int lDefine = App::Color::asPackedRGB<QColor>(QColor(255, 170, 0));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Define name")), lDefine));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Define name")), lDefine));
unsigned int lOperat = App::Color::asPackedRGB<QColor>(QColor(160, 160, 164));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Operator")), lOperat));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Operator")), lOperat));
unsigned int lPyOutput = App::Color::asPackedRGB<QColor>(QColor(170, 170, 127));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Python output")), lPyOutput));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Python output")), lPyOutput));
unsigned int lPyError = App::Color::asPackedRGB<QColor>(QColor(Qt::red));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Python error")), lPyError));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Python error")), lPyError));
unsigned int lCLine = App::Color::asPackedRGB<QColor>(QColor(224, 224, 224));
d->colormap.push_back(QPair<QString, unsigned int>
(QString::fromLatin1(QT_TR_NOOP("Current line highlight")), lCLine));
d->colormap.push_back(
QPair<QString, unsigned int>(QString::fromLatin1(QT_TR_NOOP("Current line highlight")),
lCLine));
QStringList labels; labels << tr("Items");
QStringList labels;
labels << tr("Items");
ui->displayItems->setHeaderLabels(labels);
ui->displayItems->header()->hide();
for (const auto &[textType, textColor]: d->colormap)
{
for (const auto& [textType, textColor] : d->colormap) {
auto item = new QTreeWidgetItem(ui->displayItems);
item->setText(0, tr(textType.toLatin1()));
}
@@ -182,6 +189,7 @@ DlgSettingsEditor::~DlgSettingsEditor()
void DlgSettingsEditor::setupConnections()
{
// clang-format off
connect(ui->displayItems, &QTreeWidget::currentItemChanged,
this, &DlgSettingsEditor::onDisplayItemsCurrentItemChanged);
connect(ui->colorButton, &ColorButton::changed,
@@ -197,13 +205,14 @@ void DlgSettingsEditor::setupConnections()
connect(ui->fontSize, &PrefSpinBox::textChanged,
this, &DlgSettingsEditor::onFontSizeValueChanged);
#endif
// clang-format on
}
/** Searches for the color value corresponding to \e name in current editor
* settings ColorMap and assigns it to the color button
* @see Gui::ColorButton
*/
void DlgSettingsEditor::onDisplayItemsCurrentItemChanged(QTreeWidgetItem *item)
void DlgSettingsEditor::onDisplayItemsCurrentItemChanged(QTreeWidgetItem* item)
{
int index = ui->displayItems->indexOfTopLevelItem(item);
unsigned int col = d->colormap[index].second;
@@ -218,7 +227,7 @@ void DlgSettingsEditor::onColorButtonChanged()
int index = ui->displayItems->indexOfTopLevelItem(ui->displayItems->currentItem());
d->colormap[index].second = lcol;
pythonSyntax->setColor( d->colormap[index].first, col );
pythonSyntax->setColor(d->colormap[index].first, col);
}
void DlgSettingsEditor::setEditorTabWidth(int tabWidth)
@@ -244,13 +253,12 @@ void DlgSettingsEditor::saveSettings()
// Saves the color map
ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor");
for (const auto &[textType, textColor] : d->colormap)
{
for (const auto& [textType, textColor] : d->colormap) {
auto col = static_cast<unsigned long>(textColor);
hGrp->SetUnsigned(textType.toLatin1(), col);
}
hGrp->SetInt( "FontSize", ui->fontSize->value() );
hGrp->SetASCII( "Font", ui->fontFamily->currentText().toLatin1() );
hGrp->SetInt("FontSize", ui->fontSize->value());
hGrp->SetASCII("Font", ui->fontFamily->currentText().toLatin1());
setEditorTabWidth(ui->tabSize->value());
}
@@ -281,8 +289,7 @@ void DlgSettingsEditor::loadSettings()
// Restores the color map
ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor");
for (auto &[textType, textColor] : d->colormap)
{
for (auto& [textType, textColor] : d->colormap) {
auto col = static_cast<unsigned long>(textColor);
col = hGrp->GetUnsigned(textType.toLatin1(), col);
textColor = static_cast<unsigned int>(col);
@@ -300,7 +307,7 @@ void DlgSettingsEditor::loadSettings()
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QStringList familyNames = QFontDatabase().families(QFontDatabase::Any);
QStringList fixedFamilyNames;
for (const auto &name : familyNames) {
for (const auto& name : familyNames) {
if (QFontDatabase().isFixedPitch(name)) {
if (name.compare(QLatin1String("8514oem"), Qt::CaseInsensitive) != 0) {
fixedFamilyNames.append(name);
@@ -310,7 +317,7 @@ void DlgSettingsEditor::loadSettings()
#else
QStringList familyNames = QFontDatabase::families(QFontDatabase::Any);
QStringList fixedFamilyNames;
for (const auto &name : familyNames) {
for (const auto& name : familyNames) {
if (QFontDatabase::isFixedPitch(name)) {
if (name.compare(QLatin1String("8514oem"), Qt::CaseInsensitive) != 0) {
fixedFamilyNames.append(name);
@@ -321,8 +328,9 @@ void DlgSettingsEditor::loadSettings()
ui->fontFamily->addItems(fixedFamilyNames);
int index = fixedFamilyNames.indexOf(
QString::fromLatin1(hGrp->GetASCII("Font", defaultMonospaceFont).c_str()));
if (index < 0)
if (index < 0) {
index = 0;
}
ui->fontFamily->setCurrentIndex(index);
onFontFamilyActivated(ui->fontFamily->currentText());
ui->displayItems->setCurrentItem(ui->displayItems->topLevelItem(0));
@@ -332,31 +340,32 @@ void DlgSettingsEditor::resetSettingsToDefaults()
{
ParameterGrp::handle hGrp;
hGrp = WindowParameter::getDefaultParameter()->GetGroup("Editor");
//reset the parameters in the "Editor" group
for (const auto &[textType, textColor] : d->colormap)
{
// reset the parameters in the "Editor" group
for (const auto& [textType, textColor] : d->colormap) {
hGrp->RemoveUnsigned(textType.toLatin1());
}
//reset "FontSize" parameter
// reset "FontSize" parameter
hGrp->RemoveInt("FontSize");
//reset "Font" parameter
// reset "Font" parameter
hGrp->RemoveASCII("Font");
//finally reset all the parameters associated to Gui::Pref* widgets
// finally reset all the parameters associated to Gui::Pref* widgets
PreferencePage::resetSettingsToDefaults();
}
/**
* Sets the strings of the subwidgets using the current language.
*/
void DlgSettingsEditor::changeEvent(QEvent *e)
void DlgSettingsEditor::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
int index = 0;
for (const auto &[textType, textColor]: d->colormap)
for (const auto& [textType, textColor] : d->colormap) {
ui->displayItems->topLevelItem(index++)->setText(0, tr(textType.toLatin1()));
}
ui->retranslateUi(this);
} else {
}
else {
QWidget::changeEvent(e);
}
}

View File

@@ -22,7 +22,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QPushButton>
#include <QPushButton>
#endif
#include "DlgSettingsViewColor.h"
@@ -41,6 +41,7 @@ DlgSettingsViewColor::DlgSettingsViewColor(QWidget* parent)
: PreferencePage(parent)
, ui(new Ui_DlgSettingsViewColor)
{
// clang-format off
ui->setupUi(this);
connect(ui->SwitchGradientColors, &QPushButton::pressed, this,
&DlgSettingsViewColor::onSwitchGradientColorsPressed);
@@ -56,6 +57,7 @@ DlgSettingsViewColor::DlgSettingsViewColor(QWidget* parent)
connect(ui->checkMidColor, &QCheckBox::toggled, this,
&DlgSettingsViewColor::onCheckMidColorToggled);
// clang-format on
}
/**
@@ -93,19 +95,22 @@ void DlgSettingsViewColor::loadSettings()
ui->TreeActiveColor->onRestore();
ui->CbLabelColor->onRestore();
ui->CbLabelTextSize->onRestore();
if (ui->radioButtonSimple->isChecked())
if (ui->radioButtonSimple->isChecked()) {
onRadioButtonSimpleToggled(true);
else if(ui->radioButtonGradient->isChecked())
}
else if (ui->radioButtonGradient->isChecked()) {
onRadioButtonGradientToggled(true);
else
}
else {
onRadioButtonRadialGradientToggled(true);
}
}
/**
* Sets the strings of the subwidgets using the current language.
*/
void DlgSettingsViewColor::changeEvent(QEvent *e)
void DlgSettingsViewColor::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
@@ -161,8 +166,9 @@ void DlgSettingsViewColor::setGradientColorVisibility(bool val)
ui->checkMidColor->setVisible(val);
ui->SwitchGradientColors->setVisible(val);
if (val)
if (val) {
onCheckMidColorToggled(ui->checkMidColor->isChecked());
}
}
#include "moc_DlgSettingsViewColor.cpp"

View File

@@ -22,15 +22,15 @@
#include "PreCompiled.h"
#ifndef _PreComp_
#include <QCheckBox>
# include <QLabel>
# include <QLineEdit>
# include <QListWidget>
# include <QListWidgetItem>
# include <QMenu>
# include <QTextStream>
# include <QToolButton>
# include <QVBoxLayout>
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMenu>
#include <QTextStream>
#include <QToolButton>
#include <QVBoxLayout>
#endif
#include <App/ComplexGeoData.h>
@@ -52,11 +52,13 @@ using namespace Gui::DockWnd;
/* TRANSLATOR Gui::DockWnd::SelectionView */
SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent)
: DockWindow(pcDocument,parent)
, SelectionObserver(true, ResolveMode::NoResolve)
, x(0.0f), y(0.0f), z(0.0f)
, openedAutomatically(false)
SelectionView::SelectionView(Gui::Document* pcDocument, QWidget* parent)
: DockWindow(pcDocument, parent)
, SelectionObserver(true, ResolveMode::NoResolve)
, x(0.0f)
, y(0.0f)
, z(0.0f)
, openedAutomatically(false)
{
setWindowTitle(tr("Selection View"));
@@ -80,13 +82,13 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent)
countLabel->setText(QString::fromUtf8("0"));
countLabel->setToolTip(tr("The number of selected items"));
hLayout->addWidget(searchBox);
hLayout->addWidget(clearButton,0,Qt::AlignRight);
hLayout->addWidget(countLabel,0,Qt::AlignRight);
hLayout->addWidget(clearButton, 0, Qt::AlignRight);
hLayout->addWidget(countLabel, 0, Qt::AlignRight);
vLayout->addLayout(hLayout);
selectionView = new QListWidget(this);
selectionView->setContextMenuPolicy(Qt::CustomContextMenu);
vLayout->addWidget( selectionView );
vLayout->addWidget(selectionView);
enablePickList = new QCheckBox(this);
enablePickList->setText(tr("Picked object list"));
@@ -95,11 +97,12 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent)
pickList->setVisible(false);
vLayout->addWidget(pickList);
selectionView->setMouseTracking(true); // needed for itemEntered() to work
selectionView->setMouseTracking(true); // needed for itemEntered() to work
pickList->setMouseTracking(true);
resize(200, 200);
// clang-format off
connect(clearButton, &QToolButton::clicked, searchBox, &QLineEdit::clear);
connect(searchBox, &QLineEdit::textChanged, this, &SelectionView::search);
connect(searchBox, &QLineEdit::editingFinished, this, &SelectionView::validateSearch);
@@ -109,11 +112,12 @@ SelectionView::SelectionView(Gui::Document* pcDocument, QWidget *parent)
connect(pickList, &QListWidget::itemEntered, this, &SelectionView::preselect);
connect(selectionView, &QListWidget::customContextMenuRequested, this, &SelectionView::onItemContextMenu);
connect(enablePickList, &QCheckBox::stateChanged, this, &SelectionView::onEnablePickList);
// clang-format on
}
SelectionView::~SelectionView() = default;
void SelectionView::leaveEvent(QEvent *)
void SelectionView::leaveEvent(QEvent*)
{
Selection().rmvPreselect();
}
@@ -279,7 +283,7 @@ void SelectionView::search(const QString& text)
selectionView->clear();
for (auto it : objects) {
QString label = QString::fromUtf8(it->Label.getValue());
if (label.contains(text,Qt::CaseInsensitive)) {
if (label.contains(text, Qt::CaseInsensitive)) {
searchList.push_back(it);
// save as user data
QString selObject;
@@ -310,7 +314,7 @@ void SelectionView::validateSearch()
if (doc) {
Gui::Selection().clearSelection();
for (auto it : searchList) {
Gui::Selection().addSelection(doc->getName(),it->getNameInDocument(),nullptr);
Gui::Selection().addSelection(doc->getName(), it->getNameInDocument(), nullptr);
}
}
}
@@ -318,110 +322,141 @@ void SelectionView::validateSearch()
void SelectionView::select(QListWidgetItem* item)
{
if (!item)
if (!item) {
item = selectionView->currentItem();
if (!item)
}
if (!item) {
return;
}
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.size() < 2)
if (elements.size() < 2) {
return;
}
try {
//Gui::Selection().clearSelection();
Gui::Command::runCommand(Gui::Command::Gui,"Gui.Selection.clearSelection()");
//Gui::Selection().addSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
QString cmd = QString::fromLatin1(R"(Gui.Selection.addSelection(App.getDocument("%1").getObject("%2")))").arg(elements[0],elements[1]);
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
}catch(Base::Exception &e) {
// Gui::Selection().clearSelection();
Gui::Command::runCommand(Gui::Command::Gui, "Gui.Selection.clearSelection()");
// Gui::Selection().addSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
QString cmd = QString::fromLatin1(
R"(Gui.Selection.addSelection(App.getDocument("%1").getObject("%2")))")
.arg(elements[0], elements[1]);
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
void SelectionView::deselect()
{
QListWidgetItem *item = selectionView->currentItem();
if (!item)
QListWidgetItem* item = selectionView->currentItem();
if (!item) {
return;
}
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.size() < 2)
if (elements.size() < 2) {
return;
}
//Gui::Selection().rmvSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
QString cmd = QString::fromLatin1(R"(Gui.Selection.removeSelection(App.getDocument("%1").getObject("%2")))").arg(elements[0],elements[1]);
// Gui::Selection().rmvSelection(elements[0].toLatin1(),elements[1].toLatin1(),0);
QString cmd = QString::fromLatin1(
R"(Gui.Selection.removeSelection(App.getDocument("%1").getObject("%2")))")
.arg(elements[0], elements[1]);
try {
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
void SelectionView::toggleSelect(QListWidgetItem* item)
{
if (!item)
if (!item) {
return;
}
std::string name = item->text().toLatin1().constData();
char *docname = &name.at(0);
char *objname = std::strchr(docname,'#');
if(!objname)
char* docname = &name.at(0);
char* objname = std::strchr(docname, '#');
if (!objname) {
return;
}
*objname++ = 0;
char *subname = std::strchr(objname,'.');
if(subname) {
char* subname = std::strchr(objname, '.');
if (subname) {
*subname++ = 0;
char *end = std::strchr(subname,' ');
if(end) *end = 0;
}else {
char *end = std::strchr(objname,' ');
if(end) *end = 0;
char* end = std::strchr(subname, ' ');
if (end) {
*end = 0;
}
}
else {
char* end = std::strchr(objname, ' ');
if (end) {
*end = 0;
}
}
QString cmd;
if(Gui::Selection().isSelected(docname,objname,subname))
if (Gui::Selection().isSelected(docname, objname, subname)) {
cmd = QString::fromLatin1("Gui.Selection.removeSelection("
"App.getDocument('%1').getObject('%2'),'%3')")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname));
else
"App.getDocument('%1').getObject('%2'),'%3')")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname));
}
else {
cmd = QString::fromLatin1("Gui.Selection.addSelection("
"App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname))
.arg(x).arg(y).arg(z);
"App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname))
.arg(x)
.arg(y)
.arg(z);
}
try {
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
void SelectionView::preselect(QListWidgetItem* item)
{
if (!item)
if (!item) {
return;
}
std::string name = item->text().toLatin1().constData();
char *docname = &name.at(0);
char *objname = std::strchr(docname,'#');
if(!objname)
char* docname = &name.at(0);
char* objname = std::strchr(docname, '#');
if (!objname) {
return;
}
*objname++ = 0;
char *subname = std::strchr(objname,'.');
if(subname) {
char* subname = std::strchr(objname, '.');
if (subname) {
*subname++ = 0;
char *end = std::strchr(subname,' ');
if(end) *end = 0;
}else {
char *end = std::strchr(objname,' ');
if(end) *end = 0;
char* end = std::strchr(subname, ' ');
if (end) {
*end = 0;
}
}
else {
char* end = std::strchr(objname, ' ');
if (end) {
*end = 0;
}
}
QString cmd = QString::fromLatin1("Gui.Selection.setPreselection("
"App.getDocument('%1').getObject('%2'),'%3',tp=2)")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname));
"App.getDocument('%1').getObject('%2'),'%3',tp=2)")
.arg(QString::fromLatin1(docname),
QString::fromLatin1(objname),
QString::fromLatin1(subname));
try {
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
@@ -430,8 +465,9 @@ void SelectionView::zoom()
{
select();
try {
Gui::Command::runCommand(Gui::Command::Gui,"Gui.SendMsgToActiveView(\"ViewSelection\")");
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Gui, "Gui.SendMsgToActiveView(\"ViewSelection\")");
}
catch (Base::Exception& e) {
e.ReportException();
}
}
@@ -440,53 +476,61 @@ void SelectionView::treeSelect()
{
select();
try {
Gui::Command::runCommand(Gui::Command::Gui,"Gui.runCommand(\"Std_TreeSelection\")");
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand(\"Std_TreeSelection\")");
}
catch (Base::Exception& e) {
e.ReportException();
}
}
void SelectionView::touch()
{
QListWidgetItem *item = selectionView->currentItem();
if (!item)
QListWidgetItem* item = selectionView->currentItem();
if (!item) {
return;
}
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.size() < 2)
if (elements.size() < 2) {
return;
QString cmd = QString::fromLatin1(R"(App.getDocument("%1").getObject("%2").touch())").arg(elements[0],elements[1]);
}
QString cmd = QString::fromLatin1(R"(App.getDocument("%1").getObject("%2").touch())")
.arg(elements[0], elements[1]);
try {
Gui::Command::runCommand(Gui::Command::Doc,cmd.toLatin1());
}catch(Base::Exception &e) {
Gui::Command::runCommand(Gui::Command::Doc, cmd.toLatin1());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
void SelectionView::toPython()
{
QListWidgetItem *item = selectionView->currentItem();
if (!item)
QListWidgetItem* item = selectionView->currentItem();
if (!item) {
return;
}
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.size() < 2)
if (elements.size() < 2) {
return;
}
try {
QString cmd = QString::fromLatin1(R"(obj = App.getDocument("%1").getObject("%2"))").arg(elements[0], elements[1]);
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
QString cmd = QString::fromLatin1(R"(obj = App.getDocument("%1").getObject("%2"))")
.arg(elements[0], elements[1]);
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
if (elements.length() > 2) {
App::Document* doc = App::GetApplication().getDocument(elements[0].toLatin1());
App::DocumentObject* obj = doc->getObject(elements[1].toLatin1());
QString property = getProperty(obj);
cmd = QString::fromLatin1(R"(shp = App.getDocument("%1").getObject("%2").%3)")
.arg(elements[0], elements[1], property);
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
.arg(elements[0], elements[1], property);
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
if (supportPart(obj, elements[2])) {
cmd = QString::fromLatin1(R"(elt = App.getDocument("%1").getObject("%2").%3.%4)")
.arg(elements[0], elements[1], property, elements[2]);
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
.arg(elements[0], elements[1], property, elements[2]);
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
}
}
@@ -497,9 +541,10 @@ void SelectionView::toPython()
void SelectionView::showPart()
{
QListWidgetItem *item = selectionView->currentItem();
if (!item)
QListWidgetItem* item = selectionView->currentItem();
if (!item) {
return;
}
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.length() > 2) {
App::Document* doc = App::GetApplication().getDocument(elements[0].toLatin1());
@@ -509,9 +554,10 @@ void SelectionView::showPart()
if (!module.isEmpty() && !property.isEmpty() && supportPart(obj, elements[2])) {
try {
Gui::Command::addModule(Gui::Command::Gui, module.toLatin1());
QString cmd = QString::fromLatin1(R"(%1.show(App.getDocument("%2").getObject("%3").%4.%5))")
QString cmd =
QString::fromLatin1(R"(%1.show(App.getDocument("%2").getObject("%3").%4.%5))")
.arg(module, elements[0], elements[1], property, elements[2]);
Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1());
Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1());
}
catch (const Base::Exception& e) {
e.ReportException();
@@ -532,12 +578,15 @@ QString SelectionView::getModule(const char* type) const
std::string::size_type pos = temp.find_first_of("::");
std::string module;
if (pos != std::string::npos)
module = std::string(temp,0,pos);
if (module != "App")
if (pos != std::string::npos) {
module = std::string(temp, 0, pos);
}
if (module != "App") {
prefix = module;
else
}
else {
break;
}
typeId = typeId.getParent();
}
@@ -568,8 +617,9 @@ bool SelectionView::supportPart(App::DocumentObject* obj, const QString& part) c
const Data::ComplexGeoData* geometry = data->getComplexData();
std::vector<const char*> types = geometry->getElementTypes();
for (auto it : types) {
if (part.startsWith(QString::fromLatin1(it)))
if (part.startsWith(QString::fromLatin1(it))) {
return true;
}
}
}
}
@@ -579,39 +629,43 @@ bool SelectionView::supportPart(App::DocumentObject* obj, const QString& part) c
void SelectionView::onItemContextMenu(const QPoint& point)
{
QListWidgetItem *item = selectionView->itemAt(point);
if (!item)
QListWidgetItem* item = selectionView->itemAt(point);
if (!item) {
return;
}
QMenu menu;
QAction *selectAction = menu.addAction(tr("Select only"), this, [&]{
QAction* selectAction = menu.addAction(tr("Select only"), this, [&] {
this->select(nullptr);
});
selectAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-select")));
selectAction->setToolTip(tr("Selects only this object"));
QAction *deselectAction = menu.addAction(tr("Deselect"), this, &SelectionView::deselect);
QAction* deselectAction = menu.addAction(tr("Deselect"), this, &SelectionView::deselect);
deselectAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-unselectable")));
deselectAction->setToolTip(tr("Deselects this object"));
QAction *zoomAction = menu.addAction(tr("Zoom fit"), this, &SelectionView::zoom);
QAction* zoomAction = menu.addAction(tr("Zoom fit"), this, &SelectionView::zoom);
zoomAction->setIcon(QIcon::fromTheme(QString::fromLatin1("zoom-fit-best")));
zoomAction->setToolTip(tr("Selects and fits this object in the 3D window"));
QAction *gotoAction = menu.addAction(tr("Go to selection"), this, &SelectionView::treeSelect);
QAction* gotoAction = menu.addAction(tr("Go to selection"), this, &SelectionView::treeSelect);
gotoAction->setToolTip(tr("Selects and locates this object in the tree view"));
QAction *touchAction = menu.addAction(tr("Mark to recompute"), this, &SelectionView::touch);
QAction* touchAction = menu.addAction(tr("Mark to recompute"), this, &SelectionView::touch);
touchAction->setIcon(QIcon::fromTheme(QString::fromLatin1("view-refresh")));
touchAction->setToolTip(tr("Mark this object to be recomputed"));
QAction *toPythonAction = menu.addAction(tr("To python console"), this, &SelectionView::toPython);
QAction* toPythonAction =
menu.addAction(tr("To python console"), this, &SelectionView::toPython);
toPythonAction->setIcon(QIcon::fromTheme(QString::fromLatin1("applications-python")));
toPythonAction->setToolTip(tr("Reveals this object and its subelements in the python console."));
toPythonAction->setToolTip(
tr("Reveals this object and its subelements in the python console."));
QStringList elements = item->data(Qt::UserRole).toStringList();
if (elements.length() > 2) {
// subshape-specific entries
QAction *showPart = menu.addAction(tr("Duplicate subshape"), this, &SelectionView::showPart);
QAction* showPart =
menu.addAction(tr("Duplicate subshape"), this, &SelectionView::showPart);
showPart->setIcon(QIcon(QString::fromLatin1(":/icons/ClassBrowser/member.svg")));
showPart->setToolTip(tr("Creates a standalone copy of this subshape in the document"));
}
@@ -619,24 +673,26 @@ void SelectionView::onItemContextMenu(const QPoint& point)
}
void SelectionView::onUpdate()
{
}
{}
bool SelectionView::onMsg(const char* /*pMsg*/,const char** /*ppReturn*/)
bool SelectionView::onMsg(const char* /*pMsg*/, const char** /*ppReturn*/)
{
return false;
}
void SelectionView::hideEvent(QHideEvent *ev) {
void SelectionView::hideEvent(QHideEvent* ev)
{
DockWindow::hideEvent(ev);
}
void SelectionView::showEvent(QShowEvent *ev) {
void SelectionView::showEvent(QShowEvent* ev)
{
enablePickList->setChecked(Selection().needPickedList());
Gui::DockWindow::showEvent(ev);
}
void SelectionView::onEnablePickList() {
void SelectionView::onEnablePickList()
{
bool enabled = enablePickList->isChecked();
Selection().enablePickedList(enabled);
pickList->setVisible(enabled);

View File

@@ -39,8 +39,8 @@ namespace sp = std::placeholders;
/* TRANSLATOR Gui::TaskView::TaskAppearance */
TaskAppearance::TaskAppearance(QWidget *parent)
: TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Appearance"),true, parent)
TaskAppearance::TaskAppearance(QWidget* parent)
: TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Appearance"), true, parent)
{
// we need a separate container widget to add all controls to
proxy = new QWidget(this);
@@ -55,11 +55,10 @@ TaskAppearance::TaskAppearance(QWidget *parent)
this->groupLayout()->addWidget(proxy);
Gui::Selection().Attach(this);
//NOLINTBEGIN
this->connectChangedObject =
Gui::Application::Instance->signalChangedObject.connect(std::bind
(&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2));
//NOLINTEND
// NOLINTBEGIN
this->connectChangedObject = Gui::Application::Instance->signalChangedObject.connect(
std::bind(&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2));
// NOLINTEND
}
TaskAppearance::~TaskAppearance()
@@ -71,6 +70,7 @@ TaskAppearance::~TaskAppearance()
void TaskAppearance::setupConnections()
{
// clang-format off
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
connect(ui->changeMode, qOverload<const QString&>(&QComboBox::activated),
this, &TaskAppearance::onChangeModeActivated);
@@ -88,9 +88,10 @@ void TaskAppearance::setupConnections()
this, &TaskAppearance::onPointSizeValueChanged);
connect(ui->spinLineWidth, qOverload<int>(&QSpinBox::valueChanged),
this, &TaskAppearance::onLineWidthValueChanged);
// clang-format on
}
void TaskAppearance::changeEvent(QEvent *e)
void TaskAppearance::changeEvent(QEvent* e)
{
TaskBox::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
@@ -99,14 +100,14 @@ void TaskAppearance::changeEvent(QEvent *e)
}
/// @cond DOXERR
void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType& rCaller,
Gui::SelectionSingleton::MessageType Reason)
{
Q_UNUSED(rCaller);
if (Reason.Type == SelectionChanges::AddSelection ||
Reason.Type == SelectionChanges::RmvSelection ||
Reason.Type == SelectionChanges::SetSelection ||
Reason.Type == SelectionChanges::ClrSelection) {
Q_UNUSED(rCaller);
if (Reason.Type == SelectionChanges::AddSelection
|| Reason.Type == SelectionChanges::RmvSelection
|| Reason.Type == SelectionChanges::SetSelection
|| Reason.Type == SelectionChanges::ClrSelection) {
std::vector<Gui::ViewProvider*> views = getSelection();
setDisplayModes(views);
setPointSize(views);
@@ -116,14 +117,14 @@ void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
}
/// @endcond
void TaskAppearance::slotChangedObject(const Gui::ViewProvider& obj,
const App::Property& prop)
void TaskAppearance::slotChangedObject(const Gui::ViewProvider& obj, const App::Property& prop)
{
// This method gets called if a property of any view provider is changed.
// We pick out all the properties for which we need to update this dialog.
const std::vector<Gui::ViewProvider*> Provider = getSelection();
auto vp = std::find_if
(Provider.begin(), Provider.end(), [&obj](Gui::ViewProvider* v) { return v == &obj; });
auto vp = std::find_if(Provider.begin(), Provider.end(), [&obj](Gui::ViewProvider* v) {
return v == &obj;
});
if (vp != Provider.end()) {
std::string prop_name = obj.getPropertyName(&prop);
@@ -161,7 +162,7 @@ void TaskAppearance::onChangeModeActivated(const QString& s)
{
Gui::WaitCursor wc;
std::vector<Gui::ViewProvider*> Provider = getSelection();
for (const auto & It : Provider) {
for (const auto& It : Provider) {
App::Property* prop = It->getPropertyByName("DisplayMode");
if (prop && prop->is<App::PropertyEnumeration>()) {
auto Display = static_cast<App::PropertyEnumeration*>(prop);
@@ -170,9 +171,9 @@ void TaskAppearance::onChangeModeActivated(const QString& s)
}
}
void TaskAppearance::onChangePlotActivated(const QString&s)
void TaskAppearance::onChangePlotActivated(const QString& s)
{
Base::Console().Log("Plot = %s\n",(const char*)s.toLatin1());
Base::Console().Log("Plot = %s\n", (const char*)s.toLatin1());
}
/**
@@ -181,7 +182,7 @@ void TaskAppearance::onChangePlotActivated(const QString&s)
void TaskAppearance::onTransparencyValueChanged(int transparency)
{
std::vector<Gui::ViewProvider*> Provider = getSelection();
for (const auto & It : Provider) {
for (const auto& It : Provider) {
App::Property* prop = It->getPropertyByName("Transparency");
if (prop && prop->isDerivedFrom<App::PropertyInteger>()) {
auto Transparency = static_cast<App::PropertyInteger*>(prop);
@@ -196,7 +197,7 @@ void TaskAppearance::onTransparencyValueChanged(int transparency)
void TaskAppearance::onPointSizeValueChanged(int pointsize)
{
std::vector<Gui::ViewProvider*> Provider = getSelection();
for (const auto & It : Provider) {
for (const auto& It : Provider) {
App::Property* prop = It->getPropertyByName("PointSize");
if (prop && prop->isDerivedFrom<App::PropertyFloat>()) {
auto PointSize = static_cast<App::PropertyFloat*>(prop);
@@ -211,7 +212,7 @@ void TaskAppearance::onPointSizeValueChanged(int pointsize)
void TaskAppearance::onLineWidthValueChanged(int linewidth)
{
std::vector<Gui::ViewProvider*> Provider = getSelection();
for (const auto & It : Provider) {
for (const auto& It : Provider) {
App::Property* prop = It->getPropertyByName("LineWidth");
if (prop && prop->isDerivedFrom<App::PropertyFloat>()) {
auto LineWidth = static_cast<App::PropertyFloat*>(prop);
@@ -227,17 +228,20 @@ void TaskAppearance::setDisplayModes(const std::vector<Gui::ViewProvider*>& view
App::Property* prop = (*it)->getPropertyByName("DisplayMode");
if (prop && prop->is<App::PropertyEnumeration>()) {
auto display = static_cast<App::PropertyEnumeration*>(prop);
if (!display->hasEnums())
if (!display->hasEnums()) {
return;
}
std::vector<std::string> value = display->getEnumVector();
if (it == views.begin()) {
for (const auto & jt : value)
for (const auto& jt : value) {
commonModes << QLatin1String(jt.c_str());
}
}
else {
for (const auto & jt : value) {
if (commonModes.contains(QLatin1String(jt.c_str())))
for (const auto& jt : value) {
if (commonModes.contains(QLatin1String(jt.c_str()))) {
modes << QLatin1String(jt.c_str());
}
}
commonModes = modes;
@@ -268,7 +272,7 @@ void TaskAppearance::setDisplayModes(const std::vector<Gui::ViewProvider*>& view
void TaskAppearance::setPointSize(const std::vector<Gui::ViewProvider*>& views)
{
bool pointSize = false;
for (const auto & view : views) {
for (const auto& view : views) {
App::Property* prop = view->getPropertyByName("PointSize");
if (prop && prop->isDerivedFrom<App::PropertyFloat>()) {
bool blocked = ui->spinPointSize->blockSignals(true);
@@ -285,7 +289,7 @@ void TaskAppearance::setPointSize(const std::vector<Gui::ViewProvider*>& views)
void TaskAppearance::setLineWidth(const std::vector<Gui::ViewProvider*>& views)
{
bool lineWidth = false;
for (const auto & view : views) {
for (const auto& view : views) {
App::Property* prop = view->getPropertyByName("LineWidth");
if (prop && prop->isDerivedFrom<App::PropertyFloat>()) {
bool blocked = ui->spinLineWidth->blockSignals(true);
@@ -302,7 +306,7 @@ void TaskAppearance::setLineWidth(const std::vector<Gui::ViewProvider*>& views)
void TaskAppearance::setTransparency(const std::vector<Gui::ViewProvider*>& views)
{
bool transparency = false;
for (const auto & view : views) {
for (const auto& view : views) {
App::Property* prop = view->getPropertyByName("Transparency");
if (prop && prop->isDerivedFrom<App::PropertyInteger>()) {
bool blocked = ui->spinTransparency->blockSignals(true);
@@ -323,9 +327,12 @@ std::vector<Gui::ViewProvider*> TaskAppearance::getSelection() const
// get the complete selection
std::vector<SelectionSingleton::SelObj> sel = Selection().getCompleteSelection();
for (const auto & it : sel) {
Gui::ViewProvider* view = Application::Instance->getDocument(it.pDoc)->getViewProvider(it.pObject);
if (view) views.push_back(view);
for (const auto& it : sel) {
Gui::ViewProvider* view =
Application::Instance->getDocument(it.pDoc)->getViewProvider(it.pObject);
if (view) {
views.push_back(view);
}
}
return views;

View File

@@ -23,16 +23,16 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QDialog>
# include <QPushButton>
# include <QAction>
# include <QKeyEvent>
# include <map>
# include <Inventor/SoPickedPoint.h>
# include <Inventor/events/SoLocation2Event.h>
# include <Inventor/events/SoButtonEvent.h>
# include <Inventor/events/SoMouseButtonEvent.h>
# include <Inventor/events/SoKeyboardEvent.h>
#include <QDialog>
#include <QPushButton>
#include <QAction>
#include <QKeyEvent>
#include <map>
#include <Inventor/SoPickedPoint.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoButtonEvent.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#include <Inventor/events/SoKeyboardEvent.h>
#endif
#include <Base/Console.h>
@@ -59,10 +59,10 @@ using namespace Gui;
/* TRANSLATOR Gui::TaskImage */
TaskImage::TaskImage(Image::ImagePlane* obj, QWidget* parent)
: QWidget(parent)
, ui(new Ui_TaskImage)
, feature(obj)
, aspectRatio(1.0)
: QWidget(parent)
, ui(new Ui_TaskImage)
, feature(obj)
, aspectRatio(1.0)
{
ui->setupUi(this);
ui->groupBoxCalibration->hide();
@@ -87,6 +87,7 @@ TaskImage::~TaskImage()
void TaskImage::connectSignals()
{
// clang-format off
connect(ui->Reverse_checkBox, &QCheckBox::clicked,
this, &TaskImage::onPreview);
connect(ui->XY_radioButton, &QRadioButton::clicked,
@@ -118,6 +119,7 @@ void TaskImage::connectSignals()
this, &TaskImage::acceptScale);
connect(ui->pushButtonCancel, &QPushButton::clicked,
this, &TaskImage::rejectScale);
// clang-format on
}
void TaskImage::initialiseTransparency()
@@ -179,7 +181,7 @@ View3DInventorViewer* TaskImage::getViewer() const
{
if (!feature.expired()) {
auto vp = Application::Instance->getViewProvider(feature.get());
auto doc = static_cast<ViewProviderDocumentObject*>(vp)->getDocument(); // NOLINT
auto doc = static_cast<ViewProviderDocumentObject*>(vp)->getDocument(); // NOLINT
auto view = dynamic_cast<View3DInventor*>(doc->getViewOfViewProvider(vp));
if (view) {
return view->getViewer();
@@ -241,12 +243,9 @@ void TaskImage::onInteractiveScale()
if (viewer) {
auto vp = Application::Instance->getViewProvider(feature.get());
scale = new InteractiveScale(viewer, vp, feature->globalPlacement());
connect(scale, &InteractiveScale::scaleRequired,
this, &TaskImage::acceptScale);
connect(scale, &InteractiveScale::scaleCanceled,
this, &TaskImage::rejectScale);
connect(scale, &InteractiveScale::enableApplyBtn,
this, &TaskImage::enableApplyBtn);
connect(scale, &InteractiveScale::scaleRequired, this, &TaskImage::acceptScale);
connect(scale, &InteractiveScale::scaleCanceled, this, &TaskImage::rejectScale);
connect(scale, &InteractiveScale::enableApplyBtn, this, &TaskImage::enableApplyBtn);
}
}
@@ -289,9 +288,9 @@ void TaskImage::onPreview()
// NOLINTNEXTLINE
void TaskImage::restoreAngles(const Base::Rotation& rot)
{
double yaw{};
double pitch{};
double roll{};
double yaw {};
double pitch {};
double roll {};
rot.getYawPitchRoll(yaw, pitch, roll);
bool reverse = false;
@@ -358,7 +357,7 @@ void TaskImage::restore(const Base::Placement& plm)
ui->spinBoxWidth->setValue(feature->XSize.getValue());
ui->spinBoxHeight->setValue(feature->YSize.getValue());
Base::Rotation rot = plm.getRotation(); // NOLINT
Base::Rotation rot = plm.getRotation(); // NOLINT
Base::Vector3d pos = plm.getPosition();
restoreAngles(rot);
@@ -399,7 +398,9 @@ void TaskImage::updatePlacement()
}
// NOLINTEND
Base::Vector3d offset = Base::Vector3d(ui->spinBoxX->value().getValue(), ui->spinBoxY->value().getValue(), ui->spinBoxZ->value().getValue());
Base::Vector3d offset = Base::Vector3d(ui->spinBoxX->value().getValue(),
ui->spinBoxY->value().getValue(),
ui->spinBoxZ->value().getValue());
offset = rot.multVec(offset);
Pos = Base::Placement(offset, rot);
@@ -426,22 +427,22 @@ void TaskImage::updateIcon()
}
ui->previewLabel->setPixmap(
Gui::BitmapFactory().pixmapFromSvg(icon.c_str(),
ui->previewLabel->size()));
Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size()));
}
// ----------------------------------------------------------------------------
InteractiveScale::InteractiveScale(View3DInventorViewer* view,
ViewProvider* vp,
const Base::Placement& plc) // NOLINT
const Base::Placement& plc) // NOLINT
: active(false)
, placement(plc)
, viewer(view)
, viewProv(vp)
, midPoint(SbVec3f(0,0,0))
, midPoint(SbVec3f(0, 0, 0))
{
measureLabel = new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); //NOLINT
measureLabel =
new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); // NOLINT
}
InteractiveScale::~InteractiveScale()
@@ -453,8 +454,12 @@ void InteractiveScale::activate()
{
if (viewer) {
viewer->setEditing(true);
viewer->addEventCallback(SoLocation2Event::getClassTypeId(), InteractiveScale::getMousePosition, this);
viewer->addEventCallback(SoButtonEvent::getClassTypeId(), InteractiveScale::soEventFilter, this);
viewer->addEventCallback(SoLocation2Event::getClassTypeId(),
InteractiveScale::getMousePosition,
this);
viewer->addEventCallback(SoButtonEvent::getClassTypeId(),
InteractiveScale::soEventFilter,
this);
viewer->setSelectionEnabled(false);
viewer->getWidget()->setCursor(QCursor(Qt::CrossCursor));
active = true;
@@ -467,8 +472,12 @@ void InteractiveScale::deactivate()
points.clear();
measureLabel->deactivate();
viewer->setEditing(false);
viewer->removeEventCallback(SoLocation2Event::getClassTypeId(), InteractiveScale::getMousePosition, this);
viewer->removeEventCallback(SoButtonEvent::getClassTypeId(), InteractiveScale::soEventFilter, this);
viewer->removeEventCallback(SoLocation2Event::getClassTypeId(),
InteractiveScale::getMousePosition,
this);
viewer->removeEventCallback(SoButtonEvent::getClassTypeId(),
InteractiveScale::soEventFilter,
this);
viewer->setSelectionEnabled(true);
viewer->getWidget()->setCursor(QCursor(Qt::ArrowCursor));
active = false;
@@ -499,8 +508,8 @@ void InteractiveScale::setDistance(const SbVec3f& pos3d)
quantity.setValue(getDistance(pos3d));
quantity.setUnit(Base::Unit::Length);
//Update the displayed distance
double factor{};
// Update the displayed distance
double factor {};
QString unitStr;
QString valueStr;
valueStr = quantity.getUserString(factor, unitStr);
@@ -508,10 +517,10 @@ void InteractiveScale::setDistance(const SbVec3f& pos3d)
measureLabel->label->setPoints(getCoordsOnImagePlane(points[0]), getCoordsOnImagePlane(pos3d));
}
void InteractiveScale::findPointOnImagePlane(SoEventCallback * ecb)
void InteractiveScale::findPointOnImagePlane(SoEventCallback* ecb)
{
const SoEvent * mbe = ecb->getEvent();
auto view = static_cast<Gui::View3DInventorViewer*>(ecb->getUserData());
const SoEvent* mbe = ecb->getEvent();
auto view = static_cast<Gui::View3DInventorViewer*>(ecb->getUserData());
std::unique_ptr<SoPickedPoint> pp(view->getPointOnRay(mbe->getPosition(), viewProv));
if (pp) {
auto pos3d = pp->getPoint();
@@ -540,16 +549,17 @@ void InteractiveScale::collectPoint(const SbVec3f& pos3d)
Q_EMIT enableApplyBtn();
}
else {
Base::Console().Warning(std::string("Image scale"), "The second point is too close. Retry!\n");
Base::Console().Warning(std::string("Image scale"),
"The second point is too close. Retry!\n");
}
}
}
void InteractiveScale::getMousePosition(void * ud, SoEventCallback * ecb)
void InteractiveScale::getMousePosition(void* ud, SoEventCallback* ecb)
{
auto scale = static_cast<InteractiveScale*>(ud);
const SoEvent* l2e = ecb->getEvent();
auto view = static_cast<Gui::View3DInventorViewer*>(ecb->getUserData());
auto view = static_cast<Gui::View3DInventorViewer*>(ecb->getUserData());
if (scale->points.size() == 1) {
ecb->setHandled();
@@ -569,7 +579,7 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb)
const SoEvent* soEvent = ecb->getEvent();
if (soEvent->isOfType(SoKeyboardEvent::getClassTypeId())) {
/* If user presses escape, then we cancel the tool.*/
const auto kbe = static_cast<const SoKeyboardEvent*>(soEvent); // NOLINT
const auto kbe = static_cast<const SoKeyboardEvent*>(soEvent); // NOLINT
if (kbe->getKey() == SoKeyboardEvent::ESCAPE && kbe->getState() == SoButtonEvent::UP) {
ecb->setHandled();
@@ -577,15 +587,15 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb)
}
}
else if (soEvent->isOfType(SoMouseButtonEvent::getClassTypeId())) {
const auto mbe = static_cast<const SoMouseButtonEvent*>(soEvent); // NOLINT
const auto mbe = static_cast<const SoMouseButtonEvent*>(soEvent); // NOLINT
if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN)
{
if (mbe->getButton() == SoMouseButtonEvent::BUTTON1
&& mbe->getState() == SoButtonEvent::DOWN) {
ecb->setHandled();
scale->findPointOnImagePlane(ecb);
}
if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::DOWN)
{
if (mbe->getButton() == SoMouseButtonEvent::BUTTON2
&& mbe->getState() == SoButtonEvent::DOWN) {
ecb->setHandled();
Q_EMIT scale->scaleCanceled();
}
@@ -595,15 +605,16 @@ void InteractiveScale::soEventFilter(void* ud, SoEventCallback* ecb)
bool InteractiveScale::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::KeyRelease) {
auto keyEvent = static_cast<QKeyEvent*>(event); // NOLINT
auto keyEvent = static_cast<QKeyEvent*>(event); // NOLINT
/* If user press enter in the spinbox, then we validate the tool.*/
if ((keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return)
&& dynamic_cast<QuantitySpinBox*>(object)) {
&& dynamic_cast<QuantitySpinBox*>(object)) {
Q_EMIT scaleRequired();
}
/* If user press escape, then we cancel the tool. Required here as well for when checkbox has focus.*/
/* If user press escape, then we cancel the tool. Required here as well for when checkbox
* has focus.*/
if (keyEvent->key() == Qt::Key_Escape) {
Q_EMIT scaleCanceled();
}
@@ -640,7 +651,7 @@ SbVec3f InteractiveScale::getCoordsOnImagePlane(const SbVec3f& point)
// ----------------------------------------------------------------------------
TaskImageDialog::TaskImageDialog(Image::ImagePlane* obj)
: widget{new TaskImage(obj)}
: widget {new TaskImage(obj)}
{
addTaskBox(Gui::BitmapFactory().pixmap("image-plane"), widget);

View File

@@ -23,8 +23,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QDialog>
# include <map>
#include <QDialog>
#include <map>
#endif
#include <Base/Tools.h>
@@ -40,18 +40,24 @@
using namespace Gui;
TaskOrientation::TaskOrientation(App::GeoFeature* obj, QWidget* parent)
: QWidget(parent)
, ui(new Ui_TaskOrientation)
, feature(obj)
: QWidget(parent)
, ui(new Ui_TaskOrientation)
, feature(obj)
{
ui->setupUi(this);
connect(ui->Reverse_checkBox, &QCheckBox::clicked, this, &TaskOrientation::onPreview);
connect(ui->XY_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview);
connect(ui->XZ_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview);
connect(ui->YZ_radioButton , &QRadioButton::clicked, this, &TaskOrientation::onPreview);
// clang-format off
connect(ui->Reverse_checkBox, &QCheckBox::clicked,
this, &TaskOrientation::onPreview);
connect(ui->XY_radioButton , &QRadioButton::clicked,
this, &TaskOrientation::onPreview);
connect(ui->XZ_radioButton , &QRadioButton::clicked,
this, &TaskOrientation::onPreview);
connect(ui->YZ_radioButton , &QRadioButton::clicked,
this, &TaskOrientation::onPreview);
connect(ui->Offset_doubleSpinBox, qOverload<double>(&QuantitySpinBox::valueChanged),
this, &TaskOrientation::onPreview);
// clang-format on
}
TaskOrientation::~TaskOrientation() = default;
@@ -92,9 +98,7 @@ void TaskOrientation::onPreview()
void TaskOrientation::restore(const Base::Placement& plm)
{
auto isReversed = [](Camera::Orientation type) {
return (type == Camera::Bottom) ||
(type == Camera::Rear) ||
(type == Camera::Left);
return (type == Camera::Bottom) || (type == Camera::Rear) || (type == Camera::Left);
};
std::map<Camera::Orientation, Base::Rotation> rotations {
{Camera::Top, Camera::convert(Camera::Top)},
@@ -102,8 +106,7 @@ void TaskOrientation::restore(const Base::Placement& plm)
{Camera::Front, Camera::convert(Camera::Front)},
{Camera::Rear, Camera::convert(Camera::Rear)},
{Camera::Right, Camera::convert(Camera::Right)},
{Camera::Left, Camera::convert(Camera::Left)}
};
{Camera::Left, Camera::convert(Camera::Left)}};
Base::Rotation rot = plm.getRotation();
Base::Vector3d pos = plm.getPosition();
@@ -111,18 +114,15 @@ void TaskOrientation::restore(const Base::Placement& plm)
double prec = 1.0e-5;
for (const auto& it : rotations) {
if (rot.isSame(it.second, prec)) {
if (it.first == Camera::Top ||
it.first == Camera::Bottom) {
if (it.first == Camera::Top || it.first == Camera::Bottom) {
ui->XY_radioButton->setChecked(true);
ui->Offset_doubleSpinBox->setValue(pos.z);
}
else if (it.first == Camera::Front ||
it.first == Camera::Rear) {
else if (it.first == Camera::Front || it.first == Camera::Rear) {
ui->XZ_radioButton->setChecked(true);
ui->Offset_doubleSpinBox->setValue(pos.y);
}
else if (it.first == Camera::Right ||
it.first == Camera::Left) {
else if (it.first == Camera::Right || it.first == Camera::Left) {
ui->YZ_radioButton->setChecked(true);
ui->Offset_doubleSpinBox->setValue(pos.x);
}
@@ -143,32 +143,26 @@ void TaskOrientation::updatePlacement()
bool reverse = ui->Reverse_checkBox->isChecked();
if (ui->XY_radioButton->isChecked()) {
if (!reverse) {
Pos = Base::Placement(Base::Vector3d(0, 0, offset),
Camera::convert(Camera::Top));
Pos = Base::Placement(Base::Vector3d(0, 0, offset), Camera::convert(Camera::Top));
}
else {
Pos = Base::Placement(Base::Vector3d(0, 0, offset),
Camera::convert(Camera::Bottom));
Pos = Base::Placement(Base::Vector3d(0, 0, offset), Camera::convert(Camera::Bottom));
}
}
else if (ui->XZ_radioButton->isChecked()) {
if (!reverse) {
Pos = Base::Placement(Base::Vector3d(0, offset, 0),
Camera::convert(Camera::Front));
Pos = Base::Placement(Base::Vector3d(0, offset, 0), Camera::convert(Camera::Front));
}
else {
Pos = Base::Placement(Base::Vector3d(0, offset, 0),
Camera::convert(Camera::Rear));
Pos = Base::Placement(Base::Vector3d(0, offset, 0), Camera::convert(Camera::Rear));
}
}
else if (ui->YZ_radioButton->isChecked()) {
if (!reverse) {
Pos = Base::Placement(Base::Vector3d(offset, 0, 0),
Camera::convert(Camera::Right));
Pos = Base::Placement(Base::Vector3d(offset, 0, 0), Camera::convert(Camera::Right));
}
else {
Pos = Base::Placement(Base::Vector3d(offset, 0, 0),
Camera::convert(Camera::Left));
Pos = Base::Placement(Base::Vector3d(offset, 0, 0), Camera::convert(Camera::Left));
}
}
@@ -192,8 +186,7 @@ void TaskOrientation::updateIcon()
}
ui->previewLabel->setPixmap(
Gui::BitmapFactory().pixmapFromSvg(icon.c_str(),
ui->previewLabel->size()));
Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size()));
}
// ----------------------------------------------------------------------------

View File

@@ -37,8 +37,13 @@ using namespace Gui::TaskView;
/* TRANSLATOR Gui::TaskView::TaskSelectLinkProperty */
TaskSelectLinkProperty::TaskSelectLinkProperty(const char *sFilter,App::Property *prop,QWidget *parent)
: TaskBox(Gui::BitmapFactory().pixmap("mouse_pointer"),tr("edit selection"),true, parent),Filter(nullptr),LinkSub(nullptr),LinkList(nullptr)
TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter,
App::Property* prop,
QWidget* parent)
: TaskBox(Gui::BitmapFactory().pixmap("mouse_pointer"), tr("edit selection"), true, parent)
, Filter(nullptr)
, LinkSub(nullptr)
, LinkList(nullptr)
{
// we need a separate container widget to add all controls to
proxy = new QWidget(this);
@@ -60,18 +65,18 @@ TaskSelectLinkProperty::TaskSelectLinkProperty(const char *sFilter,App::Property
ui->Invert->setDisabled(true);
ui->Help->setDisabled(true);
// property have to be set!
// property have to be set!
assert(prop);
StartObject = nullptr;
if (prop->isDerivedFrom<App::PropertyLinkSub>()) {
LinkSub = dynamic_cast<App::PropertyLinkSub *>(prop);
LinkSub = dynamic_cast<App::PropertyLinkSub*>(prop);
}
else if (prop->isDerivedFrom<App::PropertyLinkList>()) {
LinkList = dynamic_cast<App::PropertyLinkList *>(prop);
LinkList = dynamic_cast<App::PropertyLinkList*>(prop);
}
else {
Base::Console().Warning("Unknown Link property type in "
"Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()");
"Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()");
}
setFilter(sFilter);
@@ -85,6 +90,7 @@ TaskSelectLinkProperty::~TaskSelectLinkProperty()
void TaskSelectLinkProperty::setupConnections()
{
// clang-format off
connect(ui->Remove, &QToolButton::clicked,
this, &TaskSelectLinkProperty::onRemoveClicked);
connect(ui->Add, &QToolButton::clicked,
@@ -93,9 +99,10 @@ void TaskSelectLinkProperty::setupConnections()
this, &TaskSelectLinkProperty::onInvertClicked);
connect(ui->Help, &QToolButton::clicked,
this, &TaskSelectLinkProperty::onHelpClicked);
// clang-format on
}
void TaskSelectLinkProperty::changeEvent(QEvent *e)
void TaskSelectLinkProperty::changeEvent(QEvent* e)
{
TaskBox::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
@@ -106,7 +113,7 @@ void TaskSelectLinkProperty::changeEvent(QEvent *e)
/// @cond DOXERR
bool TaskSelectLinkProperty::setFilter(const char * sFilter)
bool TaskSelectLinkProperty::setFilter(const char* sFilter)
{
Filter = new SelectionFilter(sFilter);
return Filter->isValid();
@@ -117,34 +124,31 @@ void TaskSelectLinkProperty::activate()
{
// first clear the selection
Gui::Selection().clearSelection();
// set the gate for the filter
// set the gate for the filter
Gui::Selection().addSelectionGate(new SelectionFilterGate(Filter));
// In case of LinkSub property
// In case of LinkSub property
if (LinkSub) {
// save the start values for a cnacel operation (reject())
StartValueBuffer = LinkSub->getSubValues();
StartObject = LinkSub->getValue();
if(StartObject) {
StartObject = LinkSub->getValue();
if (StartObject) {
std::string ObjName = StartObject->getNameInDocument();
std::string DocName = StartObject->getDocument()->getName();
for (const auto & it : StartValueBuffer)
{
Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str(),it.c_str());
for (const auto& it : StartValueBuffer) {
Gui::Selection().addSelection(DocName.c_str(), ObjName.c_str(), it.c_str());
}
}
}
// In case of LinkList property
// In case of LinkList property
else if (LinkList) {
// save the start values for a cnacel operation (reject())
const std::vector<App::DocumentObject*> &Values = LinkList->getValues();
for(const auto & Value : Values)
{
const std::vector<App::DocumentObject*>& Values = LinkList->getValues();
for (const auto& Value : Values) {
std::string ObjName = Value->getNameInDocument();
std::string DocName = Value->getDocument()->getName();
Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str());
Gui::Selection().addSelection(DocName.c_str(), ObjName.c_str());
}
}
@@ -164,9 +168,9 @@ bool TaskSelectLinkProperty::accept()
bool TaskSelectLinkProperty::reject()
{
if(LinkSub){
if (LinkSub) {
// restore the old values
LinkSub->setValue(StartObject,StartValueBuffer);
LinkSub->setValue(StartObject, StartValueBuffer);
}
// clear selection and remove gate (return to normal operation)
@@ -180,17 +184,17 @@ void TaskSelectLinkProperty::sendSelection2Property()
if (LinkSub) {
std::vector<Gui::SelectionObject> temp = Gui::Selection().getSelectionEx();
assert(temp.size() >= 1);
LinkSub->setValue(temp[0].getObject(),temp[0].getSubNames());
LinkSub->setValue(temp[0].getObject(), temp[0].getSubNames());
}
else if (LinkList) {
std::vector<Gui::SelectionObject> sel = Gui::Selection().getSelectionEx();
std::vector<App::DocumentObject*> temp;
for (auto & it : sel)
for (auto& it : sel) {
temp.push_back(it.getObject());
}
LinkList->setValues(temp);
}
}
void TaskSelectLinkProperty::checkSelectionStatus()
@@ -198,56 +202,52 @@ void TaskSelectLinkProperty::checkSelectionStatus()
QPalette palette(QApplication::palette());
if (Filter->match()) {
palette.setBrush(QPalette::Base,QColor(200,250,200));
palette.setBrush(QPalette::Base, QColor(200, 250, 200));
Q_EMIT emitSelectionFit();
}
else {
palette.setBrush(QPalette::Base,QColor(250,200,200));
palette.setBrush(QPalette::Base, QColor(250, 200, 200));
Q_EMIT emitSelectionMisfit();
}
//ui->listWidget->setAutoFillBackground(true);
// ui->listWidget->setAutoFillBackground(true);
ui->listWidget->setPalette(palette);
}
void TaskSelectLinkProperty::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
void TaskSelectLinkProperty::OnChange(Gui::SelectionSingleton::SubjectType& rCaller,
Gui::SelectionSingleton::MessageType Reason)
{
Q_UNUSED(rCaller);
if (Reason.Type == SelectionChanges::AddSelection ||
Reason.Type == SelectionChanges::RmvSelection ||
Reason.Type == SelectionChanges::SetSelection ||
Reason.Type == SelectionChanges::ClrSelection) {
ui->listWidget->clear();
std::vector<Gui::SelectionSingleton::SelObj> sel = Gui::Selection().getSelection();
for (const auto & it : sel){
std::string temp;
temp += it.FeatName;
if (strcmp(it.SubName, "") != 0){
temp += "::";
temp += it.SubName;
}
new QListWidgetItem(QString::fromLatin1(temp.c_str()), ui->listWidget);
Q_UNUSED(rCaller);
if (Reason.Type == SelectionChanges::AddSelection
|| Reason.Type == SelectionChanges::RmvSelection
|| Reason.Type == SelectionChanges::SetSelection
|| Reason.Type == SelectionChanges::ClrSelection) {
ui->listWidget->clear();
std::vector<Gui::SelectionSingleton::SelObj> sel = Gui::Selection().getSelection();
for (const auto& it : sel) {
std::string temp;
temp += it.FeatName;
if (strcmp(it.SubName, "") != 0) {
temp += "::";
temp += it.SubName;
}
checkSelectionStatus();
new QListWidgetItem(QString::fromLatin1(temp.c_str()), ui->listWidget);
}
checkSelectionStatus();
}
}
/// @endcond
void TaskSelectLinkProperty::onRemoveClicked(bool)
{
}
{}
void TaskSelectLinkProperty::onAddClicked(bool)
{
}
{}
void TaskSelectLinkProperty::onInvertClicked(bool)
{
}
{}
void TaskSelectLinkProperty::onHelpClicked(bool)
{
}
{}
#include "moc_TaskSelectLinkProperty.cpp"

View File

@@ -24,12 +24,12 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string/predicate.hpp>
# include <QApplication>
# include <QInputDialog>
# include <QHeaderView>
# include <QMenu>
# include <QPainter>
#include <boost/algorithm/string/predicate.hpp>
#include <QApplication>
#include <QInputDialog>
#include <QHeaderView>
#include <QMenu>
#include <QPainter>
#endif
#include <App/Application.h>
@@ -51,7 +51,7 @@ FC_LOG_LEVEL_INIT("PropertyView", true, true)
using namespace Gui::PropertyEditor;
PropertyEditor::PropertyEditor(QWidget *parent)
PropertyEditor::PropertyEditor(QWidget* parent)
: QTreeView(parent)
, autoexpand(false)
, autoupdate(false)
@@ -76,7 +76,7 @@ PropertyEditor::PropertyEditor(QWidget *parent)
setRootIsDecorated(false);
setExpandsOnDoubleClick(true);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QStyleOptionViewItem opt = PropertyEditor::viewOptions();
#else
QStyleOptionViewItem opt;
@@ -85,22 +85,25 @@ PropertyEditor::PropertyEditor(QWidget *parent)
this->background = opt.palette.dark();
this->groupColor = opt.palette.color(QPalette::BrightText);
this->_itemBackground.setColor(QColor(0,0,0,0));
this->_itemBackground.setColor(QColor(0, 0, 0, 0));
this->setSelectionMode(QAbstractItemView::ExtendedSelection);
// clang-format off
connect(this, &QTreeView::activated, this, &PropertyEditor::onItemActivated);
connect(this, &QTreeView::clicked, this, &PropertyEditor::onItemActivated);
connect(this, &QTreeView::expanded, this, &PropertyEditor::onItemExpanded);
connect(this, &QTreeView::collapsed, this, &PropertyEditor::onItemCollapsed);
connect(propertyModel, &QAbstractItemModel::rowsMoved, this, &PropertyEditor::onRowsMoved);
connect(propertyModel, &QAbstractItemModel::rowsRemoved, this, &PropertyEditor::onRowsRemoved);
// clang-format on
setHeaderHidden(true);
viewport()->installEventFilter(this);
viewport()->setMouseTracking(true);
auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DockWindows/PropertyView");
auto hGrp = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/DockWindows/PropertyView");
int firstColumnSize = hGrp->GetInt("FirstColumnSize", 0);
if (firstColumnSize != 0) {
header()->resizeSection(0, firstColumnSize);
@@ -124,15 +127,16 @@ bool PropertyEditor::isAutomaticExpand(bool) const
return autoexpand;
}
void PropertyEditor::onItemExpanded(const QModelIndex &index)
void PropertyEditor::onItemExpanded(const QModelIndex& index)
{
auto item = static_cast<PropertyItem*>(index.internalPointer());
item->setExpanded(true);
for(int i=0, c=item->childCount(); i<c; ++i)
for (int i = 0, c = item->childCount(); i < c; ++i) {
setExpanded(propertyModel->index(i, 0, index), item->child(i)->isExpanded());
}
}
void PropertyEditor::onItemCollapsed(const QModelIndex &index)
void PropertyEditor::onItemCollapsed(const QModelIndex& index)
{
auto item = static_cast<PropertyItem*>(index.internalPointer());
item->setExpanded(false);
@@ -178,7 +182,7 @@ void PropertyEditor::setItemBackground(const QBrush& c)
this->_itemBackground = c;
}
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QStyleOptionViewItem PropertyEditor::viewOptions() const
{
QStyleOptionViewItem option = QTreeView::viewOptions();
@@ -186,7 +190,7 @@ QStyleOptionViewItem PropertyEditor::viewOptions() const
return option;
}
#else
void PropertyEditor::initViewItemOption(QStyleOptionViewItem *option) const
void PropertyEditor::initViewItemOption(QStyleOptionViewItem* option) const
{
QTreeView::initViewItemOption(option);
option->showDecorationSelected = true;
@@ -198,27 +202,26 @@ bool PropertyEditor::event(QEvent* event)
if (event->type() == QEvent::ShortcutOverride) {
auto kevent = static_cast<QKeyEvent*>(event);
Qt::KeyboardModifiers ShiftKeypadModifier = Qt::ShiftModifier | Qt::KeypadModifier;
if (kevent->modifiers() == Qt::NoModifier ||
kevent->modifiers() == Qt::ShiftModifier ||
kevent->modifiers() == Qt::KeypadModifier ||
kevent->modifiers() == ShiftKeypadModifier) {
if (kevent->modifiers() == Qt::NoModifier || kevent->modifiers() == Qt::ShiftModifier
|| kevent->modifiers() == Qt::KeypadModifier
|| kevent->modifiers() == ShiftKeypadModifier) {
switch (kevent->key()) {
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Backspace:
case Qt::Key_Left:
case Qt::Key_Right:
kevent->accept();
default:
break;
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Backspace:
case Qt::Key_Left:
case Qt::Key_Right:
kevent->accept();
default:
break;
}
}
}
return QTreeView::event(event);
}
void PropertyEditor::commitData (QWidget * editor)
void PropertyEditor::commitData(QWidget* editor)
{
committing = true;
QTreeView::commitData(editor);
@@ -229,7 +232,7 @@ void PropertyEditor::commitData (QWidget * editor)
}
}
void PropertyEditor::editorDestroyed (QObject * editor)
void PropertyEditor::editorDestroyed(QObject* editor)
{
QTreeView::editorDestroyed(editor);
@@ -239,10 +242,10 @@ void PropertyEditor::editorDestroyed (QObject * editor)
closeTransaction();
}
void PropertyEditor::currentChanged ( const QModelIndex & current, const QModelIndex & previous )
void PropertyEditor::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
FC_LOG("current changed " << current.row()<<","<<current.column()
<< " " << previous.row()<<","<<previous.column());
FC_LOG("current changed " << current.row() << "," << current.column() << " " << previous.row()
<< "," << previous.column());
QTreeView::currentChanged(current, previous);
@@ -264,7 +267,7 @@ void PropertyEditor::closeEditor()
#ifdef Q_OS_MACOS
// Brute-force workaround for https://github.com/FreeCAD/FreeCAD/issues/14350
int currentIndex = 0;
QTabBar *tabBar = nullptr;
QTabBar* tabBar = nullptr;
if (auto mdiArea = Gui::MainWindow::getInstance()->findChild<QMdiArea*>()) {
tabBar = mdiArea->findChild<QTabBar*>();
if (tabBar) {
@@ -280,75 +283,84 @@ void PropertyEditor::closeEditor()
#endif
editingIndex = QPersistentModelIndex();
activeEditor = nullptr;
if(hasFocus)
if (hasFocus) {
setFocus();
}
}
}
void PropertyEditor::openEditor(const QModelIndex &index)
void PropertyEditor::openEditor(const QModelIndex& index)
{
if(editingIndex == index && activeEditor)
if (editingIndex == index && activeEditor) {
return;
}
closeEditor();
openPersistentEditor(model()->buddy(index));
if(!editingIndex.isValid() || !autoupdate)
if (!editingIndex.isValid() || !autoupdate) {
return;
}
auto &app = App::GetApplication();
if(app.getActiveTransaction()) {
auto& app = App::GetApplication();
if (app.getActiveTransaction()) {
FC_LOG("editor already transacting " << app.getActiveTransaction());
return;
}
auto item = static_cast<PropertyItem*>(editingIndex.internalPointer());
auto items = item->getPropertyData();
for(auto propItem=item->parent();items.empty() && propItem;propItem=propItem->parent())
for (auto propItem = item->parent(); items.empty() && propItem; propItem = propItem->parent()) {
items = propItem->getPropertyData();
if(items.empty()) {
}
if (items.empty()) {
FC_LOG("editor no item");
return;
}
auto prop = items[0];
auto parent = prop->getContainer();
auto obj = Base::freecad_dynamic_cast<App::DocumentObject>(parent);
auto obj = Base::freecad_dynamic_cast<App::DocumentObject>(parent);
if (!obj) {
auto view = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(parent);
if (view)
auto view = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(parent);
if (view) {
obj = view->getObject();
}
}
if(!obj || !obj->getDocument()) {
if (!obj || !obj->getDocument()) {
FC_LOG("invalid object");
return;
}
if(obj->getDocument()->hasPendingTransaction()) {
if (obj->getDocument()->hasPendingTransaction()) {
FC_LOG("pending transaction");
return;
}
std::ostringstream str;
str << tr("Edit").toUtf8().constData() << ' ';
for(auto prop : items) {
if(prop->getContainer()!=obj) {
for (auto prop : items) {
if (prop->getContainer() != obj) {
obj = nullptr;
break;
}
}
if(obj && obj->isAttachedToDocument())
if (obj && obj->isAttachedToDocument()) {
str << obj->getNameInDocument() << '.';
else
}
else {
str << tr("property").toUtf8().constData() << ' ';
}
str << prop->getName();
if(items.size()>1)
if (items.size() > 1) {
str << "...";
}
transactionID = app.setActiveTransaction(str.str().c_str());
FC_LOG("editor transaction " << app.getActiveTransaction());
}
void PropertyEditor::onItemActivated ( const QModelIndex & index )
void PropertyEditor::onItemActivated(const QModelIndex& index)
{
if(index.column() != 1)
if (index.column() != 1) {
return;
}
openEditor(index);
}
@@ -358,8 +370,9 @@ void PropertyEditor::recomputeDocument(App::Document* doc)
if (doc && !doc->isTransactionEmpty()) {
// Between opening and committing a transaction a recompute
// could already have been done
if (doc->isTouched())
if (doc->isTouched()) {
doc->recompute();
}
}
}
// do not re-throw
@@ -367,11 +380,14 @@ void PropertyEditor::recomputeDocument(App::Document* doc)
e.ReportException();
}
catch (const std::exception& e) {
Base::Console().Error("Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n"
"The error message is: %s\n", e.what());
Base::Console().Error(
"Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n"
"The error message is: %s\n",
e.what());
}
catch (...) {
Base::Console().Error("Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n");
Base::Console().Error(
"Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n");
}
}
@@ -387,10 +403,11 @@ void PropertyEditor::closeTransaction()
}
}
void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEditHint hint)
void PropertyEditor::closeEditor(QWidget* editor, QAbstractItemDelegate::EndEditHint hint)
{
if (closingEditor)
if (closingEditor) {
return;
}
if (removingRows) {
// When removing rows, QTreeView will temporary hide the editor which
@@ -422,23 +439,29 @@ void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEd
do {
QModelIndex index;
if (hint == QAbstractItemDelegate::EditNextItem) {
index = moveCursor(MoveDown,Qt::NoModifier);
} else if(hint == QAbstractItemDelegate::EditPreviousItem) {
index = moveCursor(MoveUp,Qt::NoModifier);
} else
index = moveCursor(MoveDown, Qt::NoModifier);
}
else if (hint == QAbstractItemDelegate::EditPreviousItem) {
index = moveCursor(MoveUp, Qt::NoModifier);
}
else {
break;
}
if (!index.isValid() || index == lastIndex) {
if (wrapped) {
setCurrentIndex(propertyModel->buddy(indexSaved));
break;
}
wrapped = true;
if (hint == QAbstractItemDelegate::EditNextItem)
if (hint == QAbstractItemDelegate::EditNextItem) {
index = moveCursor(MoveHome, Qt::NoModifier);
else
}
else {
index = moveCursor(MoveEnd, Qt::NoModifier);
if (!index.isValid() || index == indexSaved)
}
if (!index.isValid() || index == indexSaved) {
break;
}
}
lastIndex = index;
setCurrentIndex(propertyModel->buddy(index));
@@ -446,8 +469,9 @@ void PropertyEditor::closeEditor (QWidget * editor, QAbstractItemDelegate::EndEd
auto item = static_cast<PropertyItem*>(index.internalPointer());
// Skip readonly item, because the editor will be disabled and hence
// does not accept focus, and in turn break Tab/Backtab navigation.
if (item && item->isReadOnly())
if (item && item->isReadOnly()) {
continue;
}
openEditor(index);
@@ -462,74 +486,88 @@ void PropertyEditor::reset()
QModelIndex parent;
int numRows = propertyModel->rowCount(parent);
for (int i=0; i<numRows; ++i) {
for (int i = 0; i < numRows; ++i) {
QModelIndex index = propertyModel->index(i, 0, parent);
auto item = static_cast<PropertyItem*>(index.internalPointer());
if (item->childCount() == 0) {
if(item->isSeparator())
if (item->isSeparator()) {
setRowHidden(i, parent, true);
} else
setEditorMode(index, 0, item->childCount()-1);
if(item->isExpanded())
}
}
else {
setEditorMode(index, 0, item->childCount() - 1);
}
if (item->isExpanded()) {
setExpanded(index, true);
}
}
}
void PropertyEditor::onRowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &dst, int)
void PropertyEditor::onRowsMoved(const QModelIndex& parent,
int start,
int end,
const QModelIndex& dst,
int)
{
if(parent != dst) {
if (parent != dst) {
auto item = static_cast<PropertyItem*>(parent.internalPointer());
if(item && item->isSeparator() && item->childCount()==0)
if (item && item->isSeparator() && item->childCount() == 0) {
setRowHidden(parent.row(), propertyModel->parent(parent), true);
}
item = static_cast<PropertyItem*>(dst.internalPointer());
if(item && item->isSeparator() && item->childCount()==end-start+1) {
if (item && item->isSeparator() && item->childCount() == end - start + 1) {
setRowHidden(dst.row(), propertyModel->parent(dst), false);
setExpanded(dst, true);
}
}
}
void PropertyEditor::rowsInserted (const QModelIndex & parent, int start, int end)
void PropertyEditor::rowsInserted(const QModelIndex& parent, int start, int end)
{
QTreeView::rowsInserted(parent, start, end);
auto item = static_cast<PropertyItem*>(parent.internalPointer());
if (item && item->isSeparator() && item->childCount() == end-start+1) {
if (item && item->isSeparator() && item->childCount() == end - start + 1) {
setRowHidden(parent.row(), propertyModel->parent(parent), false);
if(item->isExpanded())
if (item->isExpanded()) {
setExpanded(parent, true);
}
}
for (int i=start; i<end; ++i) {
for (int i = start; i < end; ++i) {
QModelIndex index = propertyModel->index(i, 0, parent);
auto child = static_cast<PropertyItem*>(index.internalPointer());
if(child->isSeparator()) {
if (child->isSeparator()) {
// Set group header rows to span all columns
setFirstColumnSpanned(i, parent, true);
}
if(child->isExpanded())
if (child->isExpanded()) {
setExpanded(index, true);
}
}
if(parent.isValid())
if (parent.isValid()) {
setEditorMode(parent, start, end);
}
}
void PropertyEditor::rowsAboutToBeRemoved (const QModelIndex & parent, int start, int end)
void PropertyEditor::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
QTreeView::rowsAboutToBeRemoved(parent, start, end);
auto item = static_cast<PropertyItem*>(parent.internalPointer());
if (item && item->isSeparator() && item->childCount() == end-start+1)
if (item && item->isSeparator() && item->childCount() == end - start + 1) {
setRowHidden(parent.row(), propertyModel->parent(parent), true);
}
if (editingIndex.isValid()) {
if (editingIndex.row() >= start && editingIndex.row() <= end)
if (editingIndex.row() >= start && editingIndex.row() <= end) {
closeTransaction();
}
else {
removingRows = 1;
for (QWidget *w = qApp->focusWidget(); w; w = w->parentWidget()) {
if(w == activeEditor) {
for (QWidget* w = qApp->focusWidget(); w; w = w->parentWidget()) {
if (w == activeEditor) {
removingRows = -1;
break;
}
@@ -538,10 +576,11 @@ void PropertyEditor::rowsAboutToBeRemoved (const QModelIndex & parent, int start
}
}
void PropertyEditor::onRowsRemoved(const QModelIndex &, int, int)
void PropertyEditor::onRowsRemoved(const QModelIndex&, int, int)
{
if (removingRows < 0 && activeEditor)
if (removingRows < 0 && activeEditor) {
activeEditor->setFocus();
}
removingRows = 0;
}
@@ -568,12 +607,13 @@ void Gui::PropertyEditor::PropertyEditor::drawRow(QPainter* painter,
QTreeView::drawRow(painter, options, index);
}
void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDocument)
void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDocument)
{
checkDocument = _checkDocument;
if (committing) {
Base::Console().Warning("While committing the data to the property the selection has changed.\n");
Base::Console().Warning(
"While committing the data to the property the selection has changed.\n");
delaybuild = true;
return;
}
@@ -585,8 +625,9 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDoc
QModelIndex index = this->currentIndex();
QStringList propertyPath = propertyModel->propertyPathFromIndex(index);
if (!propertyPath.isEmpty())
if (!propertyPath.isEmpty()) {
this->selectedProperty = propertyPath;
}
propertyModel->buildUp(props);
if (!this->selectedProperty.isEmpty()) {
QModelIndex index = propertyModel->propertyIndexFromPath(this->selectedProperty);
@@ -595,37 +636,41 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList &&props, bool _checkDoc
propList = std::move(props);
propOwners.clear();
for(auto &v : propList) {
for(auto prop : v.second) {
for (auto& v : propList) {
for (auto prop : v.second) {
auto container = prop->getContainer();
if(!container)
if (!container) {
continue;
}
// Include document to get proper handling in PropertyView::slotDeleteDocument()
if(checkDocument && container->isDerivedFrom(App::DocumentObject::getClassTypeId()))
if (checkDocument && container->isDerivedFrom(App::DocumentObject::getClassTypeId())) {
propOwners.insert(static_cast<App::DocumentObject*>(container)->getDocument());
}
propOwners.insert(container);
}
}
if (autoexpand)
if (autoexpand) {
expandAll();
}
}
void PropertyEditor::updateProperty(const App::Property& prop)
{
// forward this to the model if the property is changed from outside
if (!committing)
if (!committing) {
propertyModel->updateProperty(prop);
}
}
void PropertyEditor::setEditorMode(const QModelIndex & parent, int start, int end)
void PropertyEditor::setEditorMode(const QModelIndex& parent, int start, int end)
{
int column = 1;
for (int i=start; i<=end; i++) {
for (int i = start; i <= end; i++) {
QModelIndex item = propertyModel->index(i, column, parent);
auto propItem = static_cast<PropertyItem*>(item.internalPointer());
if (!PropertyView::showAll() && propItem && propItem->testStatus(App::Property::Hidden)) {
setRowHidden (i, parent, true);
setRowHidden(i, parent, true);
}
}
}
@@ -634,7 +679,8 @@ void PropertyEditor::removeProperty(const App::Property& prop)
{
for (PropertyModel::PropertyList::iterator it = propList.begin(); it != propList.end(); ++it) {
// find the given property in the list and remove it if it's there
std::vector<App::Property*>::iterator pos = std::find(it->second.begin(), it->second.end(), &prop);
std::vector<App::Property*>::iterator pos =
std::find(it->second.begin(), it->second.end(), &prop);
if (pos != it->second.end()) {
it->second.erase(pos);
// if the last property of this name is removed then also remove the whole group
@@ -647,7 +693,8 @@ void PropertyEditor::removeProperty(const App::Property& prop)
}
}
enum MenuAction {
enum MenuAction
{
MA_AutoExpand,
MA_ShowHidden,
MA_Expression,
@@ -664,23 +711,25 @@ enum MenuAction {
MA_CopyOnChange,
};
void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
void PropertyEditor::contextMenuEvent(QContextMenuEvent*)
{
QMenu menu;
QAction *autoExpand = nullptr;
QAction* autoExpand = nullptr;
auto contextIndex = currentIndex();
// acquiring the selected properties
std::unordered_set<App::Property*> props;
const auto indexes = selectedIndexes();
for(const auto& index : indexes) {
for (const auto& index : indexes) {
auto item = static_cast<PropertyItem*>(index.internalPointer());
if(item->isSeparator())
if (item->isSeparator()) {
continue;
for(auto parent=item;parent;parent=parent->parent()) {
const auto &ps = parent->getPropertyData();
if(!ps.empty()) {
props.insert(ps.begin(),ps.end());
}
for (auto parent = item; parent; parent = parent->parent()) {
const auto& ps = parent->getPropertyData();
if (!ps.empty()) {
props.insert(ps.begin(), ps.end());
break;
}
}
@@ -689,10 +738,9 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
// add property
menu.addAction(tr("Add property"))->setData(QVariant(MA_AddProp));
if (!props.empty() && std::all_of(props.begin(), props.end(), [](auto prop) {
return prop->testStatus(App::Property::PropDynamic)
&& !boost::starts_with(prop->getName(),prop->getGroup());
}))
{
return prop->testStatus(App::Property::PropDynamic)
&& !boost::starts_with(prop->getName(), prop->getGroup());
})) {
menu.addAction(tr("Rename property group"))->setData(QVariant(MA_EditPropGroup));
}
@@ -700,23 +748,23 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
bool canRemove = !props.empty();
unsigned long propType = 0;
unsigned long propStatus = 0xffffffff;
for(auto prop : props) {
for (auto prop : props) {
propType |= prop->getType();
propStatus &= prop->getStatus();
if(!prop->testStatus(App::Property::PropDynamic)
|| prop->testStatus(App::Property::LockDynamic))
{
if (!prop->testStatus(App::Property::PropDynamic)
|| prop->testStatus(App::Property::LockDynamic)) {
canRemove = false;
}
}
if(canRemove)
if (canRemove) {
menu.addAction(tr("Remove property"))->setData(QVariant(MA_RemoveProp));
}
// add a separator between adding/removing properties and the rest
menu.addSeparator();
// show all
QAction *showHidden = menu.addAction(tr("Show hidden"));
QAction* showHidden = menu.addAction(tr("Show hidden"));
showHidden->setCheckable(true);
showHidden->setChecked(PropertyView::showAll());
showHidden->setData(QVariant(MA_ShowHidden));
@@ -728,15 +776,12 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
autoExpand->setData(QVariant(MA_AutoExpand));
// expression
if(props.size() == 1) {
if (props.size() == 1) {
auto item = static_cast<PropertyItem*>(contextIndex.internalPointer());
auto prop = *props.begin();
if(item->isBound()
&& !prop->isDerivedFrom(App::PropertyExpressionEngine::getClassTypeId())
&& !prop->isReadOnly()
&& !prop->testStatus(App::Property::Immutable)
&& !(prop->getType() & App::Prop_ReadOnly))
{
if (item->isBound() && !prop->isDerivedFrom(App::PropertyExpressionEngine::getClassTypeId())
&& !prop->isReadOnly() && !prop->testStatus(App::Property::Immutable)
&& !(prop->getType() & App::Prop_ReadOnly)) {
contextIndex = propertyModel->buddy(contextIndex);
setCurrentIndex(contextIndex);
// menu.addSeparator();
@@ -745,29 +790,31 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
}
// the various flags
if(!props.empty()) {
if (!props.empty()) {
menu.addSeparator();
// the subMenu is allocated on the heap but managed by menu.
auto subMenu = new QMenu(QString::fromLatin1("Status"), &menu);
QAction *action;
QAction* action;
QString text;
#define _ACTION_SETUP(_name) do { \
text = tr(#_name); \
action = subMenu->addAction(text); \
action->setData(QVariant(MA_##_name)); \
action->setCheckable(true); \
if(propStatus & (1<<App::Property::_name)) \
action->setChecked(true); \
}while(0)
#define ACTION_SETUP(_name) do { \
_ACTION_SETUP(_name); \
if(propType & App::Prop_##_name) { \
action->setText(text + QString::fromLatin1(" *")); \
action->setChecked(true); \
} \
}while(0)
#define _ACTION_SETUP(_name) \
do { \
text = tr(#_name); \
action = subMenu->addAction(text); \
action->setData(QVariant(MA_##_name)); \
action->setCheckable(true); \
if (propStatus & (1 << App::Property::_name)) \
action->setChecked(true); \
} while (0)
#define ACTION_SETUP(_name) \
do { \
_ACTION_SETUP(_name); \
if (propType & App::Prop_##_name) { \
action->setText(text + QString::fromLatin1(" *")); \
action->setChecked(true); \
} \
} while (0)
ACTION_SETUP(Hidden);
ACTION_SETUP(Output);
@@ -782,112 +829,124 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) {
}
auto action = menu.exec(QCursor::pos());
if(!action)
if (!action) {
return;
}
switch(action->data().toInt()) {
case MA_AutoExpand:
if (autoExpand) {
// Variable autoExpand should not be null when we arrive here, but
// since we explicitly initialize the variable to nullptr, a check
// nonetheless.
autoexpand = autoExpand->isChecked();
if (autoexpand)
expandAll();
}
return;
case MA_ShowHidden:
PropertyView::setShowAll(action->isChecked());
return;
#define ACTION_CHECK(_name) \
case MA_##_name:\
for(auto prop : props) \
prop->setStatus(App::Property::_name,action->isChecked());\
break
ACTION_CHECK(Transient);
ACTION_CHECK(ReadOnly);
ACTION_CHECK(Output);
ACTION_CHECK(Hidden);
ACTION_CHECK(EvalOnRestore);
ACTION_CHECK(CopyOnChange);
case MA_Touched:
for(auto prop : props) {
if(action->isChecked())
prop->touch();
else
prop->purgeTouched();
}
break;
case MA_Expression:
if(contextIndex == currentIndex()) {
Base::FlagToggler<> flag(binding);
closeEditor();
openEditor(contextIndex);
}
break;
case MA_AddProp: {
App::AutoTransaction committer("Add property");
std::unordered_set<App::PropertyContainer*> containers;
auto sels = Gui::Selection().getSelection("*");
if(sels.size() == 1)
containers.insert(sels[0].pObject);
else {
for(auto prop : props)
containers.insert(prop->getContainer());
}
Gui::Dialog::DlgAddProperty dlg(
Gui::getMainWindow(),std::move(containers));
dlg.exec();
return;
}
case MA_EditPropGroup: {
// This operation is not undoable yet.
const char *groupName = (*props.begin())->getGroup();
if(!groupName)
groupName = "Base";
QString res = QInputDialog::getText(Gui::getMainWindow(),
tr("Rename property group"), tr("Group name:"),
QLineEdit::Normal, QString::fromUtf8(groupName));
if(res.size()) {
std::string group = res.toUtf8().constData();
for(auto prop : props)
prop->getContainer()->changeDynamicProperty(prop,group.c_str(),nullptr);
buildUp(PropertyModel::PropertyList(propList),checkDocument);
}
return;
}
case MA_RemoveProp: {
App::AutoTransaction committer("Remove property");
for(auto prop : props) {
try {
prop->getContainer()->removeDynamicProperty(prop->getName());
}catch(Base::Exception &e) {
e.ReportException();
switch (action->data().toInt()) {
case MA_AutoExpand:
if (autoExpand) {
// Variable autoExpand should not be null when we arrive here, but
// since we explicitly initialize the variable to nullptr, a check
// nonetheless.
autoexpand = autoExpand->isChecked();
if (autoexpand) {
expandAll();
}
}
return;
case MA_ShowHidden:
PropertyView::setShowAll(action->isChecked());
return;
#define ACTION_CHECK(_name) \
case MA_##_name: \
for (auto prop : props) \
prop->setStatus(App::Property::_name, action->isChecked()); \
break
ACTION_CHECK(Transient);
ACTION_CHECK(ReadOnly);
ACTION_CHECK(Output);
ACTION_CHECK(Hidden);
ACTION_CHECK(EvalOnRestore);
ACTION_CHECK(CopyOnChange);
case MA_Touched:
for (auto prop : props) {
if (action->isChecked()) {
prop->touch();
}
else {
prop->purgeTouched();
}
}
break;
case MA_Expression:
if (contextIndex == currentIndex()) {
Base::FlagToggler<> flag(binding);
closeEditor();
openEditor(contextIndex);
}
break;
case MA_AddProp: {
App::AutoTransaction committer("Add property");
std::unordered_set<App::PropertyContainer*> containers;
auto sels = Gui::Selection().getSelection("*");
if (sels.size() == 1) {
containers.insert(sels[0].pObject);
}
else {
for (auto prop : props) {
containers.insert(prop->getContainer());
}
}
Gui::Dialog::DlgAddProperty dlg(Gui::getMainWindow(), std::move(containers));
dlg.exec();
return;
}
break;
}
default:
break;
case MA_EditPropGroup: {
// This operation is not undoable yet.
const char* groupName = (*props.begin())->getGroup();
if (!groupName) {
groupName = "Base";
}
QString res = QInputDialog::getText(Gui::getMainWindow(),
tr("Rename property group"),
tr("Group name:"),
QLineEdit::Normal,
QString::fromUtf8(groupName));
if (res.size()) {
std::string group = res.toUtf8().constData();
for (auto prop : props) {
prop->getContainer()->changeDynamicProperty(prop, group.c_str(), nullptr);
}
buildUp(PropertyModel::PropertyList(propList), checkDocument);
}
return;
}
case MA_RemoveProp: {
App::AutoTransaction committer("Remove property");
for (auto prop : props) {
try {
prop->getContainer()->removeDynamicProperty(prop->getName());
}
catch (Base::Exception& e) {
e.ReportException();
}
}
break;
}
default:
break;
}
}
bool PropertyEditor::eventFilter(QObject* object, QEvent* event) {
bool PropertyEditor::eventFilter(QObject* object, QEvent* event)
{
if (object == viewport()) {
QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
if (mouse_event) {
if (mouse_event->type() == QEvent::MouseMove) {
if (dragInProgress) { // apply dragging
if (dragInProgress) { // apply dragging
QHeaderView* header_view = header();
int delta = mouse_event->pos().x() - dragPreviousPos;
dragPreviousPos = mouse_event->pos().x();
//using minimal size = dragSensibility * 2 to prevent collapsing
header_view->resizeSection(dragSection,
// using minimal size = dragSensibility * 2 to prevent collapsing
header_view->resizeSection(
dragSection,
qMax(dragSensibility * 2, header_view->sectionSize(dragSection) + delta));
return true;
}
else { // set mouse cursor shape
else { // set mouse cursor shape
if (indexResizable(mouse_event->pos()).isValid()) {
viewport()->setCursor(Qt::SplitHCursor);
}
@@ -896,10 +955,11 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) {
}
}
}
else if (mouse_event->type() == QEvent::MouseButtonPress && mouse_event->button() == Qt::LeftButton && !dragInProgress) {
else if (mouse_event->type() == QEvent::MouseButtonPress
&& mouse_event->button() == Qt::LeftButton && !dragInProgress) {
if (indexResizable(mouse_event->pos()).isValid()) {
dragInProgress = true;
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
dragPreviousPos = mouse_event->x();
#else
dragPreviousPos = mouse_event->position().toPoint().x();
@@ -908,11 +968,12 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) {
return true;
}
}
else if (mouse_event->type() == QEvent::MouseButtonRelease &&
mouse_event->button() == Qt::LeftButton && dragInProgress) {
else if (mouse_event->type() == QEvent::MouseButtonRelease
&& mouse_event->button() == Qt::LeftButton && dragInProgress) {
dragInProgress = false;
auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DockWindows/PropertyView");
auto hGrp = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/DockWindows/PropertyView");
hGrp->SetInt("FirstColumnSize", header()->sectionSize(0));
return true;
}
@@ -921,11 +982,12 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) {
return false;
}
QModelIndex PropertyEditor::indexResizable(QPoint mouse_pos) {
QModelIndex PropertyEditor::indexResizable(QPoint mouse_pos)
{
QModelIndex index = indexAt(mouse_pos - QPoint(dragSensibility + 1, 0));
if (index.isValid()) {
if (qAbs(visualRect(index).right() - mouse_pos.x()) < dragSensibility &&
header()->sectionResizeMode(index.column()) == QHeaderView::Interactive) {
if (qAbs(visualRect(index).right() - mouse_pos.x()) < dragSensibility
&& header()->sectionResizeMode(index.column()) == QHeaderView::Interactive) {
return index;
}
}

View File

@@ -82,7 +82,7 @@ WidgetFactorySupplier::WidgetFactorySupplier()
new PrefPageProducer<DlgSettingsReportView> ( QT_TRANSLATE_NOOP("QObject","General") );
new PrefPageProducer<DlgSettings3DViewImp> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsLightSources> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsUI> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsUI> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsNavigation> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsViewColor> ( QT_TRANSLATE_NOOP("QObject","Display") );
new PrefPageProducer<DlgSettingsAdvanced> ( QT_TRANSLATE_NOOP("QObject","Display") );