FreeCAD

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

23

24
#include "PreCompiled.h"
25
#ifdef __GNUC__
26
#include <unistd.h>
27
#endif
28

29
#include <CXX/WrapPython.h>
30
#include <memory>
31
#include <QString>
32
#include "Exception.h"
33

34
#include "UnitsApi.h"
35
#include "UnitsSchemaCentimeters.h"
36
#include "UnitsSchemaInternal.h"
37
#include "UnitsSchemaImperial1.h"
38
#include "UnitsSchemaMKS.h"
39
#include "UnitsSchemaMmMin.h"
40
#include "UnitsSchemaFemMilliMeterNewton.h"
41
#include "UnitsSchemaMeterDecimal.h"
42

43
#ifndef M_PI
44
#define M_PI 3.14159265358979323846
45
#endif
46
#ifndef M_E
47
#define M_E 2.71828182845904523536
48
#endif
49
#ifndef DOUBLE_MAX
50
#define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/
51
#endif
52
#ifndef DOUBLE_MIN
53
#define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/
54
#endif
55

56
using namespace Base;
57

58
// === static attributes  ================================================
59

60
UnitsSchemaPtr UnitsApi::UserPrefSystem(new UnitsSchemaInternal());
61
UnitSystem UnitsApi::currentSystem = UnitSystem::SI1;
62

63
int UnitsApi::UserPrefDecimals = 2;
64

65
QString UnitsApi::getDescription(UnitSystem system)
66
{
67
    switch (system) {
68
        case UnitSystem::SI1:
69
            return tr("Standard (mm, kg, s, °)");
70
        case UnitSystem::SI2:
71
            return tr("MKS (m, kg, s, °)");
72
        case UnitSystem::Imperial1:
73
            return tr("US customary (in, lb)");
74
        case UnitSystem::ImperialDecimal:
75
            return tr("Imperial decimal (in, lb)");
76
        case UnitSystem::Centimeters:
77
            return tr("Building Euro (cm, m², m³)");
78
        case UnitSystem::ImperialBuilding:
79
            return tr("Building US (ft-in, sqft, cft)");
80
        case UnitSystem::MmMin:
81
            return tr("Metric small parts & CNC (mm, mm/min)");
82
        case UnitSystem::ImperialCivil:
83
            return tr("Imperial for Civil Eng (ft, ft/s)");
84
        case UnitSystem::FemMilliMeterNewton:
85
            return tr("FEM (mm, N, s)");
86
        case UnitSystem::MeterDecimal:
87
            return tr("Meter decimal (m, m², m³)");
88
        default:
89
            return tr("Unknown schema");
90
    }
91
}
92

93
UnitsSchemaPtr UnitsApi::createSchema(UnitSystem system)
94
{
95
    switch (system) {
96
        case UnitSystem::SI1:
97
            return std::make_unique<UnitsSchemaInternal>();
98
        case UnitSystem::SI2:
99
            return std::make_unique<UnitsSchemaMKS>();
100
        case UnitSystem::Imperial1:
101
            return std::make_unique<UnitsSchemaImperial1>();
102
        case UnitSystem::ImperialDecimal:
103
            return std::make_unique<UnitsSchemaImperialDecimal>();
104
        case UnitSystem::Centimeters:
105
            return std::make_unique<UnitsSchemaCentimeters>();
106
        case UnitSystem::ImperialBuilding:
107
            return std::make_unique<UnitsSchemaImperialBuilding>();
108
        case UnitSystem::MmMin:
109
            return std::make_unique<UnitsSchemaMmMin>();
110
        case UnitSystem::ImperialCivil:
111
            return std::make_unique<UnitsSchemaImperialCivil>();
112
        case UnitSystem::FemMilliMeterNewton:
113
            return std::make_unique<UnitsSchemaFemMilliMeterNewton>();
114
        case UnitSystem::MeterDecimal:
115
            return std::make_unique<UnitsSchemaMeterDecimal>();
116
        default:
117
            break;
118
    }
119

120
    return nullptr;
121
}
122

123
void UnitsApi::setSchema(UnitSystem system)
124
{
125
    if (UserPrefSystem) {
126
        UserPrefSystem->resetSchemaUnits();  // for schemas changed the Quantity constants
127
    }
128

129
    UserPrefSystem = createSchema(system);
130
    currentSystem = system;
131

132
    // for wrong value fall back to standard schema
133
    if (!UserPrefSystem) {
134
        UserPrefSystem = std::make_unique<UnitsSchemaInternal>();
135
        currentSystem = UnitSystem::SI1;
136
    }
137

138
    UserPrefSystem->setSchemaUnits();  // if necessary a unit schema can change the constants in
139
                                       // Quantity (e.g. mi=1.8km rather then 1.6km).
140
}
141

142
QString UnitsApi::toString(const Base::Quantity& quantity, const QuantityFormat& format)
143
{
144
    QString value = QString::fromLatin1("'%1 %2'")
145
                        .arg(quantity.getValue(), 0, format.toFormat(), format.precision)
146
                        .arg(quantity.getUnit().getString());
147
    return value;
148
}
149

150
QString UnitsApi::toNumber(const Base::Quantity& quantity, const QuantityFormat& format)
151
{
152
    return toNumber(quantity.getValue(), format);
153
}
154

155
QString UnitsApi::toNumber(double value, const QuantityFormat& format)
156
{
157
    QString number = QString::fromLatin1("%1").arg(value, 0, format.toFormat(), format.precision);
158
    return number;
159
}
160

161
// return true if the current user schema uses multiple units for length (ex. Ft/In)
162
bool UnitsApi::isMultiUnitLength()
163
{
164
    return UserPrefSystem->isMultiUnitLength();
165
}
166

167
// return true if the current user schema uses multiple units for angles (ex. DMS)
168
bool UnitsApi::isMultiUnitAngle()
169
{
170
    return UserPrefSystem->isMultiUnitAngle();
171
}
172

173
std::string UnitsApi::getBasicLengthUnit()
174
{
175
    return UserPrefSystem->getBasicLengthUnit();
176
}
177

178
// === static translation methods ==========================================
179

180
QString UnitsApi::schemaTranslate(const Base::Quantity& quant, double& factor, QString& unitString)
181
{
182
    return UserPrefSystem->schemaTranslate(quant, factor, unitString);
183
}
184

185
double UnitsApi::toDouble(PyObject* args, const Base::Unit& u)
186
{
187
    if (PyUnicode_Check(args)) {
188
        QString str = QString::fromUtf8(PyUnicode_AsUTF8(args));
189
        // Parse the string
190
        Quantity q = Quantity::parse(str);
191
        if (q.getUnit() == u) {
192
            return q.getValue();
193
        }
194
        throw Base::UnitsMismatchError("Wrong unit type!");
195
    }
196

197
    if (PyFloat_Check(args)) {
198
        return PyFloat_AsDouble(args);
199
    }
200
    if (PyLong_Check(args)) {
201
        return static_cast<double>(PyLong_AsLong(args));
202
    }
203

204
    throw Base::UnitsMismatchError("Wrong parameter type!");
205
}
206

207
Quantity UnitsApi::toQuantity(PyObject* args, const Base::Unit& u)
208
{
209
    double d {};
210
    if (PyUnicode_Check(args)) {
211
        QString str = QString::fromUtf8(PyUnicode_AsUTF8(args));
212
        // Parse the string
213
        Quantity q = Quantity::parse(str);
214
        d = q.getValue();
215
    }
216
    else if (PyFloat_Check(args)) {
217
        d = PyFloat_AsDouble(args);
218
    }
219
    else if (PyLong_Check(args)) {
220
        d = static_cast<double>(PyLong_AsLong(args));
221
    }
222
    else {
223
        throw Base::UnitsMismatchError("Wrong parameter type!");
224
    }
225

226
    return Quantity(d, u);
227
}
228

229
void UnitsApi::setDecimals(int prec)
230
{
231
    UserPrefDecimals = prec;
232
}
233

234
int UnitsApi::getDecimals()
235
{
236
    return UserPrefDecimals;
237
}
238

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

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

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

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