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

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

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

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

58 59

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

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

81 82
const int DirectRenderType = QTreeWidgetItem::Type;
const int ScriptRenderType = QTreeWidgetItem::UserType;
83 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

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

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

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

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

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


Laurent Montel's avatar
Laurent Montel committed
152
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const MltVideoProfile &profile, QWidget * parent) :
153
        QDialog(parent),
154
        m_projectFolder(projectfolder),
155
        m_profile(profile),
156
        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 188 189 190 191 192 193 194 195 196 197 198
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.optionsGroup, SLOT(setVisible(bool)));
    m_view.videoLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.videoLabel, SLOT(setVisible(bool)));
    m_view.video->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.video, SLOT(setVisible(bool)));
    m_view.audioLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audioLabel, SLOT(setVisible(bool)));
    m_view.audio->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audio, SLOT(setVisible(bool)));
    connect(m_view.quality, SIGNAL(valueChanged(int)), this, SLOT(adjustAVQualities(int)));
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
199
    connect(m_view.speed, SIGNAL(valueChanged(int)), this, SLOT(adjustSpeed(int)));
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 234
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
    connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
235

236 237 238
    connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
    connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));

239 240 241 242
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

243 244 245
    connect(m_view.export_audio, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateAudioLabel(int)));
    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);
250 251
    connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
    connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
252 253
    connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
    connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
Laurent Montel's avatar
Laurent Montel committed
254
    connect(m_view.running_jobs, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotPlayRendering(QTreeWidgetItem*,int)));
255

256
    connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
257
    connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
258
    connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
259 260
    connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));

261
    connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
262
    connect(m_view.start_job, SIGNAL(clicked()), this, SLOT(slotStartCurrentJob()));
263 264 265
    connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
    connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));

266 267
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
268
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
269
    connect(m_view.rescale, SIGNAL(toggled(bool)), this, SLOT(setRescaleEnabled(bool)));
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

273 274
    connect(m_view.formats, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(refreshParams()));
    connect(m_view.formats, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotEditItem(QTreeWidgetItem*)));
275

276 277 278 279 280 281 282
    connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));

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

283
    connect(m_view.tc_overlay, SIGNAL(toggled(bool)), m_view.tc_type, SLOT(setEnabled(bool)));
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
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
290

291
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
292 293
    m_jobsDelegate = new RenderViewDelegate(this);
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
294

295
    QHeaderView *header = m_view.running_jobs->header();
296
    header->setSectionResizeMode(0, QHeaderView::Fixed);
297
    header->resizeSection(0, size + 4);
298
    header->setSectionResizeMode(1, QHeaderView::Interactive);
299

300
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
301 302
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
303
    header = m_view.scripts_list->header();
304
    header->setSectionResizeMode(0, QHeaderView::Fixed);
305
    header->resizeSection(0, size + 4);
306

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
307
    // Find path for Kdenlive renderer
308 309 310
#ifdef Q_OS_WIN
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render.exe");
#else
311
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
312
#endif
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
313
    if (!QFile::exists(m_renderer)) {
314
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
Laurent Montel's avatar
Laurent Montel committed
315
        if (m_renderer.isEmpty())
316
            m_renderer = QStringLiteral("kdenlive_render");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
317 318
    }

319
    QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
320
    if (!interface || (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager"))))
321
        m_view.shutdown->setEnabled(false);
322
    checkCodecs();
323
    refreshView();
324
    focusFirstVisibleItem();
325
    adjustSize();
326 327 328 329 330 331
}

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

334 335 336 337 338 339 340 341
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;
342
    delete m_infoMessage;
343 344
}

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

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

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

377 378
}

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

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

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

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

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

Simon Eugster's avatar
Simon Eugster committed
445 446 447 448
/**
 * 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!
 */
449 450
void RenderWidget::slotUpdateButtons()
{
451 452 453 454 455 456
    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
457 458
}

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

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

        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
513
    }
514

515 516
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
    ui.group_name->setText(customGroup);
517

518
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
519 520
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
521
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
522 523

        QDomDocument doc;
524 525 526 527
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
528
        QString args = ui.parameters->toPlainText().simplified();
529 530
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
531
            // profile has a variable bitrate
532 533 534 535 536
            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());
537
        }
538

539
        if (args.contains(QStringLiteral("%audiobitrate"))) {
540
            // profile has a variable bitrate
541 542 543
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
544
            // profile has a variable bitrate
545 546
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
547
        }
548
        if (!ui.speeds_list->toPlainText().isEmpty()) {
549 550
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
551

552 553 554
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

555
        parseProfiles();
556 557 558 559 560
    }
    delete d;
}


561
bool RenderWidget::saveProfile(QDomElement newprofile)
562
{
563
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/export/");
564
    if (!dir.exists()) {
565
        dir.mkpath(QStringLiteral("."));
566
    }
567
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/export/customprofiles.xml";
568
    QDomDocument doc;
569
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
570 571 572 573
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
574
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
575
        doc.clear();
576 577
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
578 579
        doc.appendChild(profiles);
    }
580
    int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
581 582
    if (version < 1) {
        doc.clear();
583 584
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
585 586
        doc.appendChild(profiles);
    }
587

588

589
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
590 591 592
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
593 594 595
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
596
        QString profileName = documentElement.attribute(QStringLiteral("name"));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        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);
        if (!ok) return false;
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
612
        }
613
    }
614

615
    profiles.appendChild(newprofile);
616

617
    //QCString save = doc.toString().utf8();
618

619
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
620
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
621
        return false;
622 623 624 625
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
626
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
627
        file.close();
628
        return false;
629 630
    }
    file.close();
631
    return true;
632 633 634 635
}

void RenderWidget::slotCopyToFavorites()
{
636 637
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent())
Laurent Montel's avatar
Laurent Montel committed
638
        return;
639
    QString currentGroup = item->parent()->text(0);
640

641 642 643
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
644
    QDomDocument doc;
645 646 647 648 649 650 651
    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"))) {
652
        // profile has a variable bitrate
653 654
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
655
    } else if (params.contains(QStringLiteral("%quality"))) {
656 657
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
658
    }
659
    if (params.contains(QStringLiteral("%audiobitrate"))) {
660
        // profile has a variable bitrate
661 662
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
663
    } else if (params.contains(QStringLiteral("%audioquality"))) {
664
        // profile has a variable bitrate
665 666 667
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
    }
668
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
669 670
        // profile has a variable speed
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QStringLiteral(";")));
671
    }
672
    doc.appendChild(profileElement);
673
    if (saveProfile(doc.documentElement())) {
674
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
675
    }
676 677
}

678 679
void RenderWidget::slotEditProfile()
{
680 681 682
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentGroup = item->parent()->text(0);
683

684
    QString params = item->data(0, ParamsRole).toString();
685 686

    Ui::SaveProfile_UI ui;
687
    QPointer<QDialog> d = new QDialog(this);
688
    ui.setupUi(d);
689

690
    QString customGroup = item->parent()->text(0);
Yuri Chornoivan's avatar
Yuri Chornoivan committed
691
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
692 693
    ui.group_name->setText(customGroup);

694 695
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
696 697
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
698 699
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.contains(QStringLiteral("%quality"))) {
700 701 702 703 704 705
            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"));
        }
706 707
        if ( item->data(0, BitratesRole).canConvert(QVariant::StringList) && item->data(0, BitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
708
            ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
709 710
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String))
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
711
        }
Laurent Montel's avatar
Laurent Montel committed
712 713
    } else {
        ui.vbitrates->setHidden(true);
714
    }
Laurent Montel's avatar
Laurent Montel committed
715

716 717
    if (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
718 719 720 721 722 723
            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"));
        }
724 725
        if ( item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && item->data(0, AudioBitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
726
            ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
727 728
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String))
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
729 730 731
        }
    }
    else ui.abitrates->setHidden(true);
732 733 734 735 736 737

    if ( item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

738
    d->setWindowTitle(i18n("Edit Profile"));
739

740
    if (d->exec() == QDialog::Accepted) {
741
        slotDeleteProfile(false);
742
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/export/customprofiles.xml";
743 744 745 746 747
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
748 749
        QDomElement profiles = doc.documentElement();

750
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
751
            doc.clear();
752 753
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
754 755 756
            doc.appendChild(profiles);
        }

757
        int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
758 759
        if (version < 1) {
            doc.clear();
760 761
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
762
            doc.appendChild(profiles);
763 764 765 766
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
767
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
768
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
769 770 771 772
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
773
            QString profileName = documentElement.attribute(QStringLiteral("name"));
774 775 776
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
777
                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);
778 779 780
                if (!ok) return;
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
781 782 783
                    break;
                }
            }
784
            ++i;
785
        }
786

787 788 789 790
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
791
        QString args = ui.parameters->toPlainText().simplified();
792 793
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
794
            // profile has a variable bitrate
795 796 797 798 799
            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());
800
        }
801
        if (args.contains(QStringLiteral("%audiobitrate"))) {
802
            // profile has a variable bitrate
803 804 805 806 807
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
808 809
        }

810
        if (!ui.speeds_list->toPlainText().isEmpty()) {
811 812 813
            // profile has a variable speed
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
814

815
        profiles.appendChild(profileElement);
816 817

        //QCString save = doc.toString().utf8();
818
        delete d;
819
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
820
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
821 822 823 824
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
825 826 827 828 829
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
            return;
        }
830
        file.close();
831
        parseProfiles();
832
    } else delete d;
833 834
}

835 836
void RenderWidget::slotDeleteProfile(bool refresh)
{
837 838
    //TODO: delete a profile installed by KNewStuff the easy way
    /*
839
    QString edit = m_view.formats->currentItem()->data(EditableRole).toString();
840
    if (!edit.endsWith(QLatin1String("customprofiles.xml"))) {
841
        // This is a KNewStuff installed file, process through KNS
842 843 844 845 846 847
        KNS::Engine engine(0);
        if (engine.init("kdenlive_render.knsrc")) {
            KNS::Entry::List entries;
        }
        return;
    }*/
848 849 850 851
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentProfile = item->text(0);
    QString currentGroup = item->parent()->text(0);
852

853
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/export/customprofiles.xml";
854 855 856 857 858 859
    QDomDocument doc;
    QFile file</