FreeCAD

Форк
0
/
DlgAddProperty.cpp 
157 строк · 6.4 Кб
1
/****************************************************************************
2
 *   Copyright (c) 2019 Zheng Lei (realthunder) <realthunder.dev@gmail.com> *
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
#ifndef _PreComp_
25
# include <QMessageBox>
26
#endif
27

28
#include <App/Application.h>
29
#include <App/Document.h>
30
#include <App/DocumentObject.h>
31
#include <Base/Tools.h>
32

33
#include "DlgAddProperty.h"
34
#include "ui_DlgAddProperty.h"
35
#include "MainWindow.h"
36
#include "ViewProviderDocumentObject.h"
37

38

39
using namespace Gui;
40
using namespace Gui::Dialog;
41

42
DlgAddProperty::DlgAddProperty(QWidget* parent,
43
        std::unordered_set<App::PropertyContainer *> &&c)
44
  : QDialog( parent )
45
  , containers(std::move(c))
46
  , ui(new Ui_DlgAddProperty)
47
{
48
    ui->setupUi(this);
49

50
    auto hGrp = App::GetApplication().GetParameterGroupByPath(
51
            "User parameter:BaseApp/Preferences/PropertyView");
52
    auto defType = Base::Type::fromName(
53
            hGrp->GetASCII("NewPropertyType","App::PropertyString").c_str());
54
    if(defType.isBad())
55
        defType = App::PropertyString::getClassTypeId();
56

57
    std::vector<Base::Type> proptypes;
58
    std::vector<Base::Type> types;
59
    Base::Type::getAllDerivedFrom(Base::Type::fromName("App::Property"), proptypes);
60
    std::copy_if (proptypes.begin(), proptypes.end(), std::back_inserter(types), [](const Base::Type& type) {
61
        return type.canInstantiate();
62
    });
63
    std::sort(types.begin(), types.end(), [](Base::Type a, Base::Type b) {
64
        return strcmp(a.getName(), b.getName()) < 0;
65
    });
66

67
    for(const auto& type : types) {
68
        ui->comboType->addItem(QString::fromLatin1(type.getName()));
69
        if(type == defType)
70
            ui->comboType->setCurrentIndex(ui->comboType->count()-1);
71
    }
72

73
    ui->edtGroup->setText(QString::fromLatin1(
74
                hGrp->GetASCII("NewPropertyGroup","Base").c_str()));
75
    ui->chkAppend->setChecked(hGrp->GetBool("NewPropertyAppend",true));
76
}
77

78
/**
79
 *  Destroys the object and frees any allocated resources
80
 */
81
DlgAddProperty::~DlgAddProperty() = default;
82

83
static std::string containerName(const App::PropertyContainer *c) {
84
    auto doc = Base::freecad_dynamic_cast<App::Document>(c);
85
    if(doc)
86
        return doc->getName();
87
    auto obj = Base::freecad_dynamic_cast<App::DocumentObject>(c);
88
    if(obj)
89
        return obj->getFullName();
90
    auto vpd = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(c);
91
    if(vpd)
92
        return vpd->getObject()->getFullName();
93
    return "?";
94
}
95

96
void DlgAddProperty::accept()
97
{
98
    std::string name = ui->edtName->text().toUtf8().constData();
99
    std::string group = ui->edtGroup->text().toUtf8().constData();
100
    if(name.empty() || group.empty()
101
            || name != Base::Tools::getIdentifier(name)
102
            || group != Base::Tools::getIdentifier(group))
103
    {
104
        QMessageBox::critical(getMainWindow(),
105
            QObject::tr("Invalid name"),
106
            QObject::tr("The property name or group name must only contain alpha numericals,\n"
107
                        "underscore, and must not start with a digit."));
108
        return;
109
    }
110

111
    if(ui->chkAppend->isChecked())
112
        name = group + "_" + name;
113

114
    for(auto c : containers) {
115
        auto prop = c->getPropertyByName(name.c_str());
116
        if(prop && prop->getContainer() == c) {
117
            QMessageBox::critical(getMainWindow(),
118
                QObject::tr("Invalid name"),
119
                QObject::tr("The property '%1' already exists in '%2'").arg(
120
                    QString::fromLatin1(name.c_str()),
121
                    QString::fromLatin1(containerName(c).c_str())));
122
            return;
123
        }
124
    }
125

126
    std::string type = ui->comboType->currentText().toLatin1().constData();
127

128
    for(auto it=containers.begin();it!=containers.end();++it) {
129
        try {
130
            (*it)->addDynamicProperty(type.c_str(),name.c_str(),
131
                    group.c_str(),ui->edtDoc->toPlainText().toUtf8().constData());
132
        } catch(Base::Exception &e) {
133
            e.ReportException();
134
            for(auto it2=containers.begin();it2!=it;++it2) {
135
                try {
136
                    (*it2)->removeDynamicProperty(name.c_str());
137
                } catch(Base::Exception &e) {
138
                    e.ReportException();
139
                }
140
            }
141
            QMessageBox::critical(getMainWindow(),
142
                QObject::tr("Add property"),
143
                QObject::tr("Failed to add property to '%1': %2").arg(
144
                    QString::fromLatin1(containerName(*it).c_str()),
145
                    QString::fromUtf8(e.what())));
146
            return;
147
        }
148
    }
149
    auto hGrp = App::GetApplication().GetParameterGroupByPath(
150
            "User parameter:BaseApp/Preferences/PropertyView");
151
    hGrp->SetASCII("NewPropertyType",type.c_str());
152
    hGrp->SetASCII("NewPropertyGroup",group.c_str());
153
    hGrp->SetBool("NewPropertyAppend",ui->chkAppend->isChecked());
154
    QDialog::accept();
155
}
156

157
#include "moc_DlgAddProperty.cpp"
158

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

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

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

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