Members of the KDE Community are recommended to subscribe to the kde-community mailing list at https://mail.kde.org/mailman/listinfo/kde-community to allow them to participate in important discussions and receive other important announcements

renderwidget.cpp 121 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
linting  
Nicolas Carion committed
21
#include "core.h"
Nicolas Carion's avatar
Nicolas Carion committed
22
#include "dialogs/profilesdialog.h"
23
#include "kdenlivesettings.h"
Nicolas Carion's avatar
Nicolas Carion committed
24 25
#include "profiles/profilemodel.hpp"
#include "profiles/profilerepository.hpp"
26
#include "timecode.h"
Nicolas Carion's avatar
Nicolas Carion committed
27
#include "ui_saveprofile_ui.h"
28
#include "utils/KoIconUtils.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
29

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

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

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

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

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

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

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

90
#ifdef Q_OS_WIN
91
const QLatin1String ScriptFormat(".bat");
Nicolas Carion's avatar
format  
Nicolas Carion committed
92 93 94 95 96 97 98 99
QString ScriptSetVar(const QString name, const QString value)
{
    return QString("set ") + name + "=" + value;
}
QString ScriptGetVar(const QString varName)
{
    return QString('%') + varName + '%';
}
100 101
#else
const QLatin1String ScriptFormat(".sh");
Nicolas Carion's avatar
linting  
Nicolas Carion committed
102
QString ScriptSetVar(const QString &name, const QString &value)
Nicolas Carion's avatar
format  
Nicolas Carion committed
103 104 105
{
    return name + "=\"" + value + '\"';
}
Nicolas Carion's avatar
linting  
Nicolas Carion committed
106
QString ScriptGetVar(const QString &varName)
Nicolas Carion's avatar
format  
Nicolas Carion committed
107 108 109
{
    return QString('$') + varName;
}
110 111
#endif

112 113 114
static QStringList acodecsList;
static QStringList vcodecsList;
static QStringList supportedFormats;
115

116 117 118
RenderJobItem::RenderJobItem(QTreeWidget *parent, const QStringList &strings, int type)
    : QTreeWidgetItem(parent, strings, type)
    , m_status(-1)
119
{
120
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
121 122 123 124 125
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
126
    if (m_status == status) {
Laurent Montel's avatar
Laurent Montel committed
127
        return;
128
    }
129 130
    m_status = status;
    switch (status) {
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    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;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    }
}

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

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

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

169
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, QWidget *parent)
170 171 172
    : QDialog(parent)
    , m_projectFolder(projectfolder)
    , m_blockProcessing(false)
173
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
174
    m_view.setupUi(this);
175 176
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
177

178
    setWindowTitle(i18n("Rendering"));
179 180 181 182
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
183

184
    m_view.buttonDelete->setIcon(KoIconUtils::themedIcon(QStringLiteral("trash-empty")));
185 186 187
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

188
    m_view.buttonEdit->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-edit")));
189 190 191
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

192
    m_view.buttonSave->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-new")));
193 194
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

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

197
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
198
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
199

200
    m_view.out_file->button()->setToolTip(i18n("Select output destination"));
201
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
202

203
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
204
    connect(m_view.options, &QAbstractButton::toggled, m_view.optionsGroup, &QWidget::setVisible);
205
    m_view.videoLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
206
    connect(m_view.options, &QAbstractButton::toggled, m_view.videoLabel, &QWidget::setVisible);
207
    m_view.video->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
208
    connect(m_view.options, &QAbstractButton::toggled, m_view.video, &QWidget::setVisible);
209
    m_view.audioLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
210
    connect(m_view.options, &QAbstractButton::toggled, m_view.audioLabel, &QWidget::setVisible);
211
    m_view.audio->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
212 213
    connect(m_view.options, &QAbstractButton::toggled, m_view.audio, &QWidget::setVisible);
    connect(m_view.quality, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustAVQualities);
214
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
Laurent Montel's avatar
Laurent Montel committed
215
    connect(m_view.speed, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustSpeed);
216

217 218
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
219
    setRescaleEnabled(false);
220 221 222 223 224 225 226
    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);
227
    m_view.proxy_render->setHidden(!enableProxy);
228
    connect(m_view.proxy_render, &QCheckBox::toggled, this, &RenderWidget::slotProxyWarn);
229 230
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
Nicolas Carion's avatar
Nicolas Carion committed
231 232
    m_view.errorBox->setStyleSheet(
        QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
233
    int height = QFontInfo(font()).pixelSize();
234
    m_view.errorIcon->setPixmap(KoIconUtils::themedIcon(QStringLiteral("dialog-warning")).pixmap(height, height));
235 236 237
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
238
    m_view.info->addWidget(m_infoMessage);
239 240 241
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

242
    m_view.encoder_threads->setMinimum(0);
243
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
244
    m_view.encoder_threads->setToolTip(i18n("Encoding threads (0 is automatic)"));
245 246 247
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
    connect(m_view.encoder_threads, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateEncodeThreads(int)));

248 249 250
    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)));
251
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
252
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
Laurent Montel's avatar
Laurent Montel committed
253
    connect(m_view.rescale_keep, &QAbstractButton::clicked, this, &RenderWidget::slotSwitchAspectRatio);
254

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

258 259 260 261
    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
262
    connect(m_view.export_audio, &QCheckBox::stateChanged, this, &RenderWidget::slotUpdateAudioLabel);
263 264
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

265
    parseProfiles();
266
    parseScriptFiles();
267 268
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
Laurent Montel's avatar
Laurent Montel committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    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
289
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
290
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
291

Laurent Montel's avatar
Laurent Montel committed
292 293
    connect(m_view.formats, &QTreeWidget::currentItemChanged, this, &RenderWidget::refreshParams);
    connect(m_view.formats, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotEditItem);
294

Laurent Montel's avatar
Laurent Montel committed
295 296 297
    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);
298 299 300 301

    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
302
    connect(m_view.tc_overlay, &QAbstractButton::toggled, m_view.tc_type, &QWidget::setEnabled);
303

Nicolas Carion's avatar
Nicolas Carion committed
304 305
    // m_view.splitter->setStretchFactor(1, 5);
    // m_view.splitter->setStretchFactor(0, 2);
306

307
    m_view.out_file->setMode(KFile::File);
308
#if KIO_VERSION >= QT_VERSION_CHECK(5,33,0)
309
    m_view.out_file->setAcceptMode(QFileDialog::AcceptSave);
310
#elif !defined(KIOWIDGETS_DEPRECATED)
311
    m_view.out_file->fileDialog()->setAcceptMode(QFileDialog::AcceptSave);
312 313
#endif

314
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
315

316
    m_jobsDelegate = new RenderViewDelegate(this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
317
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
318
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
319

320
    QHeaderView *header = m_view.running_jobs->header();
321
    header->setSectionResizeMode(0, QHeaderView::Fixed);
322
    header->resizeSection(0, size + 4);
323
    header->setSectionResizeMode(1, QHeaderView::Interactive);
324

325
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
326 327
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
328
    header = m_view.scripts_list->header();
329
    header->setSectionResizeMode(0, QHeaderView::Fixed);
330
    header->resizeSection(0, size + 4);
331

Nicolas Carion's avatar
Nicolas Carion committed
332
// Find path for Kdenlive renderer
333 334 335
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
336
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
337
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
338
    if (!QFile::exists(m_renderer)) {
339
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
340
        if (m_renderer.isEmpty()) {
341
            m_renderer = QStringLiteral("kdenlive_render");
342
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
343 344
    }

345
    QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface();
Nicolas Carion's avatar
Nicolas Carion committed
346 347
    if ((interface == nullptr) ||
        (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager")))) {
348
        m_view.shutdown->setEnabled(false);
349
    }
350
    checkCodecs();
351
    refreshView();
352
    focusFirstVisibleItem();
353
    adjustSize();
354 355 356 357 358 359
}

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

362 363 364 365 366 367 368 369
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;
370
    delete m_infoMessage;
371 372
}

373
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
374
{
Laurent Montel's avatar
Laurent Montel committed
375
    if (item->parent() == nullptr) {
376 377 378
        // This is a top level item - group - don't edit
        return;
    }
379
    const QString edit = item->data(0, EditableRole).toString();
380
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml"))) {
Laurent Montel's avatar
Laurent Montel committed
381
        slotSaveProfile();
382 383 384
    } else {
        slotEditProfile();
    }
385 386
}

387 388
void RenderWidget::showInfoPanel()
{
389 390 391 392 393 394 395
    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
396 397
}

398
void RenderWidget::setDocumentPath(const QString &path)
399
{
Nicolas Carion's avatar
Nicolas Carion committed
400 401
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile() ==
        QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).toLocalFile()) {
402
        const QString fileName = m_view.out_file->url().fileName();
403
        m_view.out_file->setUrl(QUrl::fromLocalFile(path + fileName));
404
    }
405
    m_projectFolder = path;
406
    parseScriptFiles();
407 408
}

409 410
void RenderWidget::slotUpdateGuideBox()
{
411 412 413
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

414 415
void RenderWidget::slotCheckStartGuidePosition()
{
416
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex()) {
417
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
418
    }
419 420
}

421 422
void RenderWidget::slotCheckEndGuidePosition()
{
423
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex()) {
424
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
425
    }
426 427
}

428
void RenderWidget::setGuides(const QList<CommentedTime> &guidesList, double duration)
429
{
430 431
    m_view.guide_start->clear();
    m_view.guide_end->clear();
432
    if (!guidesList.isEmpty()) {
433
        m_view.guide_start->addItem(i18n("Beginning"), "0");
434
        m_view.render_guide->setEnabled(true);
435 436 437 438 439
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
440
    double fps = pCore->getCurrentProfile()->fps();
441 442 443
    for (int i = 0; i < guidesList.count(); i++) {
        CommentedTime c = guidesList.at(i);
        GenTime pos = c.time();
444
        const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
445 446
        m_view.guide_start->addItem(c.comment() + QLatin1Char('/') + guidePos, pos.seconds());
        m_view.guide_end->addItem(c.comment() + QLatin1Char('/') + guidePos, pos.seconds());
447
    }
448
    if (!guidesList.isEmpty()) {
449
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
450
    }
451 452
}

453
/**
Simon Eugster's avatar
Simon Eugster committed
454 455 456
 * Will be called when the user selects an output file via the file dialog.
 * File extension will be added automatically.
 */
457
void RenderWidget::slotUpdateButtons(const QUrl &url)
458
{
459 460 461 462
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonGenerateScript->setEnabled(false);
        m_view.buttonRender->setEnabled(false);
    } else {
463 464
        updateButtons(); // This also checks whether the selected format is available
    }
465
    if (url.isValid()) {
466
        QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
467
        if ((item == nullptr) || (item->parent() == nullptr)) { // categories have no parent
468 469
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
470 471
            return;
        }
472
        const QString extension = item->data(0, ExtensionRole).toString();
Laurent Montel's avatar
Laurent Montel committed
473
        m_view.out_file->setUrl(filenameWithExtension(url, extension));
474 475 476
    }
}

Simon Eugster's avatar
Simon Eugster committed
477 478 479 480
/**
 * 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!
 */
481 482
void RenderWidget::slotUpdateButtons()
{
483 484 485 486 487 488
    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
489 490
}

491 492
void RenderWidget::slotSaveProfile()
{
493
    Ui::SaveProfile_UI ui;
494
    QPointer<QDialog> d = new QDialog(this);
495
    ui.setupUi(d);
496

497
    QString customGroup;
498
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
499
    if (!arguments.isEmpty()) {
500
        ui.parameters->setText(arguments.join(QLatin1Char(' ')));
501
    }
502
    ui.profile_name->setFocus();
503
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
504
    if ((item != nullptr) && (item->parent() != nullptr)) { // not a category
505
        // Duplicate current item settings
506 507
        customGroup = item->parent()->text(0);
        ui.extension->setText(item->data(0, ExtensionRole).toString());
508 509
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
510 511 512 513 514 515
                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
516
            if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
517
                QStringList bitrates = item->data(0, BitratesRole).toStringList();
518
                ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
519
                if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
520
                    ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
521
                }
522
            }
523 524
        } else {
            ui.vbitrates->setHidden(true);
525
        }
526 527
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
528 529 530 531 532 533
                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
534 535
            if ((item != nullptr) && item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) &&
                (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
536
                QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
537
                ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
538
                if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
539
                    ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
540
                }
541
            }
542 543
        } else {
            ui.abitrates->setHidden(true);
544
        }
545

Nicolas Carion's avatar
Nicolas Carion committed
546
        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
547 548 549
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
550
    }
551

552 553 554
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
555
    ui.group_name->setText(customGroup);
556

557
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
558 559
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
560 561 562
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
563 564

        QDomDocument doc;
565 566 567 568
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
569
        QString args = ui.parameters->toPlainText().simplified();
570 571
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
572
            // profile has a variable bitrate
573 574 575 576 577
            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());
578
        }
579

580
        if (args.contains(QStringLiteral("%audiobitrate"))) {
581
            // profile has a variable bitrate
582 583 584
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
585
            // profile has a variable bitrate
586 587
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
588
        }
589 590 591
        QString speeds_list_str = ui.speeds_list->toPlainText();
        if (!speeds_list_str.isEmpty()) {
            profileElement.setAttribute(QStringLiteral("speeds"), speeds_list_str.replace('\n', ';').simplified());
592
        }
593

594 595 596
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

597
        parseProfiles();
598 599 600 601
    }
    delete d;
}

602
bool RenderWidget::saveProfile(QDomElement newprofile)
603
{
Laurent Montel's avatar
Laurent Montel committed
604
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/"));
605
    if (!dir.exists()) {
606
        dir.mkpath(QStringLiteral("."));
607
    }
608
    QDomDocument doc;
609
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
610 611 612 613
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
614
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
615
        doc.clear();
616 617
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
618 619
        doc.appendChild(profiles);
    }
Laurent Montel's avatar
Laurent Montel committed
620
    int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
621 622
    if (version < 1) {
        doc.clear();
623 624
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
625 626
        doc.appendChild(profiles);
    }
627

628
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
629 630 631
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
632 633 634
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
635
        QString profileName = documentElement.attribute(QStringLiteral("name"));
636 637 638 639 640 641
        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
642 643 644
        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);
645 646 647
        if (!ok) {
            return false;
        }
648 649 650 651 652 653 654
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
655
        }
656
    }
657

658
    profiles.appendChild(newprofile);
659

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

662
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
663
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
664
        return false;
665 666 667 668
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
669
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
670
        file.close();
671
        return false;
672 673
    }
    file.close();
674
    return true;
675 676 677 678
}

void RenderWidget::slotCopyToFavorites()
{
679
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
680
    if ((item == nullptr) || (item->parent() == nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
681
        return;
682
    }
683

684 685 686
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
687
    QDomDocument doc;
688 689 690 691 692 693 694
    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"))) {
695
        // profile has a variable bitrate
696
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
697
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
698
    } else if (params.contains(QStringLiteral("%quality"))) {
699
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
700
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
701
    }
702
    if (params.contains(QStringLiteral("%audiobitrate"))) {
703
        // profile has a variable bitrate
704
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
705
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
706
    } else if (params.contains(QStringLiteral("%audioquality"))) {
707
        // profile has a variable bitrate
708
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
709
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
710
    }
Nicolas Carion's avatar
Nicolas Carion committed
711
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
712
        // profile has a variable speed
713
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QLatin1Char(';')));
714
    }
715
    doc.appendChild(profileElement);
716
    if (saveProfile(doc.documentElement())) {
717
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
718
    }
719 720
}

721 722
void RenderWidget::slotEditProfile()
{
723
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
724
    if ((item == nullptr) || (item->parent() == nullptr)) {
725 726
        return;
    }
727
    QString params = item->data(0, ParamsRole).toString();
728 729

    Ui::SaveProfile_UI ui;
730
    QPointer<QDialog> d = new QDialog(this);
731
    ui.setupUi(d);
732

733
    QString customGroup = item->parent()->text(0);
734 735 736
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
737 738
    ui.group_name->setText(customGroup);

739 740
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
741 742
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
743 744
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
745 746 747 748 749 750
            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
751
        if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
752
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
753
            ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
754
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
755
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
756
            }
757
        }
Laurent Montel's avatar
Laurent Montel committed
758 759
    } else {
        ui.vbitrates->setHidden(true);
760
    }
Laurent Montel's avatar
Laurent Montel committed
761

762 763
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
764 765 766 767 768 769
            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
770
        if (item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
771
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
772
            ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
773
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
774
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
775
            }
776
        }
777 778
    } else {
        ui.abitrates->setHidden(true);
779
    }
780

Nicolas Carion's avatar
Nicolas Carion committed
781
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
782 783 784 785
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

786
    d->setWindowTitle(i18n("Edit Profile"));
787

788
    if (d->exec() == QDialog::Accepted) {
789
        slotDeleteProfile(false);
790
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/customprofiles.xml");
791 792 793 794 795
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
796 797
        QDomElement profiles = doc.documentElement();

798
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
799
            doc.clear();
800 801
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
802 803 804
            doc.appendChild(profiles);
        }

Laurent Montel's avatar
Laurent Montel committed
805
        int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
806 807
        if (version < 1) {
            doc.clear();
808 809
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
810
            doc.appendChild(profiles);
811 812 813 814
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
815 816 817
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
818
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
819 820 821 822
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
823
            QString profileName = documentElement.attribute(QStringLiteral("name"));
824 825 826
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Nicolas Carion's avatar
Nicolas Carion committed
827 828 829
                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);
830 831 832
                if (!ok) {
                    return;
                }
833 834
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));