renderwidget.cpp 125 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

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 <kio_version.h>
Nicolas Carion's avatar
Nicolas Carion committed
38
#include <knotifications_version.h>
39
#include <kns3/downloaddialog.h>
40

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

59 60 61 62 63
#ifdef KF5_USE_PURPOSE
#include <Purpose/AlternativesModel>
#include <PurposeWidgets/Menu>
#endif

Vincent Pinon's avatar
Vincent Pinon committed
64
#include <locale>
65 66 67
#ifdef Q_OS_MAC
#include <xlocale.h>
#endif
68

69
// Render profiles roles
Nicolas Carion's avatar
Nicolas Carion committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
enum {
    GroupRole = Qt::UserRole,
    ExtensionRole,
    StandardRole,
    RenderRole,
    ParamsRole,
    EditableRole,
    ExtraRole,
    BitratesRole,
    DefaultBitrateRole,
    AudioBitratesRole,
    DefaultAudioBitrateRole,
    SpeedsRole,
    ErrorRole
};
85

86 87 88
// Render job roles
const int ParametersRole = Qt::UserRole + 1;
const int TimeRole = Qt::UserRole + 2;
89 90
const int ProgressRole = Qt::UserRole + 3;
const int ExtraInfoRole = Qt::UserRole + 5;
91

92 93
const int DirectRenderType = QTreeWidgetItem::Type;
const int ScriptRenderType = QTreeWidgetItem::UserType;
94

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

98
#ifdef Q_OS_WIN
99
const QLatin1String ScriptFormat(".bat");
Nicolas Carion's avatar
format  
Nicolas Carion committed
100 101 102 103 104 105 106 107
QString ScriptSetVar(const QString name, const QString value)
{
    return QString("set ") + name + "=" + value;
}
QString ScriptGetVar(const QString varName)
{
    return QString('%') + varName + '%';
}
108 109
#else
const QLatin1String ScriptFormat(".sh");
Nicolas Carion's avatar
linting  
Nicolas Carion committed
110
QString ScriptSetVar(const QString &name, const QString &value)
Nicolas Carion's avatar
format  
Nicolas Carion committed
111 112 113
{
    return name + "=\"" + value + '\"';
}
Nicolas Carion's avatar
linting  
Nicolas Carion committed
114
QString ScriptGetVar(const QString &varName)
Nicolas Carion's avatar
format  
Nicolas Carion committed
115 116 117
{
    return QString('$') + varName;
}
118 119
#endif

120 121 122
static QStringList acodecsList;
static QStringList vcodecsList;
static QStringList supportedFormats;
123

124 125 126
RenderJobItem::RenderJobItem(QTreeWidget *parent, const QStringList &strings, int type)
    : QTreeWidgetItem(parent, strings, type)
    , m_status(-1)
127
{
128
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
129 130 131 132 133
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
134
    if (m_status == status) {
Laurent Montel's avatar
Laurent Montel committed
135
        return;
136
    }
137 138
    m_status = status;
    switch (status) {
139
    case WAITINGJOB:
140
        setIcon(0, QIcon::fromTheme(QStringLiteral("media-playback-pause")));
141 142 143 144
        setData(1, Qt::UserRole, i18n("Waiting..."));
        break;
    case FINISHEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering finished"));
145
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-ok")));
146 147 148 149
        setData(1, ProgressRole, 100);
        break;
    case FAILEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering crashed"));
150
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-close")));
151 152 153 154
        setData(1, ProgressRole, 100);
        break;
    case ABORTEDJOB:
        setData(1, Qt::UserRole, i18n("Rendering aborted"));
155
        setIcon(0, QIcon::fromTheme(QStringLiteral("dialog-cancel")));
156 157 158
        setData(1, ProgressRole, 100);
    default:
        break;
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    }
}

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

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

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

177
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, QWidget *parent)
178 179 180
    : QDialog(parent)
    , m_projectFolder(projectfolder)
    , m_blockProcessing(false)
181
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
182
    m_view.setupUi(this);
183 184
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
185

186
    setWindowTitle(i18n("Rendering"));
187 188 189 190
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
191
    m_view.buttonDownload->setIconSize(iconSize);
192

193
    m_view.buttonDelete->setIcon(QIcon::fromTheme(QStringLiteral("trash-empty")));
194 195 196
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

197
    m_view.buttonEdit->setIcon(QIcon::fromTheme(QStringLiteral("document-edit")));
198 199 200
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

201
    m_view.buttonSave->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
202 203
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

204
    m_view.hide_log->setIcon(QIcon::fromTheme(QStringLiteral("go-down")));
205

206
    m_view.buttonFavorite->setIcon(QIcon::fromTheme(QStringLiteral("favorite")));
207
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
208

209 210 211
    m_view.buttonDownload->setIcon(QIcon::fromTheme(QStringLiteral("edit-download")));
    m_view.buttonDownload->setToolTip(i18n("Download New Render Profiles..."));

212
    m_view.out_file->button()->setToolTip(i18n("Select output destination"));
213
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
214

215
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
216
    connect(m_view.options, &QAbstractButton::toggled, m_view.optionsGroup, &QWidget::setVisible);
217
    m_view.videoLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
218
    connect(m_view.options, &QAbstractButton::toggled, m_view.videoLabel, &QWidget::setVisible);
219
    m_view.video->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
220
    connect(m_view.options, &QAbstractButton::toggled, m_view.video, &QWidget::setVisible);
221
    m_view.audioLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
222
    connect(m_view.options, &QAbstractButton::toggled, m_view.audioLabel, &QWidget::setVisible);
223
    m_view.audio->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
224 225
    connect(m_view.options, &QAbstractButton::toggled, m_view.audio, &QWidget::setVisible);
    connect(m_view.quality, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustAVQualities);
226
    connect(m_view.video, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::adjustQuality);
Laurent Montel's avatar
Laurent Montel committed
227
    connect(m_view.speed, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustSpeed);
228

229 230
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
231
    setRescaleEnabled(false);
232 233 234 235 236 237 238
    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);
239
    m_view.proxy_render->setHidden(!enableProxy);
240
    connect(m_view.proxy_render, &QCheckBox::toggled, this, &RenderWidget::slotProxyWarn);
241
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window);
242
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
Nicolas Carion's avatar
Nicolas Carion committed
243 244
    m_view.errorBox->setStyleSheet(
        QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
245
    int height = QFontInfo(font()).pixelSize();
246
    m_view.errorIcon->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-warning")).pixmap(height, height));
247 248 249
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
250
    m_view.info->addWidget(m_infoMessage);
251 252 253
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

254 255 256 257 258
    m_jobInfoMessage = new KMessageWidget;
    m_view.jobInfo->addWidget(m_jobInfoMessage);
    m_jobInfoMessage->setCloseButtonVisible(false);
    m_jobInfoMessage->hide();

259
    m_view.encoder_threads->setMinimum(0);
260
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
261
    m_view.encoder_threads->setToolTip(i18n("Encoding threads (0 is automatic)"));
262
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
263
    connect(m_view.encoder_threads, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::slotUpdateEncodeThreads);
264

265
    m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
266 267
    connect(m_view.rescale_width, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::slotUpdateRescaleWidth);
    connect(m_view.rescale_height, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &RenderWidget::slotUpdateRescaleHeight);
268
    m_view.rescale_keep->setIcon(QIcon::fromTheme(QStringLiteral("edit-link")));
269
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
Laurent Montel's avatar
Laurent Montel committed
270
    connect(m_view.rescale_keep, &QAbstractButton::clicked, this, &RenderWidget::slotSwitchAspectRatio);
271

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

275 276 277 278
    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
279
    connect(m_view.export_audio, &QCheckBox::stateChanged, this, &RenderWidget::slotUpdateAudioLabel);
280 281
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
282
    checkCodecs();
283
    parseProfiles();
284
    parseScriptFiles();
285 286
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
Laurent Montel's avatar
Laurent Montel committed
287 288 289 290 291 292 293 294 295 296
    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);
297
    connect(m_view.buttonDownload, &QAbstractButton::clicked, this, &RenderWidget::slotDownloadNewRenderProfiles);
Laurent Montel's avatar
Laurent Montel committed
298 299 300 301 302 303 304 305 306 307

    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);
Vincent Pinon's avatar
Vincent Pinon committed
308 309
    connect(m_view.out_file, &KUrlRequester::textChanged, this, static_cast<void(RenderWidget::*)()>(&RenderWidget::slotUpdateButtons));
    connect(m_view.out_file, &KUrlRequester::urlSelected, this, static_cast<void(RenderWidget::*)(const QUrl&)>(&RenderWidget::slotUpdateButtons));
310

Laurent Montel's avatar
Laurent Montel committed
311 312
    connect(m_view.formats, &QTreeWidget::currentItemChanged, this, &RenderWidget::refreshParams);
    connect(m_view.formats, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotEditItem);
313

Laurent Montel's avatar
Laurent Montel committed
314 315 316
    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);
317

Vincent Pinon's avatar
Vincent Pinon committed
318 319
    connect(m_view.guide_end, static_cast<void(KComboBox::*)(int)>(&KComboBox::activated), this, &RenderWidget::slotCheckStartGuidePosition);
    connect(m_view.guide_start, static_cast<void(KComboBox::*)(int)>(&KComboBox::activated), this, &RenderWidget::slotCheckEndGuidePosition);
320

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

Nicolas Carion's avatar
Nicolas Carion committed
323 324
    // m_view.splitter->setStretchFactor(1, 5);
    // m_view.splitter->setStretchFactor(0, 2);
325

326
    m_view.out_file->setMode(KFile::File);
Nicolas Carion's avatar
Nicolas Carion committed
327
#if KIO_VERSION >= QT_VERSION_CHECK(5, 33, 0)
328
    m_view.out_file->setAcceptMode(QFileDialog::AcceptSave);
329
#elif !defined(KIOWIDGETS_DEPRECATED)
330
    m_view.out_file->fileDialog()->setAcceptMode(QFileDialog::AcceptSave);
331 332
#endif

333
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
334

335
    m_jobsDelegate = new RenderViewDelegate(this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
336
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
337
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
338

339
    QHeaderView *header = m_view.running_jobs->header();
340
    header->setSectionResizeMode(0, QHeaderView::Fixed);
341
    header->resizeSection(0, size + 4);
342
    header->setSectionResizeMode(1, QHeaderView::Interactive);
343

344
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
345 346
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
347
    header = m_view.scripts_list->header();
348
    header->setSectionResizeMode(0, QHeaderView::Fixed);
349
    header->resizeSection(0, size + 4);
350

Nicolas Carion's avatar
Nicolas Carion committed
351
// Find path for Kdenlive renderer
352 353 354
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
355
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
356
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
357
    if (!QFile::exists(m_renderer)) {
358
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
359
        if (m_renderer.isEmpty()) {
360
            m_renderer = QStringLiteral("kdenlive_render");
361
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
362 363
    }

364
    QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface();
Nicolas Carion's avatar
Nicolas Carion committed
365 366
    if ((interface == nullptr) ||
        (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager")))) {
367
        m_view.shutdown->setEnabled(false);
368
    }
369 370 371 372

#ifdef KF5_USE_PURPOSE
    m_shareMenu = new Purpose::Menu();
    m_view.shareButton->setMenu(m_shareMenu);
373
    m_view.shareButton->setIcon( QIcon::fromTheme(QStringLiteral("document-share")));
374
    connect(m_shareMenu, &Purpose::Menu::finished, this, &RenderWidget::slotShareActionFinished);
375 376 377
#else
    m_view.shareButton->setEnabled(false);
#endif
378 379 380 381
    m_view.parallel_process->setChecked(KdenliveSettings::parallelrender());
    connect(m_view.parallel_process, &QCheckBox::stateChanged, [this] (int state) {
        KdenliveSettings::setParallelrender(state == Qt::Checked);
    });
382
    refreshView();
383
    focusFirstVisibleItem();
384
    adjustSize();
385 386
}

387 388
void RenderWidget::slotShareActionFinished(const QJsonObject &output, int error, const QString &message)
{
389
#ifdef KF5_USE_PURPOSE
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    m_jobInfoMessage->hide();
    if (error) {
        KMessageBox::error(this, i18n("There was a problem sharing the document: %1", message),
                           i18n("Share"));
    } else {
        const QString url = output["url"].toString();
        if (url.isEmpty()) {
            m_jobInfoMessage->setMessageType(KMessageWidget::Positive);
            m_jobInfoMessage->setText(i18n("Document shared successfully"));
            m_jobInfoMessage->show();
        } else {
            KMessageBox::information(this, i18n("You can find the shared document at: <a href=\"%1\">%1</a>", url),
                                     i18n("Share"), QString(),
                                     KMessageBox::Notify | KMessageBox::AllowLink);
        }
    }
#endif
407
}
408

409 410 411 412
QSize RenderWidget::sizeHint() const
{
    // Make sure the widget has minimum size on opening
    return QSize(200, 200);
413 414
}

415 416 417 418 419 420 421 422
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;
423
    delete m_infoMessage;
424
    delete m_jobInfoMessage;
425 426
}

427
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
428
{
Laurent Montel's avatar
Laurent Montel committed
429
    if (item->parent() == nullptr) {
430 431 432
        // This is a top level item - group - don't edit
        return;
    }
433
    const QString edit = item->data(0, EditableRole).toString();
434
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml"))) {
Laurent Montel's avatar
Laurent Montel committed
435
        slotSaveProfile();
436 437 438
    } else {
        slotEditProfile();
    }
439 440
}

441 442
void RenderWidget::showInfoPanel()
{
443 444 445 446 447 448 449
    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
450 451
}

452
void RenderWidget::setDocumentPath(const QString &path)
453
{
Nicolas Carion's avatar
Nicolas Carion committed
454 455
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile() ==
        QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).toLocalFile()) {
456
        const QString fileName = m_view.out_file->url().fileName();
457
        m_view.out_file->setUrl(QUrl::fromLocalFile(QDir(path).absoluteFilePath(fileName)));
458
    }
459
    m_projectFolder = QUrl::fromLocalFile(path).adjusted(QUrl::NormalizePathSegments | QUrl::StripTrailingSlash).toLocalFile() + QDir::separator();
460
    parseScriptFiles();
461 462
}

463 464
void RenderWidget::slotUpdateGuideBox()
{
465 466 467
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

468 469
void RenderWidget::slotCheckStartGuidePosition()
{
470
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex()) {
471
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
472
    }
473 474
}

475 476
void RenderWidget::slotCheckEndGuidePosition()
{
477
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex()) {
478
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
479
    }
480 481
}

482
void RenderWidget::setGuides(const QList<CommentedTime> &guidesList, double duration)
483
{
484 485
    m_view.guide_start->clear();
    m_view.guide_end->clear();
486
    if (!guidesList.isEmpty()) {
487
        m_view.guide_start->addItem(i18n("Beginning"), "0");
488
        m_view.render_guide->setEnabled(true);
489 490 491 492 493
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
494
    double fps = pCore->getCurrentProfile()->fps();
495 496 497
    for (int i = 0; i < guidesList.count(); i++) {
        CommentedTime c = guidesList.at(i);
        GenTime pos = c.time();
498
        const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
499 500
        m_view.guide_start->addItem(c.comment() + QLatin1Char('/') + guidePos, pos.seconds());
        m_view.guide_end->addItem(c.comment() + QLatin1Char('/') + guidePos, pos.seconds());
501
    }
502
    if (!guidesList.isEmpty()) {
503
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
504
    }
505 506
}

507
/**
Simon Eugster's avatar
Simon Eugster committed
508 509 510
 * Will be called when the user selects an output file via the file dialog.
 * File extension will be added automatically.
 */
511
void RenderWidget::slotUpdateButtons(const QUrl &url)
512
{
513 514 515 516
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonGenerateScript->setEnabled(false);
        m_view.buttonRender->setEnabled(false);
    } else {
517 518
        updateButtons(); // This also checks whether the selected format is available
    }
519
    if (url.isValid()) {
520
        QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
521
        if ((item == nullptr) || (item->parent() == nullptr)) { // categories have no parent
522 523
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
524 525
            return;
        }
526
        const QString extension = item->data(0, ExtensionRole).toString();
Laurent Montel's avatar
Laurent Montel committed
527
        m_view.out_file->setUrl(filenameWithExtension(url, extension));
528 529 530
    }
}

Simon Eugster's avatar
Simon Eugster committed
531 532 533 534
/**
 * 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!
 */
535 536
void RenderWidget::slotUpdateButtons()
{
537 538 539 540 541 542
    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
543 544
}

545 546
void RenderWidget::slotSaveProfile()
{
547
    Ui::SaveProfile_UI ui;
548
    QPointer<QDialog> d = new QDialog(this);
549
    ui.setupUi(d);
550

551
    QString customGroup;
552
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
553
    if (!arguments.isEmpty()) {
554
        ui.parameters->setText(arguments.join(QLatin1Char(' ')));
555
    }
556
    ui.profile_name->setFocus();
557
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
558
    if ((item != nullptr) && (item->parent() != nullptr)) { // not a category
559
        // Duplicate current item settings
560 561
        customGroup = item->parent()->text(0);
        ui.extension->setText(item->data(0, ExtensionRole).toString());
562 563
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
564 565 566 567 568 569
                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
570
            if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
571
                QStringList bitrates = item->data(0, BitratesRole).toStringList();
572
                ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
573
                if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
574
                    ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
575
                }
576
            }
577 578
        } else {
            ui.vbitrates->setHidden(true);
579
        }
580 581
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
582 583 584 585 586 587
                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
588 589
            if ((item != nullptr) && item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) &&
                (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
590
                QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
591
                ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
592
                if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
593
                    ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
594
                }
595
            }
596 597
        } else {
            ui.abitrates->setHidden(true);
598
        }
599

Nicolas Carion's avatar
Nicolas Carion committed
600
        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
601 602 603
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
604
    }
605

606 607 608
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
609
    ui.group_name->setText(customGroup);
610

611
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
612 613
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
614 615 616
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
617 618

        QDomDocument doc;
619 620 621 622
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
623
        QString args = ui.parameters->toPlainText().simplified();
624 625
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
626
            // profile has a variable bitrate
627 628 629 630 631
            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());
632
        }
633

634
        if (args.contains(QStringLiteral("%audiobitrate"))) {
635
            // profile has a variable bitrate
636 637 638
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
639
            // profile has a variable bitrate
640 641
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
642
        }
643 644 645
        QString speeds_list_str = ui.speeds_list->toPlainText();
        if (!speeds_list_str.isEmpty()) {
            profileElement.setAttribute(QStringLiteral("speeds"), speeds_list_str.replace('\n', ';').simplified());
646
        }
647

648 649 650
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

651
        parseProfiles();
652 653 654 655
    }
    delete d;
}

656
bool RenderWidget::saveProfile(QDomElement newprofile)
657
{
Laurent Montel's avatar
Laurent Montel committed
658
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/"));
659
    if (!dir.exists()) {
660
        dir.mkpath(QStringLiteral("."));
661
    }
662
    QDomDocument doc;
663
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
664 665 666 667
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
668
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
669
        doc.clear();
670 671
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
672 673
        doc.appendChild(profiles);
    }
Laurent Montel's avatar
Laurent Montel committed
674
    int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
675 676
    if (version < 1) {
        doc.clear();
677 678
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
679 680
        doc.appendChild(profiles);
    }
681

682
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
683 684 685
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
686 687 688
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
689
        QString profileName = documentElement.attribute(QStringLiteral("name"));
690 691 692 693 694 695
        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
696 697 698
        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);
699 700 701
        if (!ok) {
            return false;
        }
702 703 704 705 706 707 708
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
709
        }
710
    }
711

712
    profiles.appendChild(newprofile);
713

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

716
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
717
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
718
        return false;
719 720 721 722
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
723
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
724
        file.close();
725
        return false;
726 727
    }
    file.close();
728
    return true;
729 730 731 732
}

void RenderWidget::slotCopyToFavorites()
{
733
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
734
    if ((item == nullptr) || (item->parent() == nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
735
        return;
736
    }
737

738 739 740
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
741
    QDomDocument doc;
742 743 744 745 746 747 748
    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"))) {
749
        // profile has a variable bitrate
750
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
751
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
752
    } else if (params.contains(QStringLiteral("%quality"))) {
753
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
754
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
755
    }
756
    if (params.contains(QStringLiteral("%audiobitrate"))) {
757
        // profile has a variable bitrate
758
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
759
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
760
    } else if (params.contains(QStringLiteral("%audioquality"))) {
761
        // profile has a variable bitrate
762
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
763
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
764
    }
Nicolas Carion's avatar
Nicolas Carion committed
765
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
766
        // profile has a variable speed
767
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QLatin1Char(';')));
768
    }
769
    doc.appendChild(profileElement);
770
    if (saveProfile(doc.documentElement())) {
771
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
772
    }
773 774
}

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
void RenderWidget::slotDownloadNewRenderProfiles()
{
    if (getNewStuff(QStringLiteral(":data/kdenlive_renderprofiles.knsrc")) > 0) {
        reloadProfiles();
    }
}

int RenderWidget::getNewStuff(const QString &configFile)
{
    KNS3::Entry::List entries;
    QPointer<KNS3::DownloadDialog> dialog = new KNS3::DownloadDialog(configFile);
    if (dialog->exec() != 0) {
        entries = dialog->changedEntries();
    }
    for (const KNS3::Entry &entry : entries) {
        if (entry.status() == KNS3::Entry::Installed) {
            qCDebug(KDENLIVE_LOG) << "// Installed files: " << entry.installedFiles();
        }
    }
    delete dialog;
    return entries.size();
}

798 799
void RenderWidget::slotEditProfile()
{
800
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
801
    if ((item == nullptr) || (item->parent() == nullptr)) {
802 803
        return;
    }
804
    QString params = item->data(0, ParamsRole).toString();
805 806

    Ui::SaveProfile_UI ui;
807
    QPointer<QDialog> d = new QDialog(this);
808
    ui.setupUi(d);
809

810
    QString customGroup = item->parent()->text(0);
811 812 813
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
814 815
    ui.group_name->setText(customGroup);

816 817
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
818 819
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
820 821
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
822 823 824 825 826 827
            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
828
        if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
829
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
830
            ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
831
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
832
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
833
            }
834
        }
Laurent Montel's avatar
Laurent Montel committed
835 836
    } else {
        ui.vbitrates->setHidden(true);
837
    }
Laurent Montel's avatar
Laurent Montel committed
838

839 840
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
Vincent Pinon's avatar