File: kuiviewer_part.cpp

package info (click to toggle)
kde-dev-utils 4%3A25.04.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 828 kB
  • sloc: cpp: 605; xml: 332; sh: 4; makefile: 3
file content (337 lines) | stat: -rw-r--r-- 9,963 bytes parent folder | download
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
/*
    SPDX-FileCopyrightText: 2003 Richard Moore <rich@kde.org>
    SPDX-FileCopyrightText: 2003 Ian Reinhart Geiser <geiseri@kde.org>
    SPDX-FileCopyrightText: 2017 Friedrich W. H. Kossebau <kossebau@kde.org>

    SPDX-License-Identifier: LGPL-2.0-only
*/

#define TRANSLATION_DOMAIN "kuiviewer"

#include "kuiviewer_part.h"

// part
#include <kuiviewer_part_debug.h>
#include "kuiviewer_version.h"
// KF
#include <KActionCollection>
#include <KSelectAction>
#include <KConfig>
#include <KConfigGroup>
#include <KSharedConfig>
#include <KLocalizedString>
#include <KPluginMetaData>
#include <KPluginFactory>

// Qt
#include <QApplication>
#include <QClipboard>
#include <QFile>
#include <QFormBuilder>
#include <QStyle>
#include <QStyleFactory>
#include <QScrollArea>
#include <QMdiArea>
#include <QMdiSubWindow>
#include <QMimeDatabase>
#include <QBuffer>


K_PLUGIN_FACTORY_WITH_JSON(KUIViewerPartFactory, "kuiviewer_part.json",
                           registerPlugin<KUIViewerPart>();)

KUIViewerPart::KUIViewerPart(QWidget* parentWidget,
                             QObject* parent,
                             const KPluginMetaData& metaData,
                             const QVariantList& /*args*/)
    : KParts::ReadOnlyPart(parent, metaData)
    , m_subWindow(nullptr)
    , m_view(nullptr)
{
    // this should be your custom internal widget
    m_widget = new QMdiArea(parentWidget);
    m_widget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_widget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // notify the part that this is our internal widget
    setWidget(m_widget);

    // set our XML-UI resource file
    setXMLFile(QStringLiteral("kuiviewer_part.rc"));

    m_style = actionCollection()->add<KSelectAction>(QStringLiteral("change_style"));
    m_style->setText(i18n("Style"));
    connect(m_style, &KSelectAction::indexTriggered,
            this, &KUIViewerPart::slotStyle);
    //m_style->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
    m_style->setEditable(false);

    m_styleFromConfig = KConfigGroup(KSharedConfig::openConfig(), QStringLiteral("General")).readEntry("currentWidgetStyle", QString());

    const QStringList styles = QStyleFactory::keys();
    m_style->setItems(QStringList(i18nc("Default style", "Default")) + styles);
    m_style->setCurrentItem(0);

    // empty or incorrect value  means the default value of currentWidgetStyle,
    // which leads to the Default option.
    if (!m_styleFromConfig.isEmpty()) {
        QStringList::ConstIterator it = styles.begin();
        QStringList::ConstIterator end = styles.end();

        // Skip the default item
        int idx = 1;
        for (; it != end; ++it, ++idx) {
            if ((*it).toLower() == m_styleFromConfig.toLower()) {
                m_style->setCurrentItem(idx);
                break;
            }
        }
    }

    m_style->setToolTip(i18n("Set the style used for the view."));
    m_style->setMenuAccelsEnabled(true);

    m_copy = KStandardAction::copy(this, &KUIViewerPart::slotGrab, actionCollection());
    m_copy->setText(i18n("Copy as Image"));

    updateActions();

// Commented out to fix warning (rich)
// slot should probably be called saveAs() for consistency with
// KParts::ReadWritePart BTW.
//    KStandardAction::saveAs(this, SLOT(slotSave()), actionCollection());
}

KUIViewerPart::~KUIViewerPart()
{
}

static QStringList designerPluginPaths()
{
    QStringList paths;
    const QStringList& libraryPaths = QApplication::libraryPaths();
    for (const auto& path : libraryPaths) {
        paths.append(path + QLatin1String("/designer"));
    }
    return paths;
}

bool KUIViewerPart::openFile()
{
    // m_file is always local so we can use QFile on it
    QFile file(localFilePath());

    return loadUiFile(&file);
}

bool KUIViewerPart::doOpenStream(const QString& mimeType)
{
    auto mime = QMimeDatabase().mimeTypeForName(mimeType);
    if (!mime.inherits(QStringLiteral("application/x-designer"))) {
        return false;
    }

    m_streamedData.clear();

    return true;
}

bool KUIViewerPart::doWriteStream(const QByteArray& data)
{
    m_streamedData.append(data);
    return true;
}

bool KUIViewerPart::doCloseStream()
{
    QBuffer buffer(&m_streamedData);

    const auto success = loadUiFile(&buffer);
    m_streamedData.clear();

    return success;
}

bool KUIViewerPart::loadUiFile(QIODevice* device)
{
    if (!device->open(QIODevice::ReadOnly|QIODevice::Text)) {
        qCDebug(KUIVIEWERPART) << "Could not open UI file: " << device->errorString();
        if (m_previousUrl != url()) {
            // drop previous view state
            m_previousScrollPosition = QPoint();
            m_previousSize = QSize();
        }
        return false;
    }

    if (m_subWindow) {
        m_widget->removeSubWindow(m_subWindow);
        delete m_view;
        delete m_subWindow;
        m_subWindow = nullptr;
    }

    QFormBuilder builder;
    builder.setPluginPath(designerPluginPaths());
    m_view = builder.load(device, nullptr);

    updateActions();

    if (!m_view) {
        qCDebug(KUIVIEWERPART) << "Could not load UI file: " << builder.errorString();
        if (m_previousUrl != url()) {
            // drop previous view state
            m_previousScrollPosition = QPoint();
            m_previousSize = QSize();
        }
        return false;
    }

    // hack ahead:
    // UI files have a size set for the widget they define. The QMdiSubWindow relies on sizeHint()
    // during the show event though it seems, to calculate the initial window size, and then discards
    // the widget size initially set from the builder in the following layout-ruled geometry update.
    // Enforcing the initial size by manually setting it afterwards to the widget itself seems not possible,
    // due to the layout government based on window size.
    // To inject the initial widget size into the initial window geometry, as hack the min and max sizes are
    // temporarily set to the wanted size and, once the window is shown, reset to their initial values.
    const QSize widgetSize = m_view->size();
    const QSize origWidgetMinimumSize = m_view->minimumSize();
    const QSize origWidgetMaximumSize = m_view->maximumSize();
    restyleView(m_style->currentText());
    m_view->setMinimumSize(widgetSize);
    m_view->setMaximumSize(widgetSize);

    const Qt::WindowFlags windowFlags(Qt::SubWindow|Qt::CustomizeWindowHint|Qt::WindowTitleHint);
    m_subWindow = m_widget->addSubWindow(m_view, windowFlags);
    // prevent focus stealing by adding the window in disabled state
    m_subWindow->setEnabled(false);
    m_subWindow->show();
    // and restore minimum size
    m_view->setMinimumSize(origWidgetMinimumSize);
    m_view->setMaximumSize(origWidgetMaximumSize);

    m_widget->setActiveSubWindow(m_subWindow);
    m_subWindow->setEnabled(true);

    // restore view state if reload
    if (url() == m_previousUrl) {
        qCDebug(KUIVIEWERPART) << "Restoring previous view state";
        m_subWindow->move(m_previousScrollPosition);
        if (m_previousSize.isValid()) {
            m_subWindow->resize(m_previousSize);
        }
    }

    return true;
}

bool KUIViewerPart::closeUrl()
{
    // store view state if file could be loaded
    // otherwise keep old in case same url will get reloaded again and then successfully
    if (m_subWindow) {
        m_previousScrollPosition = m_subWindow->pos();
        m_previousSize = m_subWindow->size();
    }
    // store last used url
    const auto activeUrl = url();
    if (activeUrl.isValid()) {
        m_previousUrl = activeUrl;
    }

    m_streamedData.clear();

    return ReadOnlyPart::closeUrl();
}

void KUIViewerPart::updateActions()
{
    const bool hasView = !m_view.isNull();

    m_style->setEnabled(hasView);
    m_copy->setEnabled(hasView);
}

void KUIViewerPart::restyleView(const QString& styleName)
{
    QStyle* style = QStyleFactory::create(styleName);

    m_view->setStyle(style);

    const QList<QWidget*> childWidgets = m_view->findChildren<QWidget*>();
    for (auto child : childWidgets) {
        child->setStyle(style);
    }
}

void KUIViewerPart::setWidgetSize(const QSize& size)
{
    if (m_view.isNull()) {
        return;
    }

    // hack: enforce widget size by setting min/max sizes to wanted size
    // and then have layout update the complete window
    const QSize origWidgetMinimumSize = m_view->minimumSize();
    const QSize origWidgetMaximumSize = m_view->maximumSize();
    m_view->setMinimumSize(size);
    m_view->setMaximumSize(size);
    m_subWindow->updateGeometry();
    // restore
    m_view->setMinimumSize(origWidgetMinimumSize);
    m_view->setMaximumSize(origWidgetMaximumSize);
}

QPixmap KUIViewerPart::renderWidgetAsPixmap() const
{
    if (m_view.isNull()) {
        return QPixmap();
    }

    return m_view->grab();
}

void KUIViewerPart::slotStyle(int)
{
    if (m_view.isNull()) {
        updateActions();
        return;
    }

    m_view->hide();

    const QString styleName = m_style->currentText();
    qCDebug(KUIVIEWERPART) << "Style selected:" << styleName;
    restyleView(styleName);

    m_view->show();

    /* the style changed, update the configuration */
    if (m_styleFromConfig != styleName) {
        KSharedConfig::Ptr cfg = KSharedConfig::openConfig();
        KConfigGroup cg(cfg, QStringLiteral("General"));
        if (m_style->currentItem() > 0) {
            /* A style different from the default */
            cg.writeEntry("currentWidgetStyle", styleName);
        } else {
            /* default style: remove the entry */
            cg.deleteEntry("currentWidgetStyle");
        }
        cfg->sync();
    }
}

void KUIViewerPart::slotGrab()
{
    if (m_view.isNull()) {
        updateActions();
        return;
    }

    const QPixmap pixmap = m_view->grab();
    QApplication::clipboard()->setPixmap(pixmap);
}

#include "kuiviewer_part.moc"
#include "moc_kuiviewer_part.cpp"