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

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

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

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

60
// Render profiles roles
61 62 63 64 65 66 67 68 69 70
enum {GroupRole = Qt::UserRole,
      ExtensionRole,
      StandardRole,
      RenderRole,
      ParamsRole,
      EditableRole,
      ExtraRole,
      BitratesRole,
      DefaultBitrateRole,
      AudioBitratesRole,
71
      DefaultAudioBitrateRole,
72
      SpeedsRole,
73
      ErrorRole
74
     };
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
86 87 88 89 90 91 92 93
enum JOBSTATUS {
    WAITINGJOB = 0,
    STARTINGJOB,
    RUNNINGJOB,
    FINISHEDJOB,
    FAILEDJOB,
    ABORTEDJOB
};
94

95 96 97
static QStringList acodecsList;
static QStringList vcodecsList;
static QStringList supportedFormats;
98

99
RenderJobItem::RenderJobItem(QTreeWidget *parent, const QStringList &strings, int type)
Laurent Montel's avatar
Laurent Montel committed
100
    : QTreeWidgetItem(parent, strings, type),
101
      m_status(-1)
102
{
103
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
104 105 106 107 108
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
109
    if (m_status == status) {
Laurent Montel's avatar
Laurent Montel committed
110
        return;
111
    }
112 113
    m_status = status;
    switch (status) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    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;
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    }
}

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

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

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

152
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const QString &profile, QWidget *parent) :
153 154 155 156
    QDialog(parent),
    m_projectFolder(projectfolder),
    m_profile(profile),
    m_blockProcessing(false)
157
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
158
    m_view.setupUi(this);
159 160
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
161

162
    setWindowTitle(i18n("Rendering"));
163 164 165 166
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
167

168
    m_view.buttonDelete->setIcon(KoIconUtils::themedIcon(QStringLiteral("trash-empty")));
169 170 171
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

172
    m_view.buttonEdit->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-edit")));
173 174 175
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

176
    m_view.buttonSave->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-new")));
177 178
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

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

181
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
182
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
183

184
    m_view.out_file->button()->setToolTip(i18n("Select output destination"));
185
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
186

187
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
188
    connect(m_view.options, &QAbstractButton::toggled, m_view.optionsGroup, &QWidget::setVisible);
189
    m_view.videoLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
190
    connect(m_view.options, &QAbstractButton::toggled, m_view.videoLabel, &QWidget::setVisible);
191
    m_view.video->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
192
    connect(m_view.options, &QAbstractButton::toggled, m_view.video, &QWidget::setVisible);
193
    m_view.audioLabel->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
194
    connect(m_view.options, &QAbstractButton::toggled, m_view.audioLabel, &QWidget::setVisible);
195
    m_view.audio->setVisible(m_view.options->isChecked());
Laurent Montel's avatar
Laurent Montel committed
196 197
    connect(m_view.options, &QAbstractButton::toggled, m_view.audio, &QWidget::setVisible);
    connect(m_view.quality, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustAVQualities);
198
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
Laurent Montel's avatar
Laurent Montel committed
199
    connect(m_view.speed, &QAbstractSlider::valueChanged, this, &RenderWidget::adjustSpeed);
200

201 202
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
203
    setRescaleEnabled(false);
204 205 206 207 208 209 210
    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);
211
    m_view.proxy_render->setHidden(!enableProxy);
212
    connect(m_view.proxy_render, &QCheckBox::toggled, this, &RenderWidget::slotProxyWarn);
213 214
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
215
    m_view.errorBox->setStyleSheet(QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
216
    int height = QFontInfo(font()).pixelSize();
217
    m_view.errorIcon->setPixmap(KoIconUtils::themedIcon(QStringLiteral("dialog-warning")).pixmap(height, height));
218 219 220
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
221
    m_view.info->addWidget(m_infoMessage);
222 223 224
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

225 226 227 228
    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)));

229 230 231
    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)));
232
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
233
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
Laurent Montel's avatar
Laurent Montel committed
234
    connect(m_view.rescale_keep, &QAbstractButton::clicked, this, &RenderWidget::slotSwitchAspectRatio);
235

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

239 240 241 242
    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
243
    connect(m_view.export_audio, &QCheckBox::stateChanged, this, &RenderWidget::slotUpdateAudioLabel);
244 245
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

246
    parseProfiles();
247
    parseScriptFiles();
248 249
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
Laurent Montel's avatar
Laurent Montel committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    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
270
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
271
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
272

Laurent Montel's avatar
Laurent Montel committed
273 274
    connect(m_view.formats, &QTreeWidget::currentItemChanged, this, &RenderWidget::refreshParams);
    connect(m_view.formats, &QTreeWidget::itemDoubleClicked, this, &RenderWidget::slotEditItem);
275

Laurent Montel's avatar
Laurent Montel committed
276 277 278
    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);
279 280 281 282

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

285 286
    //m_view.splitter->setStretchFactor(1, 5);
    //m_view.splitter->setStretchFactor(0, 2);
287

288
    m_view.out_file->setMode(KFile::File);
289 290 291 292 293

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

294
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
295

296
    m_jobsDelegate = new RenderViewDelegate(this);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
297
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
298
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
299

300
    QHeaderView *header = m_view.running_jobs->header();
301
    header->setSectionResizeMode(0, QHeaderView::Fixed);
302
    header->resizeSection(0, size + 4);
303
    header->setSectionResizeMode(1, QHeaderView::Interactive);
304

305
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
306 307
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
308
    header = m_view.scripts_list->header();
309
    header->setSectionResizeMode(0, QHeaderView::Fixed);
310
    header->resizeSection(0, size + 4);
311

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
312
    // Find path for Kdenlive renderer
313 314 315
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
316
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
317
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
318
    if (!QFile::exists(m_renderer)) {
319
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
320
        if (m_renderer.isEmpty()) {
321
            m_renderer = QStringLiteral("kdenlive_render");
322
        }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
323 324
    }

325
    QDBusConnectionInterface *interface = QDBusConnection::sessionBus().interface();
Nicolas Carion's avatar
Nicolas Carion committed
326
    if ((interface == nullptr) || (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager")))) {
327
        m_view.shutdown->setEnabled(false);
328
    }
329
    checkCodecs();
330
    refreshView();
331
    focusFirstVisibleItem();
332
    adjustSize();
333 334 335 336 337 338
}

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

341 342 343 344 345 346 347 348
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;
349
    delete m_infoMessage;
350 351
}

352
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
353
{
Laurent Montel's avatar
Laurent Montel committed
354
    if (item->parent() == nullptr) {
355 356 357
        // This is a top level item - group - don't edit
        return;
    }
358
    const QString edit = item->data(0, EditableRole).toString();
359
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml"))) {
Laurent Montel's avatar
Laurent Montel committed
360
        slotSaveProfile();
361 362 363
    } else {
        slotEditProfile();
    }
364 365
}

366 367
void RenderWidget::showInfoPanel()
{
368 369 370 371 372 373 374
    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
375 376
}

377
void RenderWidget::setDocumentPath(const QString &path)
378
{
379
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).toLocalFile() == QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).toLocalFile()) {
380
        const QString fileName = m_view.out_file->url().fileName();
381
        m_view.out_file->setUrl(QUrl::fromLocalFile(path + fileName));
382
    }
383
    m_projectFolder = path;
384
    parseScriptFiles();
385

386 387
}

388 389
void RenderWidget::slotUpdateGuideBox()
{
390 391 392
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

393 394
void RenderWidget::slotCheckStartGuidePosition()
{
395
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex()) {
396
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
397
    }
398 399
}

400 401
void RenderWidget::slotCheckEndGuidePosition()
{
402
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex()) {
403
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
404
    }
405 406
}

Laurent Montel's avatar
Laurent Montel committed
407
void RenderWidget::setGuides(const QMap<double, QString> &guidesData, double duration)
408
{
409 410
    m_view.guide_start->clear();
    m_view.guide_end->clear();
411
    if (!guidesData.isEmpty()) {
412
        m_view.guide_start->addItem(i18n("Beginning"), "0");
413
        m_view.render_guide->setEnabled(true);
414 415 416 417 418
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
419
    double fps = ProfileRepository::get()->getProfile(m_profile)->fps();
420 421 422 423 424
    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
425 426
        m_view.guide_start->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
        m_view.guide_end->addItem(i.value() + QLatin1Char('/') + guidePos, i.key());
427
    }
428
    if (!guidesData.isEmpty()) {
429
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
430
    }
431 432
}

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

Simon Eugster's avatar
Simon Eugster committed
457 458 459 460
/**
 * 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!
 */
461 462
void RenderWidget::slotUpdateButtons()
{
463 464 465 466 467 468
    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
469 470
}

471 472
void RenderWidget::slotSaveProfile()
{
473
    Ui::SaveProfile_UI ui;
474
    QPointer<QDialog> d = new QDialog(this);
475
    ui.setupUi(d);
476

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

Nicolas Carion's avatar
Nicolas Carion committed
525
        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
526 527 528
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
529
    }
530

531 532 533
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
534
    ui.group_name->setText(customGroup);
535

536
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
537 538
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
539 540 541
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
542 543

        QDomDocument doc;
544 545 546 547
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
548
        QString args = ui.parameters->toPlainText().simplified();
549 550
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
551
            // profile has a variable bitrate
552 553 554 555 556
            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());
557
        }
558

559
        if (args.contains(QStringLiteral("%audiobitrate"))) {
560
            // profile has a variable bitrate
561 562 563
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
564
            // profile has a variable bitrate
565 566
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
567
        }
568 569 570
        QString speeds_list_str = ui.speeds_list->toPlainText();
        if (!speeds_list_str.isEmpty()) {
            profileElement.setAttribute(QStringLiteral("speeds"), speeds_list_str.replace('\n', ';').simplified());
571
        }
572

573 574 575
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

576
        parseProfiles();
577 578 579 580
    }
    delete d;
}

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

607
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
608 609 610
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
611 612 613
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
614
        QString profileName = documentElement.attribute(QStringLiteral("name"));
615 616 617 618 619 620 621
        existingProfileNames << profileName;
        i++;
    }
    // Check if a profile with that same name already exists
    bool ok;
    while (existingProfileNames.contains(newProfileName)) {
        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);
622 623 624
        if (!ok) {
            return false;
        }
625 626 627 628 629 630 631
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
632
        }
633
    }
634

635
    profiles.appendChild(newprofile);
636

637
    //QCString save = doc.toString().utf8();
638

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

void RenderWidget::slotCopyToFavorites()
{
656
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
657
    if ((item == nullptr) || (item->parent() == nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
658
        return;
659
    }
660

661 662 663
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
664
    QDomDocument doc;
665 666 667 668 669 670 671
    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"))) {
672
        // profile has a variable bitrate
673
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
674
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
675
    } else if (params.contains(QStringLiteral("%quality"))) {
676
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
677
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QLatin1Char(',')));
678
    }
679
    if (params.contains(QStringLiteral("%audiobitrate"))) {
680
        // profile has a variable bitrate
681
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
682
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
683
    } else if (params.contains(QStringLiteral("%audioquality"))) {
684
        // profile has a variable bitrate
685
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
686
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QLatin1Char(',')));
687
    }
Nicolas Carion's avatar
Nicolas Carion committed
688
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
689
        // profile has a variable speed
690
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QLatin1Char(';')));
691
    }
692
    doc.appendChild(profileElement);
693
    if (saveProfile(doc.documentElement())) {
694
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
695
    }
696 697
}

698 699
void RenderWidget::slotEditProfile()
{
700
    QTreeWidgetItem *item = m_view.formats->currentItem();
Nicolas Carion's avatar
Nicolas Carion committed
701
    if ((item == nullptr) || (item->parent() == nullptr)) {
702 703
        return;
    }
704
    QString params = item->data(0, ParamsRole).toString();
705 706

    Ui::SaveProfile_UI ui;
707
    QPointer<QDialog> d = new QDialog(this);
708
    ui.setupUi(d);
709

710
    QString customGroup = item->parent()->text(0);
711 712 713
    if (customGroup.isEmpty()) {
        customGroup = i18nc("Group Name", "Custom");
    }
714 715
    ui.group_name->setText(customGroup);

716 717
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
718 719
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
720 721
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
722 723 724 725 726 727
            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
728
        if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && (item->data(0, BitratesRole).toStringList().count() != 0)) {
729
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
730
            ui.vbitrates_list->setText(bitrates.join(QLatin1Char(',')));
731
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String)) {
732
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
733
            }
734
        }
Laurent Montel's avatar
Laurent Montel committed
735 736
    } else {
        ui.vbitrates->setHidden(true);
737
    }
Laurent Montel's avatar
Laurent Montel committed
738

739 740
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
741 742 743 744 745 746
            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
747
        if (item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && (item->data(0, AudioBitratesRole).toStringList().count() != 0)) {
748
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
749
            ui.abitrates_list->setText(bitrates.join(QLatin1Char(',')));
750
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String)) {
751
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
752
            }
753
        }
754 755
    } else {
        ui.abitrates->setHidden(true);
756
    }
757

Nicolas Carion's avatar
Nicolas Carion committed
758
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && (item->data(0, SpeedsRole).toStringList().count() != 0)) {
759 760 761 762
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

763
    d->setWindowTitle(i18n("Edit Profile"));
764

765
    if (d->exec() == QDialog::Accepted) {
766
        slotDeleteProfile(false);
767
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/export/customprofiles.xml");
768 769 770 771 772
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
773 774
        QDomElement profiles = doc.documentElement();

775
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
776
            doc.clear();
777 778
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
779 780 781
            doc.appendChild(profiles);
        }

Laurent Montel's avatar
Laurent Montel committed
782
        int version = profiles.attribute(QStringLiteral("version"), nullptr).toInt();
783 784
        if (version < 1) {
            doc.clear();
785 786
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
787
            doc.appendChild(profiles);
788 789 790 791
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
792 793 794
        if (newGroupName.isEmpty()) {
            newGroupName = i18nc("Group Name", "Custom");
        }
795
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
796 797 798 799
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
800
            QString profileName = documentElement.attribute(QStringLiteral("name"));
801 802 803
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
804
                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);
805 806 807
                if (!ok) {
                    return;
                }
808 809
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
810 811 812
                    break;
                }
            }
813
            ++i;
814
        }
815

816 817 818 819
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
820
        QString args = ui.parameters->toPlainText().simplified();
821 822
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
823
            // profile has a variable bitrate
824 825
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());