summaryrefslogtreecommitdiffstats
path: root/src/designer/src/lib/shared/qdesigner_promotion.cpp
blob: 08b2848fd79a033d8ebba3cbb24670c984273a3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdesigner_promotion_p.h"
#include "widgetdatabase_p.h"
#include "metadatabase_p.h"
#include "widgetdatabase_p.h"

#include <QtDesigner/abstractformeditor.h>
#include <QtDesigner/abstractformwindow.h>
#include <QtDesigner/abstractformwindowmanager.h>
#include <QtDesigner/abstractobjectinspector.h>
#include <QtDesigner/abstractwidgetbox.h>
#include <QtDesigner/abstractwidgetdatabase.h>

#include <QtCore/qmap.h>
#include <QtCore/qcoreapplication.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

namespace {
    // Return a set of on-promotable classes
    const QSet<QString> &nonPromotableClasses() {
        static QSet<QString> rc;
        if (rc.isEmpty()) {
            rc.insert(QStringLiteral("Line"));
            rc.insert(QStringLiteral("QAction"));
            rc.insert(QStringLiteral("Spacer"));
            rc.insert(QStringLiteral("QMainWindow"));
            rc.insert(QStringLiteral("QDialog"));
            rc.insert(QStringLiteral("QMdiArea"));
            rc.insert(QStringLiteral("QMdiSubWindow"));
        }
        return rc;
    }

    // Return widget database index of a promoted class or -1 with error message
    int promotedWidgetDataBaseIndex(const QDesignerWidgetDataBaseInterface *widgetDataBase,
                                                                 const QString &className,
                                                                 QString *errorMessage) {
        const int index = widgetDataBase->indexOfClassName(className);
        if (index == -1 || !widgetDataBase->item(index)->isPromoted()) {
            *errorMessage = QCoreApplication::tr("%1 is not a promoted class.").arg(className);
            return -1;
        }
        return index;
    }

    // Return widget database item of a promoted class or 0 with error message
    QDesignerWidgetDataBaseItemInterface *promotedWidgetDataBaseItem(const QDesignerWidgetDataBaseInterface *widgetDataBase,
                                                                     const QString &className,
                                                                     QString *errorMessage) {

        const int index =  promotedWidgetDataBaseIndex(widgetDataBase, className, errorMessage);
        if (index == -1)
            return nullptr;
        return widgetDataBase->item(index);
    }

    // extract class name from xml  "<widget class="QWidget" ...>". Quite a hack.
    QString classNameFromXml(QString xml) {
        static const QString tag = QStringLiteral("class=\"");
        const int pos = xml.indexOf(tag);
        if (pos == -1)
            return QString();
        xml.remove(0, pos + tag.size());
        const int closingPos = xml.indexOf(QLatin1Char('"'));
        if (closingPos == -1)
            return QString();
        xml.remove(closingPos, xml.size() - closingPos);
        return xml;
    }

    // return a list of class names in the scratch pad
    QStringList getScratchPadClasses(const QDesignerWidgetBoxInterface *wb) {
        QStringList rc;
        const int catCount =  wb->categoryCount();
        for (int c = 0; c <  catCount; c++) {
            const QDesignerWidgetBoxInterface::Category category = wb->category(c);
            if (category.type() == QDesignerWidgetBoxInterface::Category::Scratchpad) {
                const int widgetCount = category.widgetCount();
                for (int w = 0; w < widgetCount; w++) {
                    const QString className = classNameFromXml( category.widget(w).domXml());
                    if (!className.isEmpty())
                        rc += className;
                }
            }
        }
        return rc;
    }
}

static void markFormsDirty(const QDesignerFormEditorInterface *core)
{
    const QDesignerFormWindowManagerInterface *fwm = core->formWindowManager();
    for (int f = 0, count = fwm->formWindowCount(); f < count; ++f)
        fwm->formWindow(f)->setDirty(true);
}

namespace qdesigner_internal {

    QDesignerPromotion::QDesignerPromotion(QDesignerFormEditorInterface *core) :
        m_core(core)  {
    }

    bool  QDesignerPromotion::addPromotedClass(const QString &baseClass,
                                               const QString &className,
                                               const QString &includeFile,
                                               QString *errorMessage)
    {
        QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();
        const int baseClassIndex = widgetDataBase->indexOfClassName(baseClass);

        if (baseClassIndex == -1) {
            *errorMessage = QCoreApplication::tr("The base class %1 is invalid.").arg(baseClass);
            return false;
        }

        const int existingClassIndex = widgetDataBase->indexOfClassName(className);

        if (existingClassIndex != -1) {
            *errorMessage = QCoreApplication::tr("The class %1 already exists.").arg(className);
            return false;
        }
        // Clone derived item.
        QDesignerWidgetDataBaseItemInterface *promotedItem = WidgetDataBaseItem::clone(widgetDataBase->item(baseClassIndex));
        // Also inherit the container flag in case of QWidget-derived classes
        // as it is most likely intended for stacked pages.
        // set new props
        promotedItem->setName(className);
        promotedItem->setGroup(QCoreApplication::tr("Promoted Widgets"));
        promotedItem->setCustom(true);
        promotedItem->setPromoted(true);
        promotedItem->setExtends(baseClass);
        promotedItem->setIncludeFile(includeFile);
        widgetDataBase->append(promotedItem);
        markFormsDirty(m_core);
        return true;
    }

    QList<QDesignerWidgetDataBaseItemInterface *> QDesignerPromotion::promotionBaseClasses() const
    {
        using SortedDatabaseItemMap = QMap<QString, QDesignerWidgetDataBaseItemInterface *>;
        SortedDatabaseItemMap sortedDatabaseItemMap;

        QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();

        const int cnt = widgetDataBase->count();
        for (int i = 0; i <  cnt; i++) {
            QDesignerWidgetDataBaseItemInterface *dbItem = widgetDataBase->item(i);
            if (canBePromoted(dbItem)) {
                sortedDatabaseItemMap.insert(dbItem->name(), dbItem);
            }
        }

        return sortedDatabaseItemMap.values();
    }


    bool QDesignerPromotion::canBePromoted(const QDesignerWidgetDataBaseItemInterface *dbItem) const
    {
        if (dbItem->isPromoted() ||  !dbItem->extends().isEmpty())
            return false;

        const QString name = dbItem->name();

        if (nonPromotableClasses().contains(name))
            return false;

        if (name.startsWith(QStringLiteral("QDesigner")) ||
            name.startsWith(QStringLiteral("QLayout")))
            return false;

        return true;
    }

    QDesignerPromotion::PromotedClasses QDesignerPromotion::promotedClasses()  const
    {
        using ClassNameItemMap = QMap<QString, QDesignerWidgetDataBaseItemInterface *>;
        // A map containing base classes and their promoted classes.
        using BaseClassPromotedMap = QMap<QString, ClassNameItemMap>;

        BaseClassPromotedMap baseClassPromotedMap;

        QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();
        // Look for promoted classes and insert into map according to base class.
        const  int cnt = widgetDataBase->count();
        for (int i = 0; i < cnt; i++) {
            QDesignerWidgetDataBaseItemInterface *dbItem = widgetDataBase->item(i);
            if (dbItem->isPromoted()) {
                const QString baseClassName = dbItem->extends();
                BaseClassPromotedMap::iterator it = baseClassPromotedMap.find(baseClassName);
                if (it == baseClassPromotedMap.end()) {
                    it = baseClassPromotedMap.insert(baseClassName, ClassNameItemMap());
                }
                it.value().insert(dbItem->name(), dbItem);
            }
        }
        // convert map into list.
        PromotedClasses rc;

        if (baseClassPromotedMap.isEmpty())
            return rc;

        const BaseClassPromotedMap::const_iterator bcend = baseClassPromotedMap.constEnd();
        for (BaseClassPromotedMap::const_iterator bit = baseClassPromotedMap.constBegin(); bit !=  bcend; ++bit) {
            const int baseIndex = widgetDataBase->indexOfClassName(bit.key());
            Q_ASSERT(baseIndex >= 0);
            QDesignerWidgetDataBaseItemInterface *baseItem = widgetDataBase->item(baseIndex);
            // promoted
            const ClassNameItemMap::const_iterator pcend = bit.value().constEnd();
            for (ClassNameItemMap::const_iterator pit = bit.value().constBegin(); pit != pcend; ++pit) {
                PromotedClass item;
                item.baseItem = baseItem;
                item.promotedItem = pit.value();
                rc.push_back(item);
            }
        }

        return rc;
    }

    QSet<QString> QDesignerPromotion::referencedPromotedClassNames()  const {
        QSet<QString> rc;
        const MetaDataBase *metaDataBase = qobject_cast<const MetaDataBase*>(m_core->metaDataBase());
        if (!metaDataBase)
            return rc;

        const QObjectList &objects = metaDataBase->objects();
        for (QObject *object : objects) {
            const QString customClass = metaDataBase->metaDataBaseItem(object)->customClassName();
            if (!customClass.isEmpty())
                rc.insert(customClass);

        }
        // check the scratchpad of the widget box
        if (QDesignerWidgetBoxInterface *widgetBox = m_core->widgetBox()) {
            const QStringList scratchPadClasses = getScratchPadClasses(widgetBox);
            if (!scratchPadClasses.isEmpty()) {
                // Check whether these are actually promoted
                QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();
                QStringList::const_iterator cend = scratchPadClasses.constEnd();
                for (QStringList::const_iterator it = scratchPadClasses.constBegin(); it != cend; ++it ) {
                    const int index = widgetDataBase->indexOfClassName(*it);
                    if (index != -1 && widgetDataBase->item(index)->isPromoted())
                        rc += *it;
                }
            }
        }
        return rc;
    }

    bool QDesignerPromotion::removePromotedClass(const QString &className, QString *errorMessage) {
        // check if it exists and is promoted
        WidgetDataBase *widgetDataBase = qobject_cast<WidgetDataBase *>(m_core->widgetDataBase());
        if (!widgetDataBase) {
            *errorMessage = QCoreApplication::tr("The class %1 cannot be removed").arg(className);
            return false;
        }

        const int index = promotedWidgetDataBaseIndex(widgetDataBase, className, errorMessage);
        if (index == -1)
            return false;

        if (referencedPromotedClassNames().contains(className)) {
            *errorMessage = QCoreApplication::tr("The class %1 cannot be removed because it is still referenced.").arg(className);
            return false;
        }
        // QTBUG-52963: Check for classes that specify the to-be-removed class as
        // base class of a promoted class. This should not happen in the normal case
        // as promoted classes cannot serve as base for further promotion. It is possible
        // though if a class provided by a plugin (say Qt WebKit's QWebView) is used as
        // a base class for a promoted widget B and the plugin is removed in the next
        // launch. QWebView will then appear as promoted class itself and the promoted
        // class B will depend on it. When removing QWebView, the base class of B will
        // be changed to that of QWebView by the below code.
        const PromotedClasses promotedList = promotedClasses();
        for (PromotedClasses::const_iterator it = promotedList.constBegin(), end = promotedList.constEnd(); it != end; ++it) {
            if (it->baseItem->name() == className) {
                const QString extends = widgetDataBase->item(index)->extends();
                qWarning().nospace() << "Warning: Promoted class " << it->promotedItem->name()
                    << " extends " << className << ", changing its base class to " <<  extends << '.';
                it->promotedItem->setExtends(extends);
            }
        }
        widgetDataBase->remove(index);
        markFormsDirty(m_core);
        return true;
    }

    bool QDesignerPromotion::changePromotedClassName(const QString &oldclassName, const QString &newClassName, QString *errorMessage) {
        const MetaDataBase *metaDataBase = qobject_cast<const MetaDataBase*>(m_core->metaDataBase());
        if (!metaDataBase) {
            *errorMessage = QCoreApplication::tr("The class %1 cannot be renamed").arg(oldclassName);
            return false;
        }
        QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();

        // check the new name
        if (newClassName.isEmpty()) {
            *errorMessage = QCoreApplication::tr("The class %1 cannot be renamed to an empty name.").arg(oldclassName);
            return false;
        }
        const int existingIndex = widgetDataBase->indexOfClassName(newClassName);
        if (existingIndex != -1) {
            *errorMessage = QCoreApplication::tr("There is already a class named %1.").arg(newClassName);
            return false;
        }
        // Check old class
        QDesignerWidgetDataBaseItemInterface *dbItem = promotedWidgetDataBaseItem(widgetDataBase, oldclassName, errorMessage);
        if (!dbItem)
            return false;

        // Change the name in the data base and change all referencing objects in the meta database
        dbItem->setName(newClassName);
        bool foundReferences = false;
        const QObjectList &dbObjects = metaDataBase->objects();
        for (QObject* object : dbObjects) {
            MetaDataBaseItem *item =  metaDataBase->metaDataBaseItem(object);
            Q_ASSERT(item);
            if (item->customClassName() == oldclassName) {
                item->setCustomClassName(newClassName);
                foundReferences = true;
            }
        }
        // set state
        if (foundReferences)
            refreshObjectInspector();

        markFormsDirty(m_core);
        return true;
    }

    bool QDesignerPromotion::setPromotedClassIncludeFile(const QString &className, const QString &includeFile, QString *errorMessage) {
        // check file
        if (includeFile.isEmpty()) {
            *errorMessage = QCoreApplication::tr("Cannot set an empty include file.");
            return false;
        }
        // check item
        QDesignerWidgetDataBaseInterface *widgetDataBase = m_core->widgetDataBase();
        QDesignerWidgetDataBaseItemInterface *dbItem = promotedWidgetDataBaseItem(widgetDataBase, className, errorMessage);
        if (!dbItem)
            return false;
        if (dbItem->includeFile() != includeFile) {
            dbItem->setIncludeFile(includeFile);
            markFormsDirty(m_core);
        }
        return true;
    }

    void QDesignerPromotion::refreshObjectInspector() {
        if (QDesignerFormWindowManagerInterface *fwm = m_core->formWindowManager()) {
            if (QDesignerFormWindowInterface *fw = fwm->activeFormWindow())
                if ( QDesignerObjectInspectorInterface *oi = m_core->objectInspector()) {
                    oi->setFormWindow(fw);
                }
        }
    }
}

QT_END_NAMESPACE