renderwidget.cpp 120 KB
Newer Older
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/***************************************************************************
 *   Copyright (C) 2008 by Jean-Baptiste Mardelle (jb@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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

20
#include "renderwidget.h"
Nicolas Carion's avatar
Nicolas Carion committed
21
#include "dialogs/profilesdialog.h"
22
#include "kdenlivesettings.h"
Nicolas Carion's avatar
Nicolas Carion committed
23 24
#include "profiles/profilemodel.hpp"
#include "profiles/profilerepository.hpp"
25
#include "timecode.h"
Nicolas Carion's avatar
Nicolas Carion committed
26
#include "ui_saveprofile_ui.h"
27
#include "utils/KoIconUtils.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
28

29
#include "klocalizedstring.h"
30
#include <KColorScheme>
31
#include <KIO/DesktopExecParser>
Nicolas Carion's avatar
Nicolas Carion committed
32 33 34 35
#include <KMessageBox>
#include <KMimeTypeTrader>
#include <KNotification>
#include <KRun>
36
#include <knotifications_version.h>
37

Laurent Montel's avatar
Laurent Montel committed
38
#include "kdenlive_debug.h"
Nicolas Carion's avatar
Nicolas Carion committed
39 40
#include <QDBusConnectionInterface>
#include <QDir>
41 42 43
#include <QDomDocument>
#include <QHeaderView>
#include <QInputDialog>
Nicolas Carion's avatar
Nicolas Carion committed
44 45
#include <QKeyEvent>
#include <QMimeDatabase>
46
#include <QProcess>
47
#include <QScriptEngine>
48
#include <QStandardPaths>
Nicolas Carion's avatar
Nicolas Carion committed
49 50 51 52 53
#include <QThread>
#include <QTimer>
#include <QTreeWidgetItem>
#include <qglobal.h>
#include <qstring.h>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
54

Vincent Pinon's avatar
Vincent Pinon committed
55
#include <locale>
56 57 58
#ifdef Q_OS_MAC
#include <xlocale.h>
#endif
59

60
// Render profiles roles
Nicolas Carion's avatar
Nicolas Carion committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
enum {
    GroupRole = Qt::UserRole,
    ExtensionRole,
    StandardRole,
    RenderRole,
    ParamsRole,
    EditableRole,
    ExtraRole,
    BitratesRole,
    DefaultBitrateRole,
    AudioBitratesRole,
    DefaultAudioBitrateRole,
    SpeedsRole,
    ErrorRole
};
76

77 78 79
// Render job roles
const int ParametersRole = Qt::UserRole + 1;
const int TimeRole = Qt::UserRole + 2;
80 81
const int ProgressRole = Qt::UserRole + 3;
const int ExtraInfoRole = Qt::UserRole + 5;
82

83 84
const int DirectRenderType = QTreeWidgetItem::Type;
const int ScriptRenderType = QTreeWidgetItem::UserType;
85

86
// Running job status
Nicolas Carion's avatar
Nicolas Carion committed
87
enum JOBSTATUS { WAITINGJOB = 0, STARTINGJOB, RUNNINGJOB, FINISHEDJOB, FAILEDJOB, ABORTEDJOB };
88

89 90 91
static QStringList acodecsList;
static QStringList vcodecsList;
static QStringList supportedFormats;
92

Nicolas Carion's avatar
Nicolas Carion committed
93
RenderJobItem::RenderJobItem(QTreeWidget *parent, const QStringList &strings, int type) : QTreeWidgetItem(parent, strings, type), m_status(-1)
94
{
95
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
96 97 98 99 100
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
101
    if (m_status == status) {
Laurent Montel's avatar
Laurent Montel committed
102
        return;
103
    }
104 105
    m_status = status;
    switch (status) {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    case WAITINGJOB:
        setIcon(0, KoIconUtils::themedIcon(QStringLiteral("media-playback-pause")));
        setData(1, Qt::UserRole, i18n("Waiting..."));
        break;
    case FINISHEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering finished"));
        setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-ok")));
        setData(1, ProgressRole, 100);
        break;
    case FAILEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering crashed"));
        setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-close")));
        setData(1, ProgressRole, 100);
        break;
    case ABORTEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering aborted"));
        setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-cancel")));
        setData(1, ProgressRole, 100);
    default:
        break;
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    }
}

int RenderJobItem::status() const
{
    return m_status;
}

void RenderJobItem::setMetadata(const QString &data)
{
    m_data = data;
}

const QString RenderJobItem::metadata() const
{
    return m_data;
}
143

Nicolas Carion's avatar
Nicolas Carion committed
144 145
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const QString &profile, QWidget *parent)
    : QDialog(parent), m_projectFolder(projectfolder), m_profile(profile), m_blockProcessing(false)
146
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
147
    m_view.setupUi(this);
148 149
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
150

151
    setWindowTitle(i18n("Rendering"));
152 153 154 155
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
156

157
    m_view.buttonDelete->setIcon(KoIconUtils::themedIcon(QStringLiteral("trash-empty")));
158 159 160
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

161
    m_view.buttonEdit->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-edit")));
162 163 164
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

165
    m_view.buttonSave->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-new")));
166 167
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

168
    m_view.hide_log->setIcon(KoIconUtils::themedIcon(QStringLiteral("go-down")));
169

170
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
171
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
172

173
    m_view.out_file->button()->setToolTip(i18n("Select output destination"));
174
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
175

176
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
177
    connect(m_view.options, &QAbstractButton::toggled, m_view.optionsGroup, &QWidget::setVisible);
178
    m_view.videoLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
179
    connect(m_view.options, &QAbstractButton::toggled, m_view.videoLabel, &QWidget::setVisible);
180
    m_view.video->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
181
    connect(m_view.options, &QAbstractButton::toggled, m_view.video, &QWidget::setVisible);
182
    m_view.audioLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
183
    connect(m_view.options, &QAbstractButton::toggled, m_view.audioLabel, &QWidget::setVisible);
184
    m_view.audio->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
185 186
    connect(m_view.options, &QAbstractButton::toggled, m_view.audio, &QWidget::setVisible);
    connect(m_view.quality, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustAVQualities);
187
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
Laurent Montel's avatar
Laurent Montel committed
188
    connect(m_view.speed, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustSpeed);
189

190 191
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
192
    setRescaleEnabled(false);
193 194 195 196 197 198 199
    m_view.guides_box->setVisible(false);
    m_view.open_dvd->setVisible(false);
    m_view.create_chapter->setVisible(false);
    m_view.open_browser->setVisible(false);
    m_view.error_box->setVisible(false);
    m_view.tc_type->setEnabled(false);
    m_view.checkTwoPass->setEnabled(false);
200
    m_view.proxy_render->setHidden(!enableProxy);
201
    connect(m_view.proxy_render, &QCheckBox::toggled, this, &RenderWidget::slotProxyWarn);
202 203
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
Nicolas Carion's avatar
Nicolas Carion committed
204 205
    m_view.errorBox->setStyleSheet(
        QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
206
    int height = QFontInfo(font()).pixelSize();
207
    m_view.errorIcon->setPixmap(KoIconUtils::themedIcon(QStringLiteral("dialog-warning")).pixmap(height, height));
208 209 210
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
211
    m_view.info->addWidget(m_infoMessage);
212 213 214
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

215 216 217 218
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
    connect(m_view.encoder_threads, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateEncodeThreads(int)));

219 220 221
    m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
    connect(m_view.rescale_width, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleWidth(int)));
    connect(m_view.rescale_height, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleHeight(int)));
222
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
223
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
Laurent Montel's avatar
Laurent Montel committed
224
    connect(m_view.rescale_keep, &QAbstractButton::clicked, this, &RenderWidget::slotSwitchAspectRatio);
225

226
    connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
Laurent Montel's avatar
Laurent Montel committed
227
    connect(m_view.buttonGenerateScript, &QAbstractButton::clicked, this, &RenderWidget::slotGenerateScript);
228

229 230 231 232
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

Laurent Montel's avatar
Laurent Montel committed
233
    connect(m_view.export_audio, &QCheckBox::stateChanged, this, &RenderWidget::slotUpdateAudioLabel);
234 235
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

236
    parseProfiles();
237
    parseScriptFiles();
238 239
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
Laurent Montel's avatar
Laurent Montel committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    connect(m_view.start_script, &QAbstractButton::clicked, this, &RenderWidget::slotStartScript);
    connect(m_view.delete_script, &QAbstractButton::clicked, this, &RenderWidget::slotDeleteScript);
    connect(m_view.scripts_list, &QTreeWidget::itemSelectionChanged, this, &RenderWidget::slotCheckScript);
    connect(m_view.running_jobs, &QTreeWidget::itemSelectionChanged, this, &RenderWidget::slotCheckJob);
    connect(m_view.running_jobs, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotPlayRendering);

    connect(m_view.buttonSave, &QAbstractButton::clicked, this, &RenderWidget::slotSaveProfile);
    connect(m_view.buttonEdit, &QAbstractButton::clicked, this, &RenderWidget::slotEditProfile);
    connect(m_view.buttonDelete, &QAbstractButton::clicked, this, &RenderWidget::slotDeleteProfile);
    connect(m_view.buttonFavorite, &QAbstractButton::clicked, this, &RenderWidget::slotCopyToFavorites);

    connect(m_view.abort_job, &QAbstractButton::clicked, this, &RenderWidget::slotAbortCurrentJob);
    connect(m_view.start_job, &QAbstractButton::clicked, this, &RenderWidget::slotStartCurrentJob);
    connect(m_view.clean_up, &QAbstractButton::clicked, this, &RenderWidget::slotCLeanUpJobs);
    connect(m_view.hide_log, &QAbstractButton::clicked, this, &RenderWidget::slotHideLog);

    connect(m_view.buttonClose, &QAbstractButton::clicked, this, &QWidget::hide);
    connect(m_view.buttonClose2, &QAbstractButton::clicked, this, &QWidget::hide);
    connect(m_view.buttonClose3, &QAbstractButton::clicked, this, &QWidget::hide);
    connect(m_view.rescale, &QAbstractButton::toggled, this, &RenderWidget::setRescaleEnabled);
Laurent Montel's avatar
Laurent Montel committed
260
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
261
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
262

Laurent Montel's avatar
Laurent Montel committed
263 264
    connect(m_view.formats, &QTreeWidget::currentItemChanged, this, &RenderWidget::refreshParams);
    connect(m_view.formats, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotEditItem);
265

Laurent Montel's avatar
Laurent Montel committed
266 267 268
    connect(m_view.render_guide, &QAbstractButton::clicked, this, &RenderWidget::slotUpdateGuideBox);
    connect(m_view.render_zone, &QAbstractButton::clicked, this, &RenderWidget::slotUpdateGuideBox);
    connect(m_view.render_full, &QAbstractButton::clicked, this, &RenderWidget::slotUpdateGuideBox);
269 270 271 272

    connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
    connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));

Laurent Montel's avatar
Laurent Montel committed
273
    connect(m_view.tc_overlay, &QAbstractButton::toggled, m_view.tc_type, &QWidget::setEnabled);
274

Nicolas Carion's avatar
Nicolas Carion committed
275 276
    // m_view.splitter->setStretchFactor(1, 5);
    // m_view.splitter->setStretchFactor(0, 2);
277

278
    m_view.out_file->setMode(KFile::File);
279 280 281 282 283

#if KXMLGUI_VERSION_MINOR > 32 || KXMLGUI_VERSION_MAJOR > 5
    m_view.out_file->setAcceptMode(QFileDialog::AcceptSave);
#endif

284
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
285

286
    m_jobsDelegate = new RenderViewDelegate(this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
287
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
288
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
289

290
    QHeaderView *header = m_view.running_jobs->header();
291
    header->setSectionResizeMode(0, QHeaderView::Fixed);
292
    header->resizeSection(0, size + 4);
293
    header->setSectionResizeMode(1, QHeaderView::Interactive);
294

295
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
296 297
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
298
    header = m_view.scripts_list->header();
299
    header->setSectionResizeMode(0, QHeaderView::Fixed);
300
    header->resizeSection(0, size + 4);
301

Nicolas Carion's avatar
Nicolas Carion committed
302
// Find path for Kdenlive renderer
303 304 305
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
306
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
307
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
308
    if (!QFile::exists(m_renderer)) {
309
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
310
        if (m_renderer.isEmpty()) {
311
            m_renderer = QStringLiteral("kdenlive_render");
312
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
313 314
    }

315
    QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface();
Nicolas Carion's avatar
Nicolas Carion committed
316 317
    if ((interface == nullptr) ||
        (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager")))) {
318
        m_view.shutdown->setEnabled(false);
319
    }
320
    checkCodecs();
321
    refreshView();
322
    focusFirstVisibleItem();
323
    adjustSize();
324 325 326 327 328 329
}

QSize RenderWidget::sizeHint() const
{
    // Make sure the widget has minimum size on opening
    return QSize(200, 200);
330 331
}

332 333 334 335 336 337 338 339
RenderWidget::~RenderWidget()
{
    m_view.running_jobs->blockSignals(true);
    m_view.scripts_list->blockSignals(true);
    m_view.running_jobs->clear();
    m_view.scripts_list->clear();
    delete m_jobsDelegate;
    delete m_scriptsDelegate;
340
    delete m_infoMessage;
341 342
}

343
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
344
{
Laurent Montel's avatar
Laurent Montel committed
345
    if (item->parent() == nullptr) {
346 347 348
        // This is a top level item - group - don't edit
        return;
    }
349
    const QString edit = item->data(0, EditableRole).toString();
350
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml"))) {
Laurent Montel's avatar
Laurent Montel committed
351
        slotSaveProfile();
352 353 354
    } else {
        slotEditProfile();
    }
355 356
}

357 358
void RenderWidget::showInfoPanel()
{
359 360 361 362 363 364 365
    if (m_view.advanced_params->isVisible()) {
        m_view.advanced_params->setVisible(false);
        KdenliveSettings::setShowrenderparams(false);
    } else {
        m_view.advanced_params->setVisible(true);
        KdenliveSettings::setShowrenderparams(true);
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
366 367
}

368
void RenderWidget::setDocumentPath(const QString &path)
369
{
Nicolas Carion's avatar
Nicolas Carion committed
370 371
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile() ==
        QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).toLocalFile()) {
372
        const QString fileName = m_view.out_file->url().fileName();
373
        m_view.out_file->setUrl(QUrl::fromLocalFile(path + fileName));
374
    }
375
    m_projectFolder = path;
376
    parseScriptFiles();
377 378
}

379 380
void RenderWidget::slotUpdateGuideBox()
{
381 382 383
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

384 385
void RenderWidget::slotCheckStartGuidePosition()
{
386
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex()) {
387
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
388
    }
389 390
}

391 392
void RenderWidget::slotCheckEndGuidePosition()
{
393
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex()) {
394
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
395
    }
396 397
}

Laurent Montel's avatar
Laurent Montel committed
398
void RenderWidget::setGuides(const QMap<double, QString> &guidesData, double duration)
399
{
400 401
    m_view.guide_start->clear();
    m_view.guide_end->clear();
402
    if (!guidesData.isEmpty()) {
403
        m_view.guide_start->addItem(i18n("Beginning"), "0");
404
        m_view.render_guide->setEnabled(true);
405 406 407 408 409
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
410
    double fps = ProfileRepository::get()->getProfile(m_profile)->fps();
411 412 413 414 415
    QMapIterator<double, QString> i(guidesData);
    while (i.hasNext()) {
        i.next();
        GenTime pos = GenTime(i.key());
        const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
Laurent Montel's avatar
Laurent Montel committed
416 417
        m_view.guide_start->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
        m_view.guide_end->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
418
    }
419
    if (!guidesData.isEmpty()) {
420
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
421
    }
422 423
}

424
/**
Simon Eugster's avatar
Simon Eugster committed
425 426 427
 * Will be called when the user selects an output file via the file dialog.
 * File extension will be added automatically.
 */
428
void RenderWidget::slotUpdateButtons(const QUrl &url)
429
{
430 431 432 433
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonGenerateScript->setEnabled(false);
        m_view.buttonRender->setEnabled(false);
    } else {
434 435
        updateButtons(); // This also checks whether the selected format is available
    }
436
    if (url.isValid()) {
437
        QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
438
        if ((item == nullptr) || (item->parent() == nullptr)) { // categories have no parent
439 440
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
441 442
            return;
        }
443
        const QString extension = item->data(0, ExtensionRole).toString();
Laurent Montel's avatar
Laurent Montel committed
444
        m_view.out_file->setUrl(filenameWithExtension(url, extension));
445 446 447
    }
}

Simon Eugster's avatar
Simon Eugster committed
448 449 450 451
/**
 * Will be called when the user changes the output file path in the text line.
 * File extension must NOT be added, would make editing impossible!
 */
452 453
void RenderWidget::slotUpdateButtons()
{
454 455 456 457 458 459
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonRender->setEnabled(false);
        m_view.buttonGenerateScript->setEnabled(false);
    } else {
        updateButtons(); // This also checks whether the selected format is available
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
460 461
}

462 463
void RenderWidget::slotSaveProfile()
{
464
    Ui::SaveProfile_UI ui;
465
    QPointer<QDialog> d = new QDialog(this);
466
    ui.setupUi(d);
467

468
    QString customGroup;
469
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
470
    if (!arguments.isEmpty()) {
471
        ui.parameters->setText(arguments.join(QLatin1Char(' ')));
472
    }
473
    ui.profile_name->setFocus();
474
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
475
    if ((item != nullptr) && (item->parent() != nullptr)) { // not a category
476
        // Duplicate current item settings
477 478
        customGroup = item->parent()->text(0);
        ui.extension->setText(item->data(0, ExtensionRole).toString());
479 480
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
481 482 483 484 485 486
                ui.vbitrates_label->setText(i18n("Qualities"));
                ui.default_vbitrate_label->setText(i18n("Default quality"));
            } else {
                ui.vbitrates_label->setText(i18n("Bitrates"));
                ui.default_vbitrate_label->setText(i18n("Default bitrate"));
            }
Nicolas Carion's avatar
Nicolas Carion committed
487
            if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
488
                QStringList bitrates = item->data(0, BitratesRole).toStringList();
489
                ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
490
                if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
491
                    ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
492
                }
493
            }
494 495
        } else {
            ui.vbitrates->setHidden(true);
496
        }
497 498
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
499 500 501 502 503 504
                ui.abitrates_label->setText(i18n("Qualities"));
                ui.default_abitrate_label->setText(i18n("Default quality"));
            } else {
                ui.abitrates_label->setText(i18n("Bitrates"));
                ui.default_abitrate_label->setText(i18n("Default bitrate"));
            }
Nicolas Carion's avatar
Nicolas Carion committed
505 506
            if ((item != nullptr) && item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) &&
                (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
507
                QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
508
                ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
509
                if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
510
                    ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
511
                }
512
            }
513 514
        } else {
            ui.abitrates->setHidden(true);
515
        }
516

Nicolas Carion's avatar
Nicolas Carion committed
517
        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
518 519 520
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
521
    }
522

523 524 525
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
526
    ui.group_name->setText(customGroup);
527

528
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
529 530
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
531 532 533
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
534 535

        QDomDocument doc;
536 537 538 539
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
540
        QString args = ui.parameters->toPlainText().simplified();
541 542
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
543
            // profile has a variable bitrate
544 545 546 547 548
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
        } else if (args.contains(QStringLiteral("%quality"))) {
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
549
        }
550

551
        if (args.contains(QStringLiteral("%audiobitrate"))) {
552
            // profile has a variable bitrate
553 554 555
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
556
            // profile has a variable bitrate
557 558
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
559
        }
560 561 562
        QString speeds_list_str = ui.speeds_list->toPlainText();
        if (!speeds_list_str.isEmpty()) {
            profileElement.setAttribute(QStringLiteral("speeds"), speeds_list_str.replace('\n', ';').simplified());
563
        }
564

565 566 567
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

568
        parseProfiles();
569 570 571 572
    }
    delete d;
}

573
bool RenderWidget::saveProfile(QDomElement newprofile)
574
{
Laurent Montel's avatar
Laurent Montel committed
575
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/"));
576
    if (!dir.exists()) {
577
        dir.mkpath(QStringLiteral("."));
578
    }
579
    QDomDocument doc;
580
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
581 582 583 584
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
585
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
586
        doc.clear();
587 588
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
589 590
        doc.appendChild(profiles);
    }
Laurent Montel's avatar
Laurent Montel committed
591
    int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
592 593
    if (version < 1) {
        doc.clear();
594 595
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
596 597
        doc.appendChild(profiles);
    }
598

599
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
600 601 602
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
603 604 605
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
606
        QString profileName = documentElement.attribute(QStringLiteral("name"));
607 608 609 610 611 612
        existingProfileNames << profileName;
        i++;
    }
    // Check if a profile with that same name already exists
    bool ok;
    while (existingProfileNames.contains(newProfileName)) {
Nicolas Carion's avatar
Nicolas Carion committed
613 614 615
        QString updatedProfileName = QInputDialog::getText(this, i18n("Profile already exists"),
                                                           i18n("This profile name already exists. Change the name if you don't want to overwrite it."),
                                                           QLineEdit::Normal, newProfileName, &ok);
616 617 618
        if (!ok) {
            return false;
        }
619 620 621 622 623 624 625
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
626
        }
627
    }
628

629
    profiles.appendChild(newprofile);
630

Nicolas Carion's avatar
Nicolas Carion committed
631
    // QCString save = doc.toString().utf8();
632

633
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
634
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
635
        return false;
636 637 638 639
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
640
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
641
        file.close();
642
        return false;
643 644
    }
    file.close();
645
    return true;
646 647 648 649
}

void RenderWidget::slotCopyToFavorites()
{
650
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
651
    if ((item == nullptr) || (item->parent() == nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
652
        return;
653
    }
654

655 656 657
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
658
    QDomDocument doc;
659 660 661 662 663 664 665
    QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
    profileElement.setAttribute(QStringLiteral("name"), currentProfile);
    profileElement.setAttribute(QStringLiteral("category"), i18nc("Category Name", "Custom"));
    profileElement.setAttribute(QStringLiteral("destinationid"), QStringLiteral("favorites"));
    profileElement.setAttribute(QStringLiteral("extension"), extension);
    profileElement.setAttribute(QStringLiteral("args"), params);
    if (params.contains(QStringLiteral("%bitrate"))) {
666
        // profile has a variable bitrate
667
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
668
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
669
    } else if (params.contains(QStringLiteral("%quality"))) {
670
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
671
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
672
    }
673
    if (params.contains(QStringLiteral("%audiobitrate"))) {
674
        // profile has a variable bitrate
675
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
676
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
677
    } else if (params.contains(QStringLiteral("%audioquality"))) {
678
        // profile has a variable bitrate
679
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
680
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
681
    }
Nicolas Carion's avatar
Nicolas Carion committed
682
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
683
        // profile has a variable speed
684
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QLatin1Char(';')));
685
    }
686
    doc.appendChild(profileElement);
687
    if (saveProfile(doc.documentElement())) {
688
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
689
    }
690 691
}

692 693
void RenderWidget::slotEditProfile()
{
694
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
695
    if ((item == nullptr) || (item->parent() == nullptr)) {
696 697
        return;
    }
698
    QString params = item->data(0, ParamsRole).toString();
699 700

    Ui::SaveProfile_UI ui;
701
    QPointer<QDialog> d = new QDialog(this);
702
    ui.setupUi(d);
703

704
    QString customGroup = item->parent()->text(0);
705 706 707
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
708 709
    ui.group_name->setText(customGroup);

710 711
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
712 713
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
714 715
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
716 717 718 719 720 721
            ui.vbitrates_label->setText(i18n("Qualities"));
            ui.default_vbitrate_label->setText(i18n("Default quality"));
        } else {
            ui.vbitrates_label->setText(i18n("Bitrates"));
            ui.default_vbitrate_label->setText(i18n("Default bitrate"));
        }
Nicolas Carion's avatar
Nicolas Carion committed
722
        if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
723
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
724
            ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
725
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
726
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
727
            }
728
        }
Laurent Montel's avatar
Laurent Montel committed
729 730
    } else {
        ui.vbitrates->setHidden(true);
731
    }
Laurent Montel's avatar
Laurent Montel committed
732

733 734
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
735 736 737 738 739 740
            ui.abitrates_label->setText(i18n("Qualities"));
            ui.default_abitrate_label->setText(i18n("Default quality"));
        } else {
            ui.abitrates_label->setText(i18n("Bitrates"));
            ui.default_abitrate_label->setText(i18n("Default bitrate"));
        }
Nicolas Carion's avatar
Nicolas Carion committed
741
        if (item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
742
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
743
            ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
744
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
745
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
746
            }
747
        }
748 749
    } else {
        ui.abitrates->setHidden(true);
750
    }
751

Nicolas Carion's avatar
Nicolas Carion committed
752
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
753 754 755 756
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

757
    d->setWindowTitle(i18n("Edit Profile"));
758

759
    if (d->exec() == QDialog::Accepted) {
760
        slotDeleteProfile(false);
761
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/customprofiles.xml");
762 763 764 765 766
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
767 768
        QDomElement profiles = doc.documentElement();

769
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
770
            doc.clear();
771 772
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
773 774 775
            doc.appendChild(profiles);
        }

Laurent Montel's avatar
Laurent Montel committed
776
        int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
777 778
        if (version < 1) {
            doc.clear();
779 780
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
781
            doc.appendChild(profiles);
782 783 784 785
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
786 787 788
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
789
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
790 791 792 793
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
794
            QString profileName = documentElement.attribute(QStringLiteral("name"));
795 796 797
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Nicolas Carion's avatar
Nicolas Carion committed
798 799 800
                newProfileName = QInputDialog::getText(this, i18n("Profile already exists"),
                                                       i18n("This profile name already exists. Change the name if you don't want to overwrite it."),
                                                       QLineEdit::Normal, newProfileName, &ok);
801 802 803
                if (!ok) {
                    return;
                }
804 805
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
806 807 808
                    break;
                }
            }
809
            ++i;
810
        }
811

812 813 814 815
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
816
        QString args = ui.parameters->toPlainText().simplified();
817 818
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
819
            // profile has a variable bitrate
820 821
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
822
        } else if (args.contains(QStringLiteral("%quality"))) {
823 824
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
825
        }
826
        if (args.contains(QStringLiteral("%audiobitrate"))) {
827
            // profile has a variable bitrate
828 829 830 831 832
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
833 834
        }