FreeCAD

Форк
0
/
PropertyGeometryList.cpp 
313 строк · 11.0 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2010 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
#include "PreCompiled.h"
24

25
#include <Base/Console.h>
26
#include <Base/Reader.h>
27
#include <Base/Writer.h>
28

29
#include "PropertyGeometryList.h"
30
#include "GeometryMigrationExtension.h"
31
#include "GeometryPy.h"
32
#include "Part2DObject.h"
33

34

35
using namespace App;
36
using namespace Base;
37
using namespace std;
38
using namespace Part;
39

40

41
//**************************************************************************
42
// PropertyGeometryList
43
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44

45
TYPESYSTEM_SOURCE(Part::PropertyGeometryList, App::PropertyLists)
46

47
//**************************************************************************
48
// Construction/Destruction
49

50

51
PropertyGeometryList::PropertyGeometryList() = default;
52

53
PropertyGeometryList::~PropertyGeometryList()
54
{
55
    for (auto it : _lValueList) {
56
        if (it) delete it;
57
    }
58
}
59

60
void PropertyGeometryList::setSize(int newSize)
61
{
62
    for (unsigned int i = newSize; i < _lValueList.size(); i++)
63
        delete _lValueList[i];
64
    _lValueList.resize(newSize);
65
}
66

67
int PropertyGeometryList::getSize() const
68
{
69
    return static_cast<int>(_lValueList.size());
70
}
71

72
void PropertyGeometryList::setValue(const Geometry* lValue)
73
{
74
    if (lValue) {
75
        aboutToSetValue();
76
        Geometry* newVal = lValue->clone();
77
        for (auto it : _lValueList)
78
            delete it;
79
        _lValueList.resize(1);
80
        _lValueList[0] = newVal;
81
        hasSetValue();
82
    }
83
}
84

85
void PropertyGeometryList::setValues(const std::vector<Geometry*>& lValue)
86
{
87
    auto copy = lValue;
88
    aboutToSetValue();
89
    std::sort(_lValueList.begin(), _lValueList.end());
90
    for (auto & geo : copy) {
91
        auto range = std::equal_range(_lValueList.begin(), _lValueList.end(), geo);
92
        // clone if the new entry does not exist in the original value list, or
93
        // else, simply reuse it (i.e. erase it so that it won't get deleted below).
94
        if (range.first == range.second)
95
            geo = geo->clone();
96
        else
97
            _lValueList.erase(range.first, range.second);
98
    }
99
    for (auto v : _lValueList)
100
        delete v;
101
    _lValueList = std::move(copy);
102
    hasSetValue();
103
}
104

105
void PropertyGeometryList::setValues(std::vector<Geometry*> &&lValue)
106
{
107
    // Unlike above, the moved version of setValues() indicates the caller want
108
    // us to manager the memory of the passed in values. So no need clone.
109
    aboutToSetValue();
110
    std::sort(_lValueList.begin(), _lValueList.end());
111
    for (auto geo : lValue) {
112
        auto range = std::equal_range(_lValueList.begin(), _lValueList.end(), geo);
113
        _lValueList.erase(range.first, range.second);
114
    }
115
    for (auto geo : _lValueList)
116
        delete geo;
117
    _lValueList = std::move(lValue);
118
    hasSetValue();
119
}
120

121
void PropertyGeometryList::set1Value(int idx, std::unique_ptr<Geometry> &&lValue)
122
{
123
    if (!lValue)
124
        return;
125
    if(idx>=(int)_lValueList.size())
126
        throw Base::IndexError("Index out of bound");
127
    aboutToSetValue();
128
    if(idx < 0)
129
        _lValueList.push_back(lValue.release());
130
    else {
131
        delete _lValueList[idx];
132
        _lValueList[idx] = lValue.release();
133
    }
134
    hasSetValue();
135
}
136

137
PyObject *PropertyGeometryList::getPyObject()
138
{
139
    Py::List list;
140
    for (int i = 0; i < getSize(); i++) {
141
        list.append(Py::asObject(_lValueList[i]->getPyObject()));
142
    }
143
    return Py::new_reference_to(list);
144
}
145

146
void PropertyGeometryList::setPyObject(PyObject *value)
147
{
148
    // check container of this property to notify about changes
149
    Part2DObject* part2d = dynamic_cast<Part2DObject*>(this->getContainer());
150

151
    if (PySequence_Check(value)) {
152
        Py::Sequence sequence(value);
153
        Py_ssize_t nSize = sequence.size();
154
        std::vector<Geometry*> values;
155
        values.resize(nSize);
156

157
        for (Py_ssize_t i=0; i < nSize; ++i) {
158
            Py::Object item = sequence.getItem(i);
159
            if (!PyObject_TypeCheck(item.ptr(), &(GeometryPy::Type))) {
160
                std::string error = std::string("types in list must be 'Geometry', not ");
161
                error += item.ptr()->ob_type->tp_name;
162
                throw Base::TypeError(error);
163
            }
164

165
            values[i] = static_cast<GeometryPy*>(item.ptr())->getGeometryPtr();
166
        }
167

168
        setValues(values);
169
        if (part2d) {
170
            part2d->acceptGeometry();
171
        }
172
    }
173
    else if (PyObject_TypeCheck(value, &(GeometryPy::Type))) {
174
        GeometryPy  *pcObject = static_cast<GeometryPy*>(value);
175
        setValue(pcObject->getGeometryPtr());
176
        if (part2d) {
177
            part2d->acceptGeometry();
178
        }
179
    }
180
    else {
181
        std::string error = std::string("type must be 'Geometry' or list of 'Geometry', not ");
182
        error += value->ob_type->tp_name;
183
        throw Base::TypeError(error);
184
    }
185
}
186

187
void PropertyGeometryList::trySaveGeometry(Geometry * geom, Base::Writer &writer) const
188
{
189
    // Not all geometry classes implement Save() and throw an exception instead
190
    try {
191
        geom->Save(writer);
192
        for( auto & ext : geom->getExtensions() ) {
193
            auto extension = ext.lock();
194
            auto gpe = freecad_dynamic_cast<GeometryMigrationPersistenceExtension>(extension.get());
195
            if (gpe)
196
                gpe->postSave(writer);
197
        }
198
    }
199
    catch (const Base::NotImplementedError& e) {
200
        Base::Console().Warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what());
201
    }
202
}
203

204
void PropertyGeometryList::tryRestoreGeometry(Geometry * geom, Base::XMLReader &reader)
205
{
206
    // Not all geometry classes implement Restore() and throw an exception instead
207
    try {
208
        if (!reader.getAttributeAsInteger("migrated", "0") && reader.hasAttribute("id")) {
209
            auto ext = std::make_unique<GeometryMigrationExtension>();
210
            ext->setId(reader.getAttributeAsInteger("id"));
211
            if(reader.hasAttribute("ref")) {
212
                const char *ref = reader.getAttribute("ref");
213
                int index = reader.getAttributeAsInteger("refIndex", "1");
214
                unsigned long flags = (unsigned long)reader.getAttributeAsUnsigned("flags");
215
                ext->setReference(ref, index, flags);
216
            }
217
            geom->setExtension(std::move(ext));
218
        }
219
        geom->Restore(reader);
220
    }
221
    catch (const Base::NotImplementedError& e) {
222
        Base::Console().Warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what());
223
    }
224
}
225

226
void PropertyGeometryList::Save(Writer &writer) const
227
{
228
    writer.Stream() << writer.ind() << "<GeometryList count=\"" << getSize() <<"\">" << endl;
229
    writer.incInd();
230
    for (int i = 0; i < getSize(); i++) {
231
        writer.Stream() << writer.ind() << "<Geometry type=\""
232
                                        << _lValueList[i]->getTypeId().getName() << "\"" << endl;
233
        for( auto &e : _lValueList[i]->getExtensions() ) {
234
            auto ext = e.lock();
235
            auto gpe = freecad_dynamic_cast<GeometryMigrationPersistenceExtension>(ext.get());
236
            if (gpe)
237
                gpe->preSave(writer);
238
        }
239
        writer.Stream() << " migrated=\"1\">\n";
240

241
        writer.incInd();
242
        trySaveGeometry(_lValueList[i], writer);
243
        writer.decInd();
244
        writer.Stream() << writer.ind() << "</Geometry>" << endl;
245
    }
246
    writer.decInd();
247
    writer.Stream() << writer.ind() << "</GeometryList>" << endl ;
248
}
249

250
void PropertyGeometryList::Restore(Base::XMLReader &reader)
251
{
252
    // read my element
253
    reader.clearPartialRestoreObject();
254
    reader.readElement("GeometryList");
255
    // get the value of my attribute
256
    int count = reader.getAttributeAsInteger("count");
257
    std::vector<Geometry*> values;
258
    values.reserve(count);
259
    for (int i = 0; i < count; i++) {
260
        reader.readElement("Geometry");
261
        const char* TypeName = reader.getAttribute("type");
262
        Geometry *newG = static_cast<Geometry *>(Base::Type::fromName(TypeName).createInstance());
263
        tryRestoreGeometry(newG, reader);
264

265
        if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) {
266
            Base::Console().Error("Geometry \"%s\" within a PropertyGeometryList was subject to a partial restore.\n",reader.localName());
267
            if(isOrderRelevant()) {
268
                // Pushes the best try by the Geometry class
269
                values.push_back(newG);
270
            }
271
            else {
272
                delete newG;
273
            }
274
            reader.clearPartialRestoreObject();
275
        }
276
        else {
277
            values.push_back(newG);
278
        }
279

280
        reader.readEndElement("Geometry");
281
    }
282

283
    reader.readEndElement("GeometryList");
284

285
    // assignment
286
    setValues(std::move(values));
287
}
288

289
App::Property *PropertyGeometryList::Copy() const
290
{
291
    PropertyGeometryList *p = new PropertyGeometryList();
292
    p->setValues(_lValueList);
293
    return p;
294
}
295

296
void PropertyGeometryList::Paste(const Property &from)
297
{
298
    const PropertyGeometryList& FromList = dynamic_cast<const PropertyGeometryList&>(from);
299
    setValues(FromList._lValueList);
300
}
301

302
unsigned int PropertyGeometryList::getMemSize() const
303
{
304
    int size = sizeof(PropertyGeometryList);
305
    for (int i = 0; i < getSize(); i++)
306
        size += _lValueList[i]->getMemSize();
307
    return size;
308
}
309

310
void PropertyGeometryList::moveValues(PropertyGeometryList &&other)
311
{
312
    setValues(std::move(other._lValueList));
313
}
314

315

316

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

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

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

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