layoutmanagement.cpp 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
Copyright (C) 2012  Jean-Baptiste Mardelle <jb@kdenlive.org>
Copyright (C) 2014  Till Theato <root@ttill.de>
This file is part of kdenlive. See www.kdenlive.org.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/

#include "layoutmanagement.h"
#include "core.h"
#include "mainwindow.h"
#include <QInputDialog>
Nicolas Carion's avatar
Nicolas Carion committed
16
#include <QMenu>
17 18 19
#include <QDialog>
#include <QDialogButtonBox>
#include <QListWidget>
20 21
#include <QMenuBar>
#include <QButtonGroup>
22

23
#include <KConfigGroup>
24
#include <KColorScheme>
25
#include <KSharedConfig>
Nicolas Carion's avatar
Nicolas Carion committed
26
#include <KXMLGUIFactory>
27
#include <klocalizedstring.h>
28

29 30
LayoutManagement::LayoutManagement(QObject *parent)
    : QObject(parent)
31 32 33 34 35
{
    // Prepare layout actions
    KActionCategory *layoutActions = new KActionCategory(i18n("Layouts"), pCore->window()->actionCollection());
    m_loadLayout = new KSelectAction(i18n("Load Layout"), pCore->window()->actionCollection());
    // Required to enable user to add the load layout action to toolbar
36
    layoutActions->addAction(QStringLiteral("load_layouts"), m_loadLayout);
Nicolas Carion's avatar
Nicolas Carion committed
37
    connect(m_loadLayout, static_cast<void (KSelectAction::*)(QAction *)>(&KSelectAction::triggered), this, &LayoutManagement::slotLoadLayout);
38

39 40 41 42 43 44 45
    QAction *saveLayout = new QAction(i18n("Save Layout"), pCore->window()->actionCollection());
    layoutActions->addAction(QStringLiteral("save_layout"), saveLayout);
    connect(saveLayout, &QAction::triggered, this, &LayoutManagement::slotSaveLayout);
    
    QAction *manageLayout = new QAction(i18n("Manage Layouts"), pCore->window()->actionCollection());
    layoutActions->addAction(QStringLiteral("manage_layout"), manageLayout);
    connect(manageLayout, &QAction::triggered, this, &LayoutManagement::slotManageLayouts);
46 47 48 49 50
    // Create 9 layout actions
    for (int i = 1; i < 10; i++) {
        QAction *load = new QAction(QIcon(), QString(), this);
        m_layoutActions <<layoutActions->addAction("load_layout" + QString::number(i), load);
    }
51 52 53
    MainWindow *main = pCore->window();
    m_container = new QWidget(main);
    m_containerGrp = new QButtonGroup(m_container);
54
    connect(m_containerGrp, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &LayoutManagement::activateLayout);
55 56 57 58 59 60 61 62 63 64 65 66
    QVBoxLayout *l1 = new QVBoxLayout;
    l1->addStretch();
    m_containerLayout = new QHBoxLayout;
    m_containerLayout->setSpacing(0);
    m_containerLayout->setContentsMargins(0, 0, 0, 0);
    l1->addLayout(m_containerLayout);
    m_container->setLayout(l1);
    KColorScheme scheme(main->palette().currentColorGroup(), KColorScheme::Button);
    QColor bg = scheme.background(KColorScheme::AlternateBackground).color();
    QString style = QString("padding-left: %4; padding-right: %4;background-color: rgb(%1,%2,%3);").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(main->fontInfo().pixelSize()/2);
    m_container->setStyleSheet(style);
    main->menuBar()->setCornerWidget(m_container, Qt::TopRightCorner);
67
    initializeLayouts();
68 69
}

Till Theato's avatar
Till Theato committed
70
void LayoutManagement::initializeLayouts()
71
{
72
    if (m_loadLayout == nullptr) {
Laurent Montel's avatar
Laurent Montel committed
73 74
        return;
    }
75 76 77 78
    QString current;
    if (m_containerGrp->checkedButton()) {
        current = m_containerGrp->checkedButton()->text();
    }
79 80 81 82 83
    MainWindow *main = pCore->window();
    // Delete existing buttons
    while (auto item = m_containerLayout->takeAt(0)) {
      delete item->widget();
    }
84 85 86 87 88 89 90 91 92
    
    // Load default base layouts
    KConfig defaultConfig(QStringLiteral("kdenlivedefaultlayouts.rc"), KConfig::CascadeConfig, QStandardPaths::AppDataLocation);
    KConfigGroup defaultOrder(&defaultConfig, "Order");
    KConfigGroup defaultLayout(&defaultConfig, "Layouts");
    QStringList defaultLayouts;
    
    // Load User defined layouts
    KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kdenlive-layoutsrc"), KConfig::NoCascade);
93
    KConfigGroup layoutGroup(config, "Layouts");
94
    KConfigGroup layoutOrder(config, "Order");
95 96 97 98 99 100 101 102 103
    // If we don't have any layout saved, check in main config file
    if (!layoutGroup.exists()) {
        config = KSharedConfig::openConfig();
        KConfigGroup layoutGroup2(config, "Layouts");
        if (layoutGroup2.exists()) {
            // Migrate to new config file
            layoutGroup2.copyTo(&layoutGroup);
        }
    }
104 105 106 107
    if (!layoutGroup.exists()) {
        defaultLayout.copyTo(&layoutGroup);
        defaultOrder.copyTo(&layoutOrder);
    }
108
    m_loadLayout->removeAllActions();
109
    QStringList entries;
110
    bool addedDefault = false;
111 112 113 114
    if (!layoutOrder.exists()) {
        // This is an old or newly created config file, import defaults
        defaultLayouts = defaultOrder.entryMap().values();
        entries = layoutGroup.keyList();
115
        addedDefault = true;
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    } else {
        // User sorted list
        entries = layoutOrder.entryMap().values();
    }
    
    // Add default layouts to user config in they don't exist
    for (const QString &lay : defaultLayouts)
    {
        if (!entries.contains(lay)) {
            entries.insert(defaultLayouts.indexOf(lay), lay);
            layoutGroup.writeEntry(lay, defaultLayout.readEntry(lay));
            addedDefault = true;
        }
    }
    
    if (addedDefault) {
        // Write updated order
        layoutOrder.deleteGroup();
        int j = 1;
        for (const QString &entry : entries) {
            layoutOrder.writeEntry(QString::number(j), entry);
            j++;
        }
139
        config->reparseConfiguration();
140
    }
141 142 143 144 145 146 147 148 149 150 151
    for (int i = 1; i < 10; i++) {
        QString layoutName;
        if (i <= entries.count()) {
            layoutName = entries.at(i - 1);
        }
        QAction *load = m_layoutActions.at(i - 1);
        if (layoutName.isEmpty()) {
            load->setText(QString());
            load->setIcon(QIcon());
        } else {
            load->setText(i18n("Layout %1: %2", i, layoutName));
152
            if (i < 6) {
153
                QPushButton *lab = new QPushButton(layoutName, m_container);
154
                lab->setFocusPolicy(Qt::NoFocus);
155 156 157 158 159
                lab->setCheckable(true);
                lab->setFlat(true);
                lab->setFont(main->menuBar()->font());
                m_containerGrp->addButton(lab);
                m_containerLayout->addWidget(lab);
160 161 162
                if (!current.isEmpty() && current == layoutName) {
                    lab->setChecked(true);
                }
163
            }
164
        }
165
        load->setData(layoutName);
166 167 168 169 170 171
        if (!layoutName.isEmpty()) {
            load->setEnabled(true);
            m_loadLayout->addAction(load);
        } else {
            load->setEnabled(false);
        }
172
    }
173 174
    // Required to trigger a refresh of the container buttons
    main->menuBar()->resize(main->menuBar()->sizeHint());
175 176
}

177 178 179 180 181
void LayoutManagement::activateLayout(QAbstractButton *button)
{
    if (!button) {
        return;
    }
182
    loadLayout(button->text(), false);
183 184
}

185 186 187 188 189 190 191 192 193 194
void LayoutManagement::slotLoadLayout(QAction *action)
{
    if (!action) {
        return;
    }

    QString layoutId = action->data().toString();
    if (layoutId.isEmpty()) {
        return;
    }
195
    loadLayout(layoutId, true);
196 197
}

198
bool LayoutManagement::loadLayout(const QString &layoutId, bool selectButton)
199
{
200
    KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kdenlive-layoutsrc"));
201
    KConfigGroup layouts(config, "Layouts");
202 203
    if (!layouts.hasKey(layoutId)) {
        // Error, layout not found
204
        return false;
205
    }
206
    QByteArray state = QByteArray::fromBase64(layouts.readEntry(layoutId).toLatin1());
207 208 209 210 211 212
    bool timelineVisible = true;
    if (state.startsWith("NO-TL")) {
        timelineVisible = false;
        state.remove(0, 5);
    }
    pCore->window()->centralWidget()->setHidden(!timelineVisible);
213
    pCore->window()->restoreState(state);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    if (selectButton) {
        // Activate layout button
        QList<QAbstractButton *>buttons = m_containerGrp->buttons();
        bool buttonFound = false;
        for (auto *button : buttons) {
            if (button->text() == layoutId) {
                QSignalBlocker bk(m_containerGrp);
                button->setChecked(true);
                buttonFound = true;
            }
        }
        if (!buttonFound && m_containerGrp->checkedButton()) {
            m_containerGrp->setExclusive(false);
            m_containerGrp->checkedButton()->setChecked(false);
            m_containerGrp->setExclusive(true);
        }
    }
231
    return true;
232 233
}

234
void LayoutManagement::slotSaveLayout()
235
{
236 237 238 239 240 241
    QAbstractButton *button = m_containerGrp->checkedButton();
    QString saveName;
    if (button) {
        saveName = button->text();
    }
    QString layoutName = QInputDialog::getText(pCore->window(), i18n("Save Layout"), i18n("Layout name:"), QLineEdit::Normal, saveName);
242 243 244
    if (layoutName.isEmpty()) {
        return;
    }
245
    KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kdenlive-layoutsrc"));
246
    KConfigGroup layouts(config, "Layouts");
247
    KConfigGroup order(config, "Order");
248 249

    QByteArray st = pCore->window()->saveState();
250 251 252
    if (!pCore->window()->timelineVisible()) {
        st.prepend("NO-TL");
    }
253
    layouts.writeEntry(layoutName, st.toBase64());
254 255 256 257
    if (!order.entryMap().values().contains(layoutName)) {
        int pos = order.keyList().last().toInt() + 1;
        order.writeEntry(QString::number(pos), layoutName);
    }
258 259
    
    config->reparseConfiguration();
Till Theato's avatar
Till Theato committed
260
    initializeLayouts();
261 262 263 264 265 266 267 268
    // Activate layout button
    QList<QAbstractButton *>buttons = m_containerGrp->buttons();
    for (auto *button : buttons) {
        if (button->text() == layoutName) {
            QSignalBlocker bk(m_containerGrp);
            button->setChecked(true);
        }
    }
Till Theato's avatar
Till Theato committed
269 270
}

271
void LayoutManagement::slotManageLayouts()
Till Theato's avatar
Till Theato committed
272
{
273 274
    KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("kdenlive-layoutsrc"));
    KConfigGroup layouts(config, "Layouts");
275 276
    KConfigGroup order(config, "Order");
    QStringList names = order.entryMap().values();
277 278 279 280
    QString current;
    if (m_containerGrp->checkedButton()) {
        current = m_containerGrp->checkedButton()->text();
    }
281 282 283 284 285 286
    QDialog d(pCore->window());
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
    auto *l = new QVBoxLayout;
    d.setLayout(l);
    l->addWidget(new QLabel(i18n("Current Layouts"), &d));
    QListWidget list(&d);
287
    list.setAlternatingRowColors(true);
288
    l->addWidget(&list); 
289
    // Delete button
290 291 292
    QToolButton tb(&d);
    tb.setIcon(QIcon::fromTheme(QStringLiteral("edit-delete")));
    tb.setAutoRaise(true);
293
    connect(&tb, &QToolButton::clicked, [this, &layouts, &list]() {
294 295 296 297 298 299
        if (list.currentItem()) {
            layouts.deleteEntry(list.currentItem()->data(Qt::UserRole).toString());
            delete list.currentItem();
        }
    });
    tb.setToolTip(i18n("Delete Layout"));
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
    auto *l2 = new QHBoxLayout;
    l->addLayout(l2);
    l2->addWidget(&tb);
    // Up button
    QToolButton tb2(&d);
    tb2.setIcon(QIcon::fromTheme(QStringLiteral("go-up")));
    tb2.setAutoRaise(true);
    connect(&tb2, &QToolButton::clicked, [&list]() {
        if (list.currentItem() && list.currentRow() > 0) {
            int updatedRow = list.currentRow() - 1;
            QListWidgetItem *item = list.takeItem(list.currentRow());
            list.insertItem(updatedRow, item);
            list.setCurrentRow(updatedRow);
        }
    });
    l2->addWidget(&tb2);

     // Down button
    QToolButton tb3(&d);
    tb3.setIcon(QIcon::fromTheme(QStringLiteral("go-down")));
    tb3.setAutoRaise(true);
    connect(&tb3, &QToolButton::clicked, [&list]() {
        if (list.currentItem() && list.currentRow() < list.count() - 1) {
            int updatedRow = list.currentRow() + 1;
            QListWidgetItem *item = list.takeItem(list.currentRow());
            list.insertItem(updatedRow, item);
            list.setCurrentRow(updatedRow);
        }
    });
    l2->addWidget(&tb3);
    
    // Reset button
    QToolButton tb4(&d);
    tb4.setIcon(QIcon::fromTheme(QStringLiteral("view-refresh")));
    tb4.setAutoRaise(true);
    tb4.setToolTip(i18n("Reset"));
336
    connect(&tb4, &QToolButton::clicked, [this, &config, &list, &layouts, current]() {
337 338 339 340 341 342 343 344 345 346 347
        // Load default base layouts
        KConfig defaultConfig(QStringLiteral("kdenlivedefaultlayouts.rc"), KConfig::CascadeConfig, QStandardPaths::AppDataLocation);
        KConfigGroup defaultOrder(&defaultConfig, "Order");
        KConfigGroup defaultLayout(&defaultConfig, "Layouts");
        QStringList defaultLayoutNames = defaultOrder.entryMap().values();
        // Get list of current layouts
        QStringList currentNames;
        for (int i = 0; i < list.count(); i++) {
            currentNames << list.item(i)->data(Qt::UserRole).toString();
        }
        int pos = 0;
348 349 350 351 352
        // Reset selected layout if it is a default one
        if (list.currentItem()) {
            QString selectedName = list.currentItem()->data(Qt::UserRole).toString();
            if (defaultLayoutNames.contains(selectedName)) {
                layouts.writeEntry(selectedName, defaultLayout.readEntry(selectedName));
353 354 355 356
                if (!current.isEmpty() && selectedName == current) {
                    config->reparseConfiguration();
                    loadLayout(current, false);
                }
357 358 359 360
            }
        }

        // Re-add missing default layouts
361 362 363 364 365 366 367 368 369 370
        for (const QString &name : defaultLayoutNames) {
            if (!currentNames.contains(name)) {
                // Insert default layout
                QListWidgetItem *item = new QListWidgetItem(name);
                item->setData(Qt::UserRole, name);
                item->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
                list.insertItem(pos, item);
                // Write layout data
                layouts.writeEntry(name, defaultLayout.readEntry(name));
            }
371
            pos++;
372 373 374 375 376 377 378 379 380 381 382 383
        }
    });
    l2->addWidget(&tb4);
    
    connect(&list, &QListWidget::currentRowChanged, [&list, &tb2, &tb3] (int row) {
        tb2.setEnabled(row > 0);
        tb3.setEnabled(row < list.count() - 1);
    });

    l2->addStretch();
    
    // Add layouts to list
384 385 386 387
    for (const QString &name : names) {
        QListWidgetItem *item = new QListWidgetItem(name, &list);
        item->setData(Qt::UserRole, name);
        item->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
Till Theato's avatar
Till Theato committed
388
    }
389 390 391 392 393 394 395 396
    int ix = 0;
    if (!current.isEmpty()) {
        QList<QListWidgetItem *> res = list.findItems(current, Qt::MatchExactly);
        if (!res.isEmpty()) {
            ix = list.row(res.first());
        }
    }
    list.setCurrentRow(ix);
397 398 399 400 401 402
    l->addWidget(buttonBox);
    d.connect(buttonBox, &QDialogButtonBox::rejected, &d, &QDialog::reject);
    d.connect(buttonBox, &QDialogButtonBox::accepted, &d, &QDialog::accept);
    if (d.exec() != QDialog::Accepted) {
        return;
    }
403 404 405
    // Reset order
    order.deleteGroup();
    // Update order and new names
406 407
    for (int i = 0; i < list.count(); i++) {
        QListWidgetItem *item = list.item(i);
408
        order.writeEntry(QString::number(i + 1), item->text());
409 410 411 412 413
        if (item->text() != item->data(Qt::UserRole).toString() && !item->text().isEmpty()) {
            layouts.writeEntry(item->text(), layouts.readEntry(item->data(Qt::UserRole).toString()));
            layouts.deleteEntry(item->data(Qt::UserRole).toString());
        }
    }
414 415
    config->reparseConfiguration();
    initializeLayouts();
416
}