FreeCAD

Форк
0
/
DlgAddProperty.cpp 
151 строка · 6.2 Кб
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> types;
58
    Base::Type::getAllDerivedFrom(Base::Type::fromName("App::Property"),types);
59
    std::sort(types.begin(), types.end(), [](Base::Type a, Base::Type b) { return strcmp(a.getName(), b.getName()) < 0; });
60

61
    for(const auto& type : types) {
62
        ui->comboType->addItem(QString::fromLatin1(type.getName()));
63
        if(type == defType)
64
            ui->comboType->setCurrentIndex(ui->comboType->count()-1);
65
    }
66

67
    ui->edtGroup->setText(QString::fromLatin1(
68
                hGrp->GetASCII("NewPropertyGroup","Base").c_str()));
69
    ui->chkAppend->setChecked(hGrp->GetBool("NewPropertyAppend",true));
70
}
71

72
/**
73
 *  Destroys the object and frees any allocated resources
74
 */
75
DlgAddProperty::~DlgAddProperty() = default;
76

77
static std::string containerName(const App::PropertyContainer *c) {
78
    auto doc = Base::freecad_dynamic_cast<App::Document>(c);
79
    if(doc)
80
        return doc->getName();
81
    auto obj = Base::freecad_dynamic_cast<App::DocumentObject>(c);
82
    if(obj)
83
        return obj->getFullName();
84
    auto vpd = Base::freecad_dynamic_cast<ViewProviderDocumentObject>(c);
85
    if(vpd)
86
        return vpd->getObject()->getFullName();
87
    return "?";
88
}
89

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

105
    if(ui->chkAppend->isChecked())
106
        name = group + "_" + name;
107

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

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

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

151
#include "moc_DlgAddProperty.cpp"
152

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

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

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

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