FreeCAD

Форк
0
/
DlgUnitsCalculatorImp.cpp 
228 строк · 10.0 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2013 Jürgen Riegel <juergen.riegel@web.de>              *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 of the License, or (at your option) any later version.      *
10
 *                                                                         *
11
 *   This library  is distributed in the hope that it will be useful,      *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23

24
#include "PreCompiled.h"
25
#ifndef _PreComp_
26
#include <QApplication>
27
#include <QClipboard>
28
#include <QLocale>
29
#endif
30

31
#include "DlgUnitsCalculatorImp.h"
32
#include "ui_DlgUnitsCalculator.h"
33
#include <Base/UnitsApi.h>
34

35
using namespace Gui::Dialog;
36

37
/* TRANSLATOR Gui::Dialog::DlgUnitsCalculator */
38

39
/**
40
 *  Constructs a DlgUnitsCalculator which is a child of 'parent', with the
41
 *  name 'name' and widget flags set to 'f'
42
 *
43
 *  The dialog will by default be modeless, unless you set 'modal' to
44
 *  true to construct a modal dialog.
45
 */
46
DlgUnitsCalculator::DlgUnitsCalculator(QWidget* parent, Qt::WindowFlags fl)
47
    : QDialog(parent, fl)
48
    , ui(new Ui_DlgUnitCalculator)
49
{
50
    // create widgets
51
    ui->setupUi(this);
52
    this->setAttribute(Qt::WA_DeleteOnClose);
53

54
    ui->comboBoxScheme->addItem(QString::fromLatin1("Preference system"), static_cast<int>(-1));
55
    int num = static_cast<int>(Base::UnitSystem::NumUnitSystemTypes);
56
    for (int i = 0; i < num; i++) {
57
        QString item = Base::UnitsApi::getDescription(static_cast<Base::UnitSystem>(i));
58
        ui->comboBoxScheme->addItem(item, i);
59
    }
60

61
    // clang-format off
62
    connect(ui->unitsBox, qOverload<int>(&QComboBox::activated),
63
            this, &DlgUnitsCalculator::onUnitsBoxActivated);
64
    connect(ui->comboBoxScheme, qOverload<int>(&QComboBox::activated),
65
            this, &DlgUnitsCalculator::onComboBoxSchemeActivated);
66
    connect(ui->spinBoxDecimals, qOverload<int>(&QSpinBox::valueChanged),
67
            this, &DlgUnitsCalculator::onSpinBoxDecimalsValueChanged);
68
    connect(ui->ValueInput, qOverload<const Base::Quantity&>(&InputField::valueChanged),
69
            this, &DlgUnitsCalculator::valueChanged);
70
    connect(ui->ValueInput, &InputField::returnPressed,
71
            this, &DlgUnitsCalculator::returnPressed);
72
    connect(ui->ValueInput, &InputField::parseError,
73
            this, &DlgUnitsCalculator::parseError);
74
    connect(ui->UnitInput, &QLineEdit::textChanged,
75
            this, &DlgUnitsCalculator::textChanged);
76
    connect(ui->UnitInput, &QLineEdit::returnPressed,
77
            this, &DlgUnitsCalculator::returnPressed);
78
    connect(ui->pushButton_Close, &QPushButton::clicked,
79
            this, &DlgUnitsCalculator::accept);
80
    connect(ui->pushButton_Copy, &QPushButton::clicked,
81
            this, &DlgUnitsCalculator::copy);
82
    // clang-format on
83

84
    ui->ValueInput->setParamGrpPath(QByteArray("User parameter:BaseApp/History/UnitsCalculator"));
85
    // set a default that also illustrates how the dialog works
86
    ui->ValueInput->setText(QString::fromLatin1("1 cm"));
87
    ui->UnitInput->setText(QString::fromLatin1("in"));
88

89
    units << Base::Unit::Acceleration << Base::Unit::AmountOfSubstance << Base::Unit::Angle
90
          << Base::Unit::Area << Base::Unit::Density << Base::Unit::CurrentDensity
91
          << Base::Unit::DissipationRate << Base::Unit::DynamicViscosity
92
          << Base::Unit::ElectricalCapacitance << Base::Unit::ElectricalInductance
93
          << Base::Unit::ElectricalConductance << Base::Unit::ElectricalResistance
94
          << Base::Unit::ElectricalConductivity << Base::Unit::ElectricCharge
95
          << Base::Unit::ElectricCurrent << Base::Unit::ElectricPotential << Base::Unit::Force
96
          << Base::Unit::Frequency << Base::Unit::HeatFlux << Base::Unit::InverseArea
97
          << Base::Unit::InverseLength << Base::Unit::InverseVolume
98
          << Base::Unit::KinematicViscosity << Base::Unit::Length << Base::Unit::LuminousIntensity
99
          << Base::Unit::Mass << Base::Unit::MagneticFieldStrength << Base::Unit::MagneticFlux
100
          << Base::Unit::MagneticFluxDensity << Base::Unit::Magnetization << Base::Unit::Power
101
          << Base::Unit::Pressure << Base::Unit::SpecificEnergy << Base::Unit::SpecificHeat
102
          << Base::Unit::Stiffness << Base::Unit::Temperature << Base::Unit::ThermalConductivity
103
          << Base::Unit::ThermalExpansionCoefficient << Base::Unit::ThermalTransferCoefficient
104
          << Base::Unit::TimeSpan << Base::Unit::VacuumPermittivity << Base::Unit::Velocity
105
          << Base::Unit::Volume << Base::Unit::VolumeFlowRate
106
          << Base::Unit::VolumetricThermalExpansionCoefficient << Base::Unit::Work;
107
    for (const Base::Unit& it : units) {
108
        ui->unitsBox->addItem(it.getTypeString());
109
    }
110

111
    ui->quantitySpinBox->setValue(1.0);
112
    ui->quantitySpinBox->setUnit(units.front());
113
    ui->spinBoxDecimals->setValue(Base::UnitsApi::getDecimals());
114
}
115

116
/** Destroys the object and frees any allocated resources */
117
DlgUnitsCalculator::~DlgUnitsCalculator() = default;
118

119
void DlgUnitsCalculator::accept()
120
{
121
    QDialog::accept();
122
}
123

124
void DlgUnitsCalculator::reject()
125
{
126
    QDialog::reject();
127
}
128

129
void DlgUnitsCalculator::textChanged(QString unit)
130
{
131
    Q_UNUSED(unit)
132
    valueChanged(actValue);
133
}
134

135
void DlgUnitsCalculator::valueChanged(const Base::Quantity& quant)
136
{
137
    // first check the unit, if it is invalid, getTypeString() outputs an empty string
138
    // explicitly check for "ee" like in "eeV" because this would trigger an exception in Base::Unit
139
    // since it expects then a scientific notation number like "1e3"
140
    if ((ui->UnitInput->text().mid(0, 2) == QString::fromLatin1("ee"))
141
        || Base::Unit(ui->UnitInput->text()).getTypeString().isEmpty()) {
142
        ui->ValueOutput->setText(
143
            QString::fromLatin1("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text()));
144
        ui->pushButton_Copy->setEnabled(false);
145
    }
146
    else {  // the unit is valid
147
        // we can only convert units of the same type, thus check
148
        if (Base::Unit(ui->UnitInput->text()).getTypeString() != quant.getUnit().getTypeString()) {
149
            ui->ValueOutput->setText(tr("unit mismatch"));
150
            ui->pushButton_Copy->setEnabled(false);
151
        }
152
        else {  // the unit is valid and has the same type
153
            double convertValue =
154
                Base::Quantity::parse(QString::fromLatin1("1") + ui->UnitInput->text()).getValue();
155
            // we got now e.g. for "1 in" the value '25.4' because 1 in = 25.4 mm
156
            // the result is now just quant / convertValue because the input is always in a base
157
            // unit (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField
158
            // of the dialog)
159
            double value = quant.getValue() / convertValue;
160
            // determine how many decimals we will need to avoid an output like "0.00"
161
            // at first use scientific notation, if there is no "e", we can round it to the
162
            // user-defined decimals, but the user-defined decimals might be too low for cases like
163
            // "10 um" in "in", thus only if value > 0.005 because FC's default are 2 decimals
164
            QString val = QLocale().toString(value, 'g');
165
            if (!val.contains(QChar::fromLatin1('e')) && (value > 0.005)) {
166
                val = QLocale().toString(value, 'f', Base::UnitsApi::getDecimals());
167
            }
168
            // create the output string
169
            QString out = QString::fromLatin1("%1 %2").arg(val, ui->UnitInput->text());
170
            ui->ValueOutput->setText(out);
171
            ui->pushButton_Copy->setEnabled(true);
172
        }
173
    }
174
    // store the input value
175
    actValue = quant;
176
}
177

178
void DlgUnitsCalculator::parseError(const QString& errorText)
179
{
180
    ui->pushButton_Copy->setEnabled(false);
181
    ui->ValueOutput->setText(errorText);
182
}
183

184
void DlgUnitsCalculator::copy()
185
{
186
    QClipboard* cb = QApplication::clipboard();
187
    cb->setText(ui->ValueOutput->text());
188
}
189

190
void DlgUnitsCalculator::returnPressed()
191
{
192
    if (ui->pushButton_Copy->isEnabled()) {
193
        ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ")
194
                             + ui->ValueOutput->text());
195
        ui->ValueInput->pushToHistory();
196
    }
197
}
198

199
void DlgUnitsCalculator::onUnitsBoxActivated(int index)
200
{
201
    // SI units use [m], not [mm] for lengths
202
    //
203
    Base::Quantity q = ui->quantitySpinBox->value();
204
    int32_t old = q.getUnit().getSignature().Length;
205
    double value = q.getValue();
206

207
    Base::Unit unit = units[index];
208
    int32_t len = unit.getSignature().Length;
209
    ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3 * (len - old)), unit));
210
}
211

212
void DlgUnitsCalculator::onComboBoxSchemeActivated(int index)
213
{
214
    int item = ui->comboBoxScheme->itemData(index).toInt();
215
    if (item > 0) {
216
        ui->quantitySpinBox->setSchema(static_cast<Base::UnitSystem>(item));
217
    }
218
    else {
219
        ui->quantitySpinBox->clearSchema();
220
    }
221
}
222

223
void DlgUnitsCalculator::onSpinBoxDecimalsValueChanged(int value)
224
{
225
    ui->quantitySpinBox->setDecimals(value);
226
}
227

228
#include "moc_DlgUnitsCalculatorImp.cpp"
229

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.