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
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 <QStandardPaths>
Nicolas Carion's avatar
Nicolas Carion committed
48 49 50 51 52
#include <QThread>
#include <QTimer>
#include <QTreeWidgetItem>
#include <qglobal.h>
#include <qstring.h>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
53

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

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

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

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

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

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

110 111 112
static QStringList acodecsList;
static QStringList vcodecsList;
static QStringList supportedFormats;
113

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

241 242 243 244
    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)));

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
289 290
    connect(m_view.formats, &QTreeWidget::currentItemChanged, this, &RenderWidget::refreshParams);
    connect(m_view.formats, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotEditItem);
291

Laurent Montel's avatar
Laurent Montel committed
292 293 294
    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);
295 296 297 298

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

Nicolas Carion's avatar
Nicolas Carion committed
301 302
    // m_view.splitter->setStretchFactor(1, 5);
    // m_view.splitter->setStretchFactor(0, 2);
303

304
    m_view.out_file->setMode(KFile::File);
305 306 307

#if KXMLGUI_VERSION_MINOR > 32 || KXMLGUI_VERSION_MAJOR > 5
    m_view.out_file->setAcceptMode(QFileDialog::AcceptSave);
308 309
#elif !defined(KIOWIDGETS_NO_DEPRECATED)
    m_view.out_file->fileDialog()->setAcceptMode(QFileDialog::AcceptSave);
310 311
#endif

312
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
313

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

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

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

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

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

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

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

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

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

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
426
void RenderWidget::setGuides(const QMap<double, QString> &guidesData, double duration)
427
{
428 429
    m_view.guide_start->clear();
    m_view.guide_end->clear();
430
    if (!guidesData.isEmpty()) {
431
        m_view.guide_start->addItem(i18n("Beginning"), "0");
432
        m_view.render_guide->setEnabled(true);
433 434 435 436 437
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
438
    double fps = ProfileRepository::get()->getProfile(m_profile)->fps();
439 440 441 442 443
    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
444 445
        m_view.guide_start->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
        m_view.guide_end->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
446
    }
447
    if (!guidesData.isEmpty()) {
448
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
449
    }
450 451
}

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

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

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

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

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

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

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

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

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

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

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

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

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

657
    profiles.appendChild(newprofile);
658

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

840 841 842 843
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
844
        QString args = ui.parameters->toPlainText().simplified();