FreeCAD

Форк
0
/
DlgUnitsCalculatorImp.cpp 
239 строк · 10.1 Кб
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), ui(new Ui_DlgUnitCalculator)
48
{
49
    // create widgets
50
    ui->setupUi(this);
51
    this->setAttribute(Qt::WA_DeleteOnClose);
52

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

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

76
    ui->ValueInput->setParamGrpPath(QByteArray("User parameter:BaseApp/History/UnitsCalculator"));
77
    // set a default that also illustrates how the dialog works
78
    ui->ValueInput->setText(QString::fromLatin1("1 cm"));
79
    ui->UnitInput->setText(QString::fromLatin1("in"));
80

81
    units << Base::Unit::Acceleration
82
          << Base::Unit::AmountOfSubstance
83
          << Base::Unit::Angle
84
          << Base::Unit::Area
85
          << Base::Unit::Density
86
          << Base::Unit::CurrentDensity
87
          << Base::Unit::DissipationRate
88
          << Base::Unit::DynamicViscosity
89
          << Base::Unit::ElectricalCapacitance
90
          << Base::Unit::ElectricalInductance
91
          << Base::Unit::ElectricalConductance
92
          << Base::Unit::ElectricalResistance
93
          << Base::Unit::ElectricalConductivity
94
          << Base::Unit::ElectricCharge
95
          << Base::Unit::ElectricCurrent
96
          << Base::Unit::ElectricPotential
97
          << Base::Unit::Force
98
          << Base::Unit::Frequency
99
          << Base::Unit::HeatFlux
100
          << Base::Unit::InverseArea
101
          << Base::Unit::InverseLength
102
          << Base::Unit::InverseVolume
103
          << Base::Unit::KinematicViscosity
104
          << Base::Unit::Length
105
          << Base::Unit::LuminousIntensity
106
          << Base::Unit::Mass
107
          << Base::Unit::MagneticFieldStrength
108
          << Base::Unit::MagneticFlux
109
          << Base::Unit::MagneticFluxDensity
110
          << Base::Unit::Magnetization
111
          << Base::Unit::Power
112
          << Base::Unit::Pressure
113
          << Base::Unit::SpecificEnergy
114
          << Base::Unit::SpecificHeat
115
          << Base::Unit::Stiffness
116
          << Base::Unit::Temperature
117
          << Base::Unit::ThermalConductivity
118
          << Base::Unit::ThermalExpansionCoefficient
119
          << Base::Unit::ThermalTransferCoefficient
120
          << Base::Unit::TimeSpan
121
          << Base::Unit::VacuumPermittivity
122
          << Base::Unit::Velocity
123
          << Base::Unit::Volume
124
          << Base::Unit::VolumeFlowRate
125
          << Base::Unit::VolumetricThermalExpansionCoefficient
126
          << Base::Unit::Work;
127
    for (const Base::Unit& it : units) {
128
        ui->unitsBox->addItem(it.getTypeString());
129
    }
130

131
    ui->quantitySpinBox->setValue(1.0);
132
    ui->quantitySpinBox->setUnit(units.front());
133
    ui->spinBoxDecimals->setValue(Base::UnitsApi::getDecimals());
134
}
135

136
/** Destroys the object and frees any allocated resources */
137
DlgUnitsCalculator::~DlgUnitsCalculator() = default;
138

139
void DlgUnitsCalculator::accept()
140
{
141
    QDialog::accept();
142
}
143

144
void DlgUnitsCalculator::reject()
145
{
146
    QDialog::reject();
147
}
148

149
void DlgUnitsCalculator::textChanged(QString unit)
150
{
151
    Q_UNUSED(unit)
152
    valueChanged(actValue);
153
}
154

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

192
void DlgUnitsCalculator::parseError(const QString& errorText)
193
{
194
    ui->pushButton_Copy->setEnabled(false);
195
    ui->ValueOutput->setText(errorText);
196
}
197

198
void DlgUnitsCalculator::copy()
199
{
200
    QClipboard *cb = QApplication::clipboard();
201
    cb->setText(ui->ValueOutput->text());
202
}
203

204
void DlgUnitsCalculator::returnPressed()
205
{
206
    if (ui->pushButton_Copy->isEnabled()) {
207
        ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ") + ui->ValueOutput->text());
208
        ui->ValueInput->pushToHistory();
209
    }
210
}
211

212
void DlgUnitsCalculator::onUnitsBoxActivated(int index)
213
{
214
    // SI units use [m], not [mm] for lengths
215
    //
216
    Base::Quantity q = ui->quantitySpinBox->value();
217
    int32_t old = q.getUnit().getSignature().Length;
218
    double value = q.getValue();
219

220
    Base::Unit unit = units[index];
221
    int32_t len = unit.getSignature().Length;
222
    ui->quantitySpinBox->setValue(Base::Quantity(value * std::pow(10.0, 3*(len-old)), unit));
223
}
224

225
void DlgUnitsCalculator::onComboBoxSchemeActivated(int index)
226
{
227
    int item = ui->comboBoxScheme->itemData(index).toInt();
228
    if (item > 0)
229
        ui->quantitySpinBox->setSchema(static_cast<Base::UnitSystem>(item));
230
    else
231
        ui->quantitySpinBox->clearSchema();
232
}
233

234
void DlgUnitsCalculator::onSpinBoxDecimalsValueChanged(int value)
235
{
236
    ui->quantitySpinBox->setDecimals(value);
237
}
238

239
#include "moc_DlgUnitsCalculatorImp.cpp"
240

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

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

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

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